Index: 3rdParty_sources/opensaml/org/opensaml/Configuration.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/Configuration.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/Configuration.java 17 Aug 2012 15:04:55 -0000 1.1 @@ -0,0 +1,110 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml; + +import org.joda.time.chrono.ISOChronology; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; +import org.opensaml.saml1.binding.artifact.SAML1ArtifactBuilderFactory; +import org.opensaml.saml2.binding.artifact.SAML2ArtifactBuilderFactory; + +/** + * OpenSAML configuration singleton. + * + * The library must be initialized with a set of configurations prior to usage. This is often done by invoking + * {@link DefaultBootstrap#bootstrap()} but may done in any manner so long as all the needed object providers and + * artifact factory are created and registered with the configuration. + */ +public class Configuration extends org.opensaml.xml.Configuration { + + /** Date format in SAML object, default is yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. */ + private static String defaultDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; + + /** Formatter used to write dates. */ + private static DateTimeFormatter dateFormatter; + + /** SAML 1 Artifact factory. */ + private static SAML1ArtifactBuilderFactory saml1ArtifactBuilderFactory; + + /** SAML 2 Artifact factory. */ + private static SAML2ArtifactBuilderFactory saml2ArtifactBuilderFactory; + + /** + * Gets the date format used to string'ify SAML's {@link org.joda.time.DateTime} objects. + * + * @return date format used to string'ify date objects + */ + public static DateTimeFormatter getSAMLDateFormatter() { + if (dateFormatter == null) { + DateTimeFormatter formatter = DateTimeFormat.forPattern(defaultDateFormat); + dateFormatter = formatter.withChronology(ISOChronology.getInstanceUTC()); + } + + return dateFormatter; + } + + /** + * Sets the date format used to string'ify SAML's date/time objects. + * + * See the + * {@link SimpleDateFormat} + * documentation for format syntax. + * + * @param format date format used to string'ify date objects + */ + public static void setSAMLDateFormat(String format) { + DateTimeFormatter formatter = DateTimeFormat.forPattern(format); + dateFormatter = formatter.withChronology(ISOChronology.getInstanceUTC()); + } + + /** + * Gets the artifact factory for the library. + * + * @return artifact factory for the library + */ + public static SAML1ArtifactBuilderFactory getSAML1ArtifactBuilderFactory() { + return saml1ArtifactBuilderFactory; + } + + /** + * Sets the artifact factory for the library. + * + * @param factory artifact factory for the library + */ + public static void setSAML1ArtifactBuilderFactory(SAML1ArtifactBuilderFactory factory) { + saml1ArtifactBuilderFactory = factory; + } + + /** + * Gets the artifact factory for the library. + * + * @return artifact factory for the library + */ + public static SAML2ArtifactBuilderFactory getSAML2ArtifactBuilderFactory() { + return saml2ArtifactBuilderFactory; + } + + /** + * Sets the artifact factory for the library. + * + * @param factory artifact factory for the library + */ + public static void setSAML2ArtifactBuilderFactory(SAML2ArtifactBuilderFactory factory) { + saml2ArtifactBuilderFactory = factory; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/DefaultBootstrap.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/DefaultBootstrap.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/DefaultBootstrap.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,223 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml; + +import org.apache.velocity.app.Velocity; +import org.apache.velocity.runtime.RuntimeConstants; +import org.apache.xml.security.Init; +import org.opensaml.saml1.binding.artifact.SAML1ArtifactBuilderFactory; +import org.opensaml.saml2.binding.artifact.SAML2ArtifactBuilderFactory; +import org.opensaml.xml.ConfigurationException; +import org.opensaml.xml.XMLConfigurator; +import org.opensaml.xml.parse.StaticBasicParserPool; +import org.opensaml.xml.parse.XMLParserException; +import org.opensaml.xml.security.DefaultSecurityConfigurationBootstrap; +import org.owasp.esapi.ESAPI; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class can be used to bootstrap the OpenSAML library with the default configurations that ship with the library. + */ +public class DefaultBootstrap { + + /** List of default XMLTooling configuration files. */ + private static String[] xmlToolingConfigs = { + "/default-config.xml", + "/schema-config.xml", + "/signature-config.xml", + "/signature-validation-config.xml", + "/encryption-config.xml", + "/encryption-validation-config.xml", + "/soap11-config.xml", + "/wsfed11-protocol-config.xml", + "/saml1-assertion-config.xml", + "/saml1-protocol-config.xml", + "/saml1-core-validation-config.xml", + "/saml2-assertion-config.xml", + "/saml2-protocol-config.xml", + "/saml2-core-validation-config.xml", + "/saml1-metadata-config.xml", + "/saml2-metadata-config.xml", + "/saml2-metadata-validation-config.xml", + "/saml2-metadata-attr-config.xml", + "/saml2-metadata-idp-discovery-config.xml", + "/saml2-metadata-ui-config.xml", + "/saml2-protocol-thirdparty-config.xml", + "/saml2-metadata-query-config.xml", + "/saml2-assertion-delegation-restriction-config.xml", + "/saml2-ecp-config.xml", + "/xacml10-saml2-profile-config.xml", + "/xacml11-saml2-profile-config.xml", + "/xacml20-context-config.xml", + "/xacml20-policy-config.xml", + "/xacml2-saml2-profile-config.xml", + "/xacml3-saml2-profile-config.xml", + "/wsaddressing-config.xml", + "/wssecurity-config.xml", + }; + + /** Constructor. */ + protected DefaultBootstrap() { + + } + + /** + * Initializes the OpenSAML library, loading default configurations. + * + * @throws ConfigurationException thrown if there is a problem initializing the OpenSAML library + */ + public static synchronized void bootstrap() throws ConfigurationException { + + initializeXMLSecurity(); + + initializeVelocity(); + + initializeXMLTooling(xmlToolingConfigs); + + initializeArtifactBuilderFactories(); + + initializeGlobalSecurityConfiguration(); + + initializeParserPool(); + + initializeESAPI(); + } + + /** + * Initializes the OWASPI ESAPI library. + */ + protected static void initializeESAPI() { + ESAPI.initialize("org.opensaml.ESAPISecurityConfig"); + } + + /** + * Initializes the default global parser pool instance. + * + *

+ * The ParserPool configured by default here is an instance of + * {@link StaticBasicParserPool}, with a maxPoolSize property of 50 + * and all other properties with default values. + *

+ * + *

+ * If a deployment wishes to use a different parser pool implementation, + * or one configured with different characteristics, they may either override this method, + * or simply configure a different ParserPool after bootstrapping via + * {@link Configuration#setParserPool(org.opensaml.xml.parse.ParserPool)}. + *

+ * + * @throws ConfigurationException thrown if there is a problem initializing the parser pool + */ + protected static void initializeParserPool() throws ConfigurationException { + StaticBasicParserPool pp = new StaticBasicParserPool(); + pp.setMaxPoolSize(50); + try { + pp.initialize(); + } catch (XMLParserException e) { + throw new ConfigurationException("Error initializing parser pool", e); + } + Configuration.setParserPool(pp); + } + + /** + * Initializes the default global security configuration. + */ + protected static void initializeGlobalSecurityConfiguration() { + Configuration.setGlobalSecurityConfiguration(DefaultSecurityConfigurationBootstrap.buildDefaultConfig()); + } + + /** + * Initializes the Apache XMLSecurity libary. + * + * @throws ConfigurationException thrown is there is a problem initializing the library + */ + protected static void initializeXMLSecurity() throws ConfigurationException { + Logger log = getLogger(); + String lineBreakPropName = "org.apache.xml.security.ignoreLineBreaks"; + // Don't override if it was set explicitly + if (System.getProperty(lineBreakPropName) == null) { + System.setProperty(lineBreakPropName, "true"); + } + if (!Init.isInitialized()) { + log.debug("Initializing Apache XMLSecurity library"); + Init.init(); + } + } + + /** + * Intializes the Apache Velocity template engine. + * + * @throws ConfigurationException thrown if there is a problem initializing Velocity + */ + protected static void initializeVelocity() throws ConfigurationException { + Logger log = getLogger(); + try { + log.debug("Initializing Velocity template engine"); + Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, + "org.apache.velocity.runtime.log.NullLogChute"); + Velocity.setProperty(RuntimeConstants.ENCODING_DEFAULT, "UTF-8"); + Velocity.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); + Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); + Velocity.setProperty("classpath.resource.loader.class", + "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + Velocity.init(); + } catch (Exception e) { + throw new ConfigurationException("Unable to initialize Velocity template engine", e); + } + } + + /** + * Initializes the XMLTooling library with a default set of object providers. + * + * @param providerConfigs list of provider configuration files located on the classpath + * + * @throws ConfigurationException thrown if there is a problem loading the configuration files + */ + protected static void initializeXMLTooling(String[] providerConfigs) throws ConfigurationException { + Logger log = getLogger(); + Class clazz = Configuration.class; + XMLConfigurator configurator = new XMLConfigurator(); + + for (String config : providerConfigs) { + log.debug("Loading XMLTooling configuration {}", config); + configurator.load(clazz.getResourceAsStream(config)); + } + } + + /** + * Initializes the artifact factories for SAML 1 and SAML 2 artifacts. + * + * @throws ConfigurationException thrown if there is a problem initializing the artifact factory + */ + protected static void initializeArtifactBuilderFactories() throws ConfigurationException { + Logger log = getLogger(); + log.debug("Initializing SAML Artifact builder factories"); + Configuration.setSAML1ArtifactBuilderFactory(new SAML1ArtifactBuilderFactory()); + Configuration.setSAML2ArtifactBuilderFactory(new SAML2ArtifactBuilderFactory()); + } + + /** + * Get an SLF4J Logger. + * + * @return a Logger instance + */ + protected static Logger getLogger() { + return LoggerFactory.getLogger(DefaultBootstrap.class); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/ESAPISecurityConfig.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/ESAPISecurityConfig.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/ESAPISecurityConfig.java 17 Aug 2012 15:04:55 -0000 1.1 @@ -0,0 +1,372 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml; + +import java.io.File; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.regex.Pattern; + +import org.owasp.esapi.SecurityConfiguration; + +/** + * Minimal implementation of OWASP ESAPI {@link SecurityConfiguration}, providing the support used within OpenSAML. + */ +public class ESAPISecurityConfig implements SecurityConfiguration { + + /** Constructor. */ + public ESAPISecurityConfig() { + } + + /** {@inheritDoc} */ + public String getAccessControlImplementation() { + return null; + } + + /** {@inheritDoc} */ + public List getAdditionalAllowedCipherModes() { + return null; + } + + /** {@inheritDoc} */ + public List getAllowedExecutables() { + return null; + } + + /** {@inheritDoc} */ + public List getAllowedFileExtensions() { + return null; + } + + /** {@inheritDoc} */ + public int getAllowedFileUploadSize() { + return 0; + } + + /** {@inheritDoc} */ + public int getAllowedLoginAttempts() { + return 0; + } + + /** {@inheritDoc} */ + public boolean getAllowMixedEncoding() { + return false; + } + + /** {@inheritDoc} */ + public boolean getAllowMultipleEncoding() { + return false; + } + + /** {@inheritDoc} */ + public String getApplicationName() { + return null; + } + + /** {@inheritDoc} */ + public String getAuthenticationImplementation() { + return null; + } + + /** {@inheritDoc} */ + public String getCharacterEncoding() { + return null; + } + + /** {@inheritDoc} */ + public String getCipherTransformation() { + return null; + } + + /** {@inheritDoc} */ + public List getCombinedCipherModes() { + return null; + } + + /** {@inheritDoc} */ + public List getDefaultCanonicalizationCodecs() { + return null; + } + + /** {@inheritDoc} */ + public String getDigitalSignatureAlgorithm() { + return null; + } + + /** {@inheritDoc} */ + public int getDigitalSignatureKeyLength() { + return 0; + } + + /** {@inheritDoc} */ + public boolean getDisableIntrusionDetection() { + return false; + } + + /** {@inheritDoc} */ + public String getEncoderImplementation() { + return "org.owasp.esapi.reference.DefaultEncoder"; + } + + /** {@inheritDoc} */ + public String getEncryptionAlgorithm() { + return null; + } + + /** {@inheritDoc} */ + public String getEncryptionImplementation() { + return null; + } + + /** {@inheritDoc} */ + public int getEncryptionKeyLength() { + return 0; + } + + /** {@inheritDoc} */ + public String getExecutorImplementation() { + return null; + } + + /** {@inheritDoc} */ + public String getFixedIV() { + return null; + } + + /** {@inheritDoc} */ + public boolean getForceHttpOnlyCookies() { + return false; + } + + /** {@inheritDoc} */ + public boolean getForceHttpOnlySession() { + return false; + } + + /** {@inheritDoc} */ + public boolean getForceSecureCookies() { + return false; + } + + /** {@inheritDoc} */ + public boolean getForceSecureSession() { + return false; + } + + /** {@inheritDoc} */ + public String getHashAlgorithm() { + return null; + } + + /** {@inheritDoc} */ + public int getHashIterations() { + return 0; + } + + /** {@inheritDoc} */ + public String getHttpSessionIdName() { + return null; + } + + /** {@inheritDoc} */ + public String getHTTPUtilitiesImplementation() { + return null; + } + + /** {@inheritDoc} */ + public String getIntrusionDetectionImplementation() { + return null; + } + + /** {@inheritDoc} */ + public String getIVType() { + return null; + } + + /** {@inheritDoc} */ + public String getKDFPseudoRandomFunction() { + return null; + } + + /** {@inheritDoc} */ + public boolean getLenientDatesAccepted() { + return false; + } + + /** {@inheritDoc} */ + public boolean getLogApplicationName() { + return false; + } + + /** {@inheritDoc} */ + public boolean getLogEncodingRequired() { + return false; + } + + /** {@inheritDoc} */ + public String getLogFileName() { + return null; + } + + /** {@inheritDoc} */ + public String getLogImplementation() { + return "org.owasp.esapi.reference.JavaLogFactory"; + } + + /** {@inheritDoc} */ + public int getLogLevel() { + return 0; + } + + /** {@inheritDoc} */ + public boolean getLogServerIP() { + return false; + } + + /** {@inheritDoc} */ + public byte[] getMasterKey() { + return null; + } + + /** {@inheritDoc} */ + public byte[] getMasterSalt() { + return null; + } + + /** {@inheritDoc} */ + public int getMaxHttpHeaderSize() { + return 0; + } + + /** {@inheritDoc} */ + public int getMaxLogFileSize() { + return 0; + } + + /** {@inheritDoc} */ + public int getMaxOldPasswordHashes() { + return 0; + } + + /** {@inheritDoc} */ + public String getPasswordParameterName() { + return null; + } + + /** {@inheritDoc} */ + public String getPreferredJCEProvider() { + return null; + } + + /** {@inheritDoc} */ + public Threshold getQuota(String eventName) { + return null; + } + + /** {@inheritDoc} */ + public String getRandomAlgorithm() { + return null; + } + + /** {@inheritDoc} */ + public String getRandomizerImplementation() { + return null; + } + + /** {@inheritDoc} */ + public long getRememberTokenDuration() { + return 0; + } + + /** {@inheritDoc} */ + public File getResourceFile(String filename) { + return null; + } + + /** {@inheritDoc} */ + public InputStream getResourceStream(String filename) throws IOException { + return null; + } + + /** {@inheritDoc} */ + public String getResponseContentType() { + return null; + } + + /** {@inheritDoc} */ + public int getSessionAbsoluteTimeoutLength() { + return 0; + } + + /** {@inheritDoc} */ + public int getSessionIdleTimeoutLength() { + return 0; + } + + /** {@inheritDoc} */ + public File getUploadDirectory() { + return null; + } + + /** {@inheritDoc} */ + public File getUploadTempDirectory() { + return null; + } + + /** {@inheritDoc} */ + public String getUsernameParameterName() { + return null; + } + + /** {@inheritDoc} */ + public String getValidationImplementation() { + return null; + } + + /** {@inheritDoc} */ + public Pattern getValidationPattern(String typeName) { + return null; + } + + /** {@inheritDoc} */ + public File getWorkingDirectory() { + return null; + } + + /** {@inheritDoc} */ + public boolean overwritePlainText() { + return false; + } + + /** {@inheritDoc} */ + public String setCipherTransformation(String cipherXform) { + return null; + } + + /** {@inheritDoc} */ + public void setResourceDirectory(String dir) { + } + + /** {@inheritDoc} */ + public boolean useMACforCipherText() { + return false; + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/Version.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/Version.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/Version.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,105 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml; + +/** Class for printing the version of this library. */ +public final class Version { + + /** Name of the library. */ + private static final String NAME; + + /** Library version. */ + private static final String VERSION; + + /** Library major version number. */ + private static final int MAJOR_VERSION; + + /** Library minor version number. */ + private static final int MINOR_VERSION; + + /** Library micro version number. */ + private static final int MICRO_VERSION; + + /** Constructor. */ + private Version() { + } + + /** + * Main entry point to program. + * + * @param args command line arguments + */ + public static void main(String[] args) { + System.out.println(NAME + " version " + VERSION); + } + + /** + * Gets the name of the library. + * + * @return name of the library + */ + public static String getName() { + return NAME; + } + + /** + * Gets the version of the library. + * + * @return version of the library + */ + public static String getVersion() { + return VERSION; + } + + /** + * Gets the major version number of the library. + * + * @return major version number of the library + */ + public static int getMajorVersion() { + return MAJOR_VERSION; + } + + /** + * Gets the minor version number of the library. + * + * @return minor version number of the library + */ + public static int getMinorVersion() { + return MINOR_VERSION; + } + + /** + * Gets the micro version number of the library. + * + * @return micro version number of the library + */ + public static int getMicroVersion() { + return MICRO_VERSION; + } + + static { + Package pkg = Version.class.getPackage(); + NAME = pkg.getImplementationTitle().intern(); + VERSION = pkg.getImplementationVersion().intern(); + String[] versionParts = VERSION.split("\\."); + MAJOR_VERSION = Integer.parseInt(versionParts[0]); + MINOR_VERSION = Integer.parseInt(versionParts[1]); + MICRO_VERSION = Integer.parseInt(versionParts[2]); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/SourceID.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/SourceID.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/SourceID.java 17 Aug 2012 15:04:56 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml1md; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.schema.XSString; + +/** + * SAML 1 Metadata extension SourceID + */ +public interface SourceID extends SAMLObject, XSString { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "SourceID"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1MD_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/package.html 17 Aug 2012 15:04:55 -0000 1.1 @@ -0,0 +1,12 @@ + + +Interfaces for SAML 1 metadata profile. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/SourceIDBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/SourceIDBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/SourceIDBuilder.java 17 Aug 2012 15:05:00 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml1md.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.samlext.saml1md.SourceID; + +/** + * Builder of {@link SourceIDImpl} objects. + */ +public class SourceIDBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor */ + public SourceIDBuilder() { + + } + + /** {@inheritDoc} */ + public SourceID buildObject() { + return buildObject(SAMLConstants.SAML1MD_NS, SourceID.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1MD_PREFIX); + } + + /** {@inheritDoc} */ + public SourceID buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SourceIDImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/SourceIDImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/SourceIDImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/SourceIDImpl.java 17 Aug 2012 15:05:00 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml1md.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.samlext.saml1md.SourceID; +import org.opensaml.xml.XMLObject; + +public class SourceIDImpl extends AbstractSAMLObject implements SourceID { + + /** Source ID */ + private String sourceID; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SourceIDImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getValue() { + return sourceID; + } + + /** {@inheritDoc} */ + public void setValue(String newSourceID) { + sourceID = prepareForAssignment(sourceID, newSourceID); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // no children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/SourceIDMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/Attic/SourceIDMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/SourceIDMarshaller.java 17 Aug 2012 15:05:00 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml1md.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.samlext.saml1md.SourceID; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller of {@link SourceID} objects. + */ +public class SourceIDMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + SourceID sourceID = (SourceID) xmlObject; + + if (!DatatypeHelper.isEmpty(sourceID.getValue())) { + XMLHelper.appendTextContent(domElement, sourceID.getValue()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/SourceIDUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/Attic/SourceIDUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/SourceIDUnmarshaller.java 17 Aug 2012 15:05:00 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml1md.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.samlext.saml1md.SourceID; +import org.opensaml.xml.XMLObject; + +/** + * Unmarshaller for {@link SourceID} objects. + */ +public class SourceIDUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + SourceID sourceID = (SourceID) samlObject; + + sourceID.setValue(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml1md/impl/package.html 17 Aug 2012 15:05:00 -0000 1.1 @@ -0,0 +1,12 @@ + + +Implementation of SAML 1 metadata profile objects. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/Delegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/Delegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/Delegate.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,125 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2delrestrict; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NameID; + +/** + * SAML 2.0 Condition for Delegation Restriction - Delegate element. + */ +public interface Delegate extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Delegate"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20DEL_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20DEL_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "DelegateType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20DEL_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20DEL_PREFIX); + + /** DelegationInstant attribute name. */ + public static final String DELEGATION_INSTANT_ATTRIB_NAME = "DelegationInstant"; + + /** ConfirmationMethod attribute name. */ + public static final String CONFIRMATION_METHOD_ATTRIB_NAME = "ConfirmationMethod"; + + + /** + * Gets the BaseID child element of the delegate. + * + * @return the base identifier of the delegate + */ + public BaseID getBaseID(); + + /** + * Sets the BaseID child element of the delegate. + * + * @param newBaseID the base identifier of the delegate + */ + public void setBaseID(BaseID newBaseID); + + /** + * Gets the NameID child element of the delegate. + * + * @return the name identifier of the principal for this request + */ + public NameID getNameID(); + + /** + * Sets the NameID child element of the delegate. + * + * @param newNameID the name identifier of the delegate + */ + public void setNameID(NameID newNameID); + + /** + * Gets the EncryptedID child element of the delegate. + * + * @return the encrypted name identifier of the delegate + */ + public EncryptedID getEncryptedID(); + + /** + * Sets the EncryptedID child element of the delegate. + * + * @param newEncryptedID the new encrypted name identifier of the delegate + */ + public void setEncryptedID(EncryptedID newEncryptedID); + + /** + * Get the delegation instant attribute value. + * + * @return the delegation instant + */ + public DateTime getDelegationInstant(); + + /** + * Set the delegation instant attribute value. + * + * @param newInstant the new delegation instant + */ + public void setDelegationInstant(DateTime newInstant); + + /** + * Get the confirmation method attribute value. + * + * @return the confirmation method + */ + public String getConfirmationMethod(); + + /** + * Set the confirmation method attribute value. + * + * @param newMethod the new confirmation method + */ + public void setConfirmationMethod(String newMethod); + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/DelegationRestrictionType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/DelegationRestrictionType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/DelegationRestrictionType.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2delrestrict; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Condition; + +/** + * SAML 2.0 Condition for Delegation Restriction - DelegationRestrictionType complex type. + */ +public interface DelegationRestrictionType extends Condition { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "DelegationRestrictionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20DEL_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20DEL_PREFIX); + + /** + * Get the list of Delegate child elements. + * + * @return list of Delegate children + */ + List getDelegates(); + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/package.html 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,12 @@ + + +Interfaces for SAML 2 Condition for Delegation Restriction. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegateBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegateBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegateBuilder.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.samlext.saml2delrestrict.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2delrestrict.Delegate; + +/** + * Builder of {@link Delegate}. + */ +public class DelegateBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public DelegateBuilder() { + + } + + /** {@inheritDoc} */ + public Delegate buildObject() { + return buildObject(Delegate.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Delegate buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DelegateImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegateImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegateImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegateImpl.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,129 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2delrestrict.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NameID; +import org.opensaml.samlext.saml2delrestrict.Delegate; +import org.opensaml.xml.XMLObject; + +/** + * Implementation of {@link Delegate}. + */ +public class DelegateImpl extends AbstractSAMLObject implements Delegate { + + /** BaseID child element. */ + private BaseID baseID; + + /** NameID child element. */ + private NameID nameID; + + /** EncryptedID child element. */ + private EncryptedID encryptedID; + + /** DelegationInstant attribute. */ + private DateTime delegationInstant; + + /** ConfirmationMethod attribute. */ + private String confirmationMethod; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected DelegateImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public BaseID getBaseID() { + return baseID; + } + + /** {@inheritDoc} */ + public String getConfirmationMethod() { + return confirmationMethod; + } + + /** {@inheritDoc} */ + public DateTime getDelegationInstant() { + return delegationInstant; + } + + /** {@inheritDoc} */ + public EncryptedID getEncryptedID() { + return encryptedID; + } + + /** {@inheritDoc} */ + public NameID getNameID() { + return nameID; + } + + /** {@inheritDoc} */ + public void setBaseID(BaseID newBaseID) { + baseID = prepareForAssignment(baseID, newBaseID); + } + + /** {@inheritDoc} */ + public void setConfirmationMethod(String newMethod) { + confirmationMethod = prepareForAssignment(confirmationMethod, newMethod); + } + + /** {@inheritDoc} */ + public void setDelegationInstant(DateTime newInstant) { + delegationInstant = prepareForAssignment(delegationInstant, newInstant); + } + + /** {@inheritDoc} */ + public void setEncryptedID(EncryptedID newEncryptedID) { + encryptedID = prepareForAssignment(encryptedID, newEncryptedID); + } + + /** {@inheritDoc} */ + public void setNameID(NameID newNameID) { + nameID = prepareForAssignment(nameID, newNameID); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (baseID != null) { + children.add(baseID); + } + if (nameID != null) { + children.add(nameID); + } + if (encryptedID != null) { + children.add(encryptedID); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegateMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegateMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegateMarshaller.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2delrestrict.impl; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.samlext.saml2delrestrict.Delegate; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for instances of {@link Delegate}. + */ +public class DelegateMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Delegate delegate = (Delegate) xmlObject; + + if (delegate.getDelegationInstant() != null) { + String delInstant = Configuration.getSAMLDateFormatter().print(delegate.getDelegationInstant()); + domElement.setAttributeNS(null, Delegate.DELEGATION_INSTANT_ATTRIB_NAME, delInstant); + } + if (!DatatypeHelper.isEmpty(delegate.getConfirmationMethod())) { + domElement.setAttributeNS(null, Delegate.CONFIRMATION_METHOD_ATTRIB_NAME, delegate.getConfirmationMethod()); + } + + super.marshallAttributes(xmlObject, domElement); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegateUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegateUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegateUnmarshaller.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2delrestrict.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NameID; +import org.opensaml.samlext.saml2delrestrict.Delegate; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for instances of {@link Delegate}. + */ +public class DelegateUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + Delegate delegate = (Delegate) samlObject; + + String attrName = attribute.getLocalName(); + if (Delegate.CONFIRMATION_METHOD_ATTRIB_NAME.equals(attrName)) { + delegate.setConfirmationMethod(attribute.getValue()); + } else if (Delegate.DELEGATION_INSTANT_ATTRIB_NAME.equals(attrName)) { + delegate.setDelegationInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + Delegate delegate = (Delegate) parentSAMLObject; + + if (childSAMLObject instanceof BaseID) { + delegate.setBaseID((BaseID) childSAMLObject); + } else if (childSAMLObject instanceof NameID) { + delegate.setNameID((NameID) childSAMLObject); + } else if (childSAMLObject instanceof EncryptedID) { + delegate.setEncryptedID((EncryptedID) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegationRestrictionTypeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegationRestrictionTypeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegationRestrictionTypeBuilder.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.samlext.saml2delrestrict.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2delrestrict.DelegationRestrictionType; + +/** + * Builder of {@link DelegationRestrictionType}. + */ +public class DelegationRestrictionTypeBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public DelegationRestrictionTypeBuilder() { + + } + + /** {@inheritDoc} */ + public DelegationRestrictionType buildObject() { + return buildObject(DelegationRestrictionType.DEFAULT_ELEMENT_NAME, DelegationRestrictionType.TYPE_NAME); + } + + /** {@inheritDoc} */ + public DelegationRestrictionType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DelegationRestrictionTypeImpl(namespaceURI, localName, namespacePrefix); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegationRestrictionTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegationRestrictionTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegationRestrictionTypeImpl.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2delrestrict.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.samlext.saml2delrestrict.Delegate; +import org.opensaml.samlext.saml2delrestrict.DelegationRestrictionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation of {@link DelegationRestrictionType}. + */ +public class DelegationRestrictionTypeImpl extends AbstractSAMLObject implements DelegationRestrictionType { + + /** Delegate child elements. */ + private XMLObjectChildrenList delegates; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected DelegationRestrictionTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + delegates = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getDelegates() { + return delegates; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + children.addAll(delegates); + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegationRestrictionTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegationRestrictionTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegationRestrictionTypeMarshaller.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2delrestrict.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.samlext.saml2delrestrict.DelegationRestrictionType; + +/** + * Marshaller for instances of {@link DelegationRestrictionType}. + */ +public class DelegationRestrictionTypeMarshaller extends AbstractSAMLObjectMarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegationRestrictionTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegationRestrictionTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/DelegationRestrictionTypeUnmarshaller.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2delrestrict.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.samlext.saml2delrestrict.Delegate; +import org.opensaml.samlext.saml2delrestrict.DelegationRestrictionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for instances of {@link DelegationRestrictionType}. + */ +public class DelegationRestrictionTypeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + DelegationRestrictionType drt = (DelegationRestrictionType) parentSAMLObject; + + if (childSAMLObject instanceof Delegate) { + drt.getDelegates().add((Delegate) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2delrestrict/impl/package.html 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,12 @@ + + +Implementation for SAML 2 Condition for Delegation Restriction. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/impl/EntityAttributesBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/impl/EntityAttributesBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/impl/EntityAttributesBuilder.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdattr.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2mdattr.EntityAttributes; + +/** Builder of {@link EntityAttributesImpl} objects. */ +public class EntityAttributesBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public EntityAttributesBuilder() { + + } + + /** {@inheritDoc} */ + public EntityAttributes buildObject() { + return buildObject(EntityAttributes.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public EntityAttributes buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EntityAttributesImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/impl/EntityAttributesImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/impl/EntityAttributesImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/impl/EntityAttributesImpl.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdattr.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.Evidentiary; +import org.opensaml.samlext.saml2mdattr.EntityAttributes; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Concrete implementation of {@link EntityAttributes}. */ +public class EntityAttributesImpl extends AbstractSAMLObject implements EntityAttributes { + + /** Assertion of the Evidence. */ + private final IndexedXMLObjectChildrenList attributeInfo; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EntityAttributesImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributeInfo = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAttributes() { + return (List) attributeInfo.subList(Attribute.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getAssertions() { + return (List) attributeInfo.subList(Assertion.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (attributeInfo.size() == 0) { + return null; + } + + children.addAll(attributeInfo); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/impl/EntityAttributesMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/impl/EntityAttributesMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/impl/EntityAttributesMarshaller.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdattr.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** A thread-safe Marshaller for {@link org.opensaml.samlext.saml2mdattr.EntityAttributes}. */ +public class EntityAttributesMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/impl/EntityAttributesUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/impl/EntityAttributesUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/impl/EntityAttributesUnmarshaller.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdattr.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.samlext.saml2mdattr.EntityAttributes; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** A thread-safe Unmarshaller for {@link org.opensaml.samlext.saml2mdattr.EntityAttributes}. */ +public class EntityAttributesUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + EntityAttributes entityAttrs = (EntityAttributes) parentObject; + + if (childObject instanceof Attribute) { + entityAttrs.getAttributes().add((Attribute) childObject); + } else if (childObject instanceof Assertion) { + entityAttrs.getAssertions().add((Assertion) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/ActionNamespace.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/ActionNamespace.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/ActionNamespace.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.schema.XSURI; + +/** + * SAML 2.0 Metadata extension ActionNamespace + */ +public interface ActionNamespace extends XSURI, SAMLObject { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "ActionNamespace"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MDQUERY_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MDQUERY_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/AttributeQueryDescriptorType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/AttributeQueryDescriptorType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/AttributeQueryDescriptorType.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AttributeConsumingService; + +/** + * SAML 2.0 Metadata extension AttributeQueryDescriptorType. + */ +public interface AttributeQueryDescriptorType extends QueryDescriptorType { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AttributeQueryDescriptorType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20MDQUERY_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20MDQUERY_PREFIX); + + /** + * Gets the list of attribute consuming service endpoints support by this role. + * + * @return the list of attribute consuming service endpoints support by this role + */ + public List getAttributeConsumingServices(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/AuthnQueryDescriptorType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/AuthnQueryDescriptorType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/AuthnQueryDescriptorType.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata extension AuthnQueryDescriptorType. + */ +public interface AuthnQueryDescriptorType extends QueryDescriptorType { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AuthnQueryDescriptorType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20MDQUERY_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20MDQUERY_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/AuthzDecisionQueryDescriptorType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/AuthzDecisionQueryDescriptorType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/AuthzDecisionQueryDescriptorType.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata extension AuthzDecisionQueryDescriptorType. + */ +public interface AuthzDecisionQueryDescriptorType extends QueryDescriptorType { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AuthzDecisionQueryDescriptorType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20MDQUERY_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20MDQUERY_PREFIX); + + /** + * Gets the list of action namespaces support by this role. + * + * @return the list of action namespaces support by this role + */ + public List getActionNamespaces(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/QueryDescriptorType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/QueryDescriptorType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/QueryDescriptorType.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * SAML 2.0 Metadata extension QueryDescriptorType. + */ +public interface QueryDescriptorType extends RoleDescriptor { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "QueryDescriptorType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20MDQUERY_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20MDQUERY_PREFIX); + + /** "WantAssertionSigned" attribute's local name. */ + public static final String WANT_ASSERTIONS_SIGNED_ATTRIB_NAME = "WantAssertionsSigned"; + + /** + * Gets whether assertions to this endpoint should be signed. + * + * @return whether assertions to this endpoint should be signed + */ + public Boolean getWantAssertionsSigned(); + + /** + * Gets whether assertions to this endpoint should be signed. + * + * @return whether assertions to this endpoint should be signed + */ + public XSBooleanValue getWantAssertionsSignedXSBoolean(); + + /** + * Sets whether assertions to this endpoint should be signed. + * + * @param newWantAssertionsSigned whether assertions to this endpoint should be signed + */ + public void setWantAssertionsSigned(Boolean newWantAssertionsSigned); + + /** + * Sets whether assertions to this endpoint should be signed. + * + * @param newWantAssertionsSigned whether assertions to this endpoint should be signed + */ + public void setWantAssertionsSigned(XSBooleanValue newWantAssertionsSigned); + + /** + * Gets the list of name ID formats supported by this query service. + * + * @return the list of name ID formats supported by this query service + */ + public List getNameIDFormat(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/package.html 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,12 @@ + + +Interfaces for SAML 2 metadata standalone query endpoints profile. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/GeolocationHintImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/GeolocationHintImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/GeolocationHintImpl.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.samlext.saml2mdui.GeolocationHint; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.samlext.saml2mdui.GeolocationHint}. + */ +public class GeolocationHintImpl extends AbstractSAMLObject implements GeolocationHint { + + /** + * local storage. + */ + private String hint; + + /** + * Constructor. + * + * @param namespaceURI the namespaceURI + * @param elementLocalName the elementLocalName + * @param namespacePrefix the namespacePrefix + */ + protected GeolocationHintImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getHint() { + return hint; + } + + /** {@inheritDoc} */ + public void setHint(String newHint) { + hint = prepareForAssignment(hint, newHint); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/GeolocationHintUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/GeolocationHintUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/GeolocationHintUnmarshaller.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.samlext.saml2mdui.GeolocationHint; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.samlext.saml2mdui.GeolocationHint} objects. + */ +public class GeolocationHintUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + GeolocationHint hint = (GeolocationHint) samlObject; + + hint.setHint(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/IPHintUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/IPHintUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/IPHintUnmarshaller.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.samlext.saml2mdui.IPHint; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.samlext.saml2mdui.IPHint} objects. + */ +public class IPHintUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + IPHint hint = (IPHint) samlObject; + + hint.setHint(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/InformationURLMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/InformationURLMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/InformationURLMarshaller.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.InformationURL} objects. + */ +public class InformationURLMarshaller extends LocalizedURIMarshaller { +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/InformationURLUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/InformationURLUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/InformationURLUnmarshaller.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,24 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.samlext.saml2mdui.InformationURL} objects. + */ +public class InformationURLUnmarshaller extends LocalizedURIUnmarshaller { +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/KeywordsBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/KeywordsBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/KeywordsBuilder.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2mdui.Keywords; +import org.opensaml.samlext.saml2mdui.UIInfo; + +/** + * Builder of {@link org.opensaml.samlext.saml2mdui.InformationURL} objects. + * @author Rod Widdowson + */ +public class KeywordsBuilder extends AbstractSAMLObjectBuilder { + /** + * Constructor. + */ + public KeywordsBuilder() { + + } + + /** {@inheritDoc} */ + public Keywords buildObject() { + return buildObject(UIInfo.MDUI_NS, + Keywords.DEFAULT_ELEMENT_LOCAL_NAME, + UIInfo.MDUI_PREFIX); + } + + /** {@inheritDoc} */ + public Keywords buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new KeywordsImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedNameMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedNameMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedNameMarshaller.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.samlext.saml2mdui.LocalizedName; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.LocalizedName} objects. + */ +public class LocalizedNameMarshaller extends AbstractSAMLObjectMarshaller { + + /** + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + LocalizedName name = (LocalizedName) samlObject; + + if (name.getName() != null) { + Attr attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), SAMLConstants.XML_NS, + LangBearing.XML_LANG_ATTR_LOCAL_NAME, SAMLConstants.XML_PREFIX); + attribute.setValue(name.getName().getLanguage()); + domElement.setAttributeNodeNS(attribute); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + LocalizedName name = (LocalizedName) samlObject; + + if (name.getName() != null) { + XMLHelper.appendTextContent(domElement, name.getName().getLocalString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LogoImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LogoImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LogoImpl.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,116 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.samlext.saml2mdui.Logo; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Concrete implementation of {@link org.opensaml.samlext.saml2mdui.Logo}. + * @author rod widdowson + */ +public class LogoImpl extends AbstractSAMLObject implements Logo { + + /** Logo URL. */ + private String url; + + /** Language. */ + private String lang; + + /** X-Dimension of the logo. */ + private Integer width; + + /** Y-Dimension of the logo. */ + private Integer height; + + /** + * Constructor. + * + * @param namespaceURI namespaceURI + * @param elementLocalName elementLocalName + * @param namespacePrefix namespacePrefix + */ + protected LogoImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + + /** {@inheritDoc} */ + public Integer getHeight() { + return height; + } + + /** {@inheritDoc} */ + public void setHeight(Integer newHeight) { + height = prepareForAssignment(height, newHeight); + } + + /** {@inheritDoc} */ + public Integer getWidth() { + return width; + } + + /** {@inheritDoc} */ + public void setWidth(Integer newWidth) { + width = prepareForAssignment(width, newWidth); + } + + /** {@inheritDoc} */ + public String getURL() { + return url; + } + + /** {@inheritDoc} */ + public void setURL(String newURL) { + url = prepareForAssignment(url, newURL); + } + + /** {@inheritDoc} */ + public String getXMLLang() { + return lang; + } + + /** {@inheritDoc} */ + public void setXMLLang(String newLang) { + boolean hasValue = newLang != null && !DatatypeHelper.isEmpty(newLang); + lang = prepareForAssignment(lang, newLang); + manageQualifiedAttributeNamespace(LangBearing.XML_LANG_ATTR_NAME, hasValue); + } + + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + + /** + * {@inheritDoc} + */ + public int hashCode() { + int hash = url.hashCode(); + hash = hash * 31 + lang.hashCode(); + hash = hash * 31 + height; + hash = hash * 31 + width; + return hash; + } +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/PrivacyStatementURLUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/PrivacyStatementURLUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/PrivacyStatementURLUnmarshaller.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + + +/** + * A thread-safe unmarshaller for {@link org.opensaml.samlext.saml2mdui.PrivacyStatementURL} objects. + */ +public class PrivacyStatementURLUnmarshaller extends LocalizedURIUnmarshaller { +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/RespondTo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/RespondTo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/RespondTo.java 17 Aug 2012 15:04:59 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.samlpthrpty; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.NameIDType; + +/** + * SAML 2.0 Protocol Third-party extension RespondTo + */ +public interface RespondTo extends NameIDType, SAMLObject { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "RespondTo"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20PTHRPTY_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20PTHRPTY_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/package.html 17 Aug 2012 15:05:00 -0000 1.1 @@ -0,0 +1,12 @@ + + +Interfaces for SAML 2 protocol third-party response profile. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/RespondToBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/RespondToBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/RespondToBuilder.java 17 Aug 2012 15:04:55 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.samlpthrpty.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.samlext.samlpthrpty.RespondTo; + +/** + * Builder of {@link RespondToImpl} objects. + */ +public class RespondToBuilder extends AbstractSAMLObjectBuilder { + + /** {@inheritDoc} */ + public RespondTo buildObject() { + return buildObject(SAMLConstants.SAML20PTHRPTY_NS, RespondTo.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20PTHRPTY_PREFIX); + } + + /** {@inheritDoc} */ + public RespondTo buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RespondToImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/RespondToImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/RespondToImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/RespondToImpl.java 17 Aug 2012 15:04:55 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.samlpthrpty.impl; + +import org.opensaml.saml2.core.impl.AbstractNameIDType; +import org.opensaml.samlext.samlpthrpty.RespondTo; + +/** + * Concerte implementation of {@link RespondTo}. + */ +public class RespondToImpl extends AbstractNameIDType implements RespondTo { + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RespondToImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/RespondToMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/RespondToMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/RespondToMarshaller.java 17 Aug 2012 15:04:55 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.samlpthrpty.impl; + +import org.opensaml.saml2.core.impl.AbstractNameIDTypeMarshaller; + +/** + * Marshaller of {@link org.opensaml.samlext.samlpthrpty.RespondTo} objects. + */ +public class RespondToMarshaller extends AbstractNameIDTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/RespondToUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/RespondToUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/RespondToUnmarshaller.java 17 Aug 2012 15:04:55 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.samlpthrpty.impl; + +import org.opensaml.saml2.core.impl.AbstractNameIDTypeUnmarshaller; + +/** + * Unmarshaller for {@link org.opensaml.samlext.samlpthrpty.RespondTo} objects. + */ +public class RespondToUnmarshaller extends AbstractNameIDTypeUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/samlpthrpty/impl/package.html 17 Aug 2012 15:04:55 -0000 1.1 @@ -0,0 +1,12 @@ + + +Implementation for SAML 2 protocol third-party response profile objects. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/XACMLConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/XACMLConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/XACMLConstants.java 17 Aug 2012 15:04:55 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml; + +/** Defines the constants for the XACML providers. */ +public class XACMLConstants { + + /** The prefix for the use of xacml policy. */ + public static final String XACML_PREFIX = "xacml"; + + /** The prefix for the use of xacml context. */ + public static final String XACMLCONTEXT_PREFIX = "xacml-context"; + + /** The namespaces for use of XACML 1.0 context. */ + public static final String XACML10CTX_NS = "urn:oasis:names:tc:xacml:1.0:context"; + + /** The namespaces for use of XACML 1.0 policy. */ + public static final String XACML10_NS = "urn:oasis:names:tc:xacml:1.0:policy"; + + /** The namespaces for use of XACML 2.0 context. */ + public static final String XACML20CTX_NS = "urn:oasis:names:tc:xacml:2.0:context:schema:os"; + + /** The namespaces for use of XACML 2.0 policy. */ + public static final String XACML20_NS = "urn:oasis:names:tc:xacml:2.0:policy:schema:os"; + + /** The namespaces for use of XACML 3.0. */ + public static final String XACML30_NS = "urn:oasis:names:tc:xacml:3.0:schema:os"; + + /** X.500 Name datatype URI. */ + public static final String X500_NAME_DATATYPE_URI = "urn:oasis:names:tc:xacml:1.0:data-type:x500Name"; + + /** RFC822 Name datatype URI. */ + public static final String RFC822_NAME_DATATYPE_URI = "urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name"; + + /** IP address datatype URI. */ + public static final String IP_ADDRESS_DATATYPE_URI = "urn:oasis:names:tc:xacml:1.0:data-type:ipAddress"; + + /** DNS Name datatype URI. */ + public static final String DNS_NAME_DATATYPE_URI = "urn:oasis:names:tc:xacml:1.0:data-type:dnsName"; +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/XACMLObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/XACMLObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/XACMLObject.java 17 Aug 2012 15:04:55 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml; + +import org.opensaml.xml.validation.ValidatingXMLObject; + +/** + * Base interface for XACML objects. + */ +public interface XACMLObject extends ValidatingXMLObject { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/XACMLObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/XACMLObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/XACMLObjectBuilder.java 17 Aug 2012 15:04:55 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml; + +import org.opensaml.xml.XMLObjectBuilder; + +/** + * Builder of XACML objects. + * + * @param type of XACML object built + */ +public interface XACMLObjectBuilder extends XMLObjectBuilder { + + /** + * Builds a XACML object, using its default attribute name. + * + * @return constructed XACML object + */ + public XACMLObjectType buildObject(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ActionType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ActionType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ActionType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML context Action schema type. */ +public interface ActionType extends XACMLObject { + + /** Local name of the Action element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Action"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ActionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** + * Returns the list of attributes in the subject. + * + * @return the list of attributes in the subject + */ + public List getAttributes(); + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/AttributeType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/AttributeType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/AttributeType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,101 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML context Attribute schema type. */ +public interface AttributeType extends XACMLObject { + + /** Local name of the Attribute element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Attribute"; + + /** Default element name XACML20. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AttributeType"; + + /** QName of the XSI type XACML20. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Name of the AttributeId attribute. */ + public static final String ATTRIBUTEID_ATTTRIB_NAME = "AttributeId"; + + /** Name for the Datatype attribute. */ + public static final String DATATYPE_ATTRIB_NAME = "DataType"; + + /** Name of the Issuer attribute. */ + public static final String ISSUER_ATTRIB_NAME = "Issuer"; + + /** + * gets the AttributeId. + * + * @return the AttributeId + */ + public String getAttributeID(); + + /** + * Gets the list of attribute values for this attribute. + * + * @return the list of values for this attribute + */ + public List getAttributeValues(); + + /** + * Get the datatype of the attribute. + * + * @return the datatype + */ + public String getDataType(); + + /** + * Gets the issuer of the attribute. + * + * @return the value of Issuer + */ + public String getIssuer(); + + /** + * Sets the AttributeId. + * + * @param attributeId is the wanted AttributeId + */ + public void setAttributeID(String attributeId); + + /** + * Sets the datatype of the attribute. + * + * @param datatype is the wanted datatype + */ + public void setDataType(String datatype); + + /** + * Sets the issuer of the attribute. + * + * @param issuer is the issuer of the attribute + */ + public void setIssuer(String issuer); +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/AttributeValueType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/AttributeValueType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/AttributeValueType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** XACML context AttributeValue schema type. */ +public interface AttributeValueType extends XACMLObject, ElementExtensibleXMLObject, AttributeExtensibleXMLObject { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeValue"; + + /** Default element name XACML20. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AttributeValueType"; + + /** QName of the XSI type XACML20. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** + * Gets the text content of the element. + * + * @return text content of the element + */ + public String getValue(); + + /** + * Sets the text content of the element. + * + * NOTE because the library does not support mixed content setting textual content will prohibit + * element content. + * + * @param value text content of the element + */ + public void setValue(String value); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/DecisionType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/DecisionType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/DecisionType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML context Decision schema type. */ +public interface DecisionType extends XACMLObject { + + /** Allowed decision values. */ + public enum DECISION { + Deny, Permit, Indeterminate, NotApplicable + }; + + /** Element name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Decision"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "DecisionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** + * Gets the value of the decision. + * + * @return The value of the decision + */ + public DECISION getDecision(); + + /** + * Sets the value of the decision. + * + * @param decision value of the decision + */ + public void setDecision(DECISION decision); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/EnvironmentType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/EnvironmentType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/EnvironmentType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML context Environment schema type. */ +public interface EnvironmentType extends XACMLObject { + + /** Local name of the Attribute element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Environment"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "EnvironmentType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** + * Returns the list of attributes in the environment. + * + * @return the list of attributes in the environment + */ + public List getAttributes(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/MissingAttributeDetailType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/MissingAttributeDetailType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/MissingAttributeDetailType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,101 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML context MissingAttributeDetail schema type. */ +public interface MissingAttributeDetailType extends XACMLObject { + + /** Local name of the element MissingAttributeDetail. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "MissingAttributeDetail"; + + /** QName of the element MissingAttributeDetail. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "MissingAttributeDetailType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** AttributeId attribute name. */ + public static final String ATTRIBUTE_ID_ATTRIB_NAME = "AttributeId"; + + /** DataType attribute name. */ + public static final String DATA_TYPE_ATTRIB_NAME = "DataType"; + + /** Issuer attribute name. */ + public static final String ISSUER_ATTRIB_NAME = "Issuer"; + + /** + * Gets the missing attribute values. + * + * @return missing attribute values + */ + public List getAttributeValues(); + + /** + * Gets the ID of the attribute. + * + * @return ID of the attribute + */ + public String getAttributeId(); + + /** + * Sets the ID of the attribute. + * + * @param id ID of the attribute + */ + public void setAttributeId(String id); + + /** + * Gets the data type of the attribute. + * + * @return data type of the attribute + */ + public String getDataType(); + + /** + * Sets the data type of the attribute. + * + * @param type data type of the attribute + */ + public void setDataType(String type); + + /** + * Gets the issuer of the attribute. + * + * @return issuer of the attribute + */ + public String getIssuer(); + + /** + * Sets the issuer of the attribute. + * + * @param issuer issuer of the attribute + */ + public void setIssuer(String issuer); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/RequestType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/RequestType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/RequestType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,85 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML context Request schema type. */ +public interface RequestType extends XACMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Request"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** + * Gets the subjects from the request. + * + * @return the subjects from the request + */ + public List getSubjects(); + + /** + * Gets the resources from the request. + * + * @return the resources from the request + */ + public List getResources(); + + /** + * Gets the action from the request. + * + * @return the action from the request + */ + public ActionType getAction(); + + /** + * Sets the action of the request. + * + * @param newAction action of the request + */ + public void setAction(ActionType newAction); + + /** + * Gets the environment from the request. + * + * @return the environment from the request + */ + public EnvironmentType getEnvironment(); + + /** + * Sets the environment of the request. + * + * @param environment environment of the request + */ + public void setEnvironment(EnvironmentType environment); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ResourceContentType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ResourceContentType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ResourceContentType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** XACML context ResourceContent schema type. */ +public interface ResourceContentType extends XACMLObject, ElementExtensibleXMLObject, AttributeExtensibleXMLObject { + + /** Local name of the ResourceContent element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "ResourceContent"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ResourceContentType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** + * Gets the text value of this element. + * + * @return text value of this element + */ + public String getValue(); + + /** + * Sets the text value of this element. + * + * @param value text value of this element + */ + public void setValue(String value); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ResourceType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ResourceType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ResourceType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML context ResourceContent schema type. */ +public interface ResourceType extends XACMLObject { + + /** Local name of the Attribute element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Resource"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ResourceType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** + * Gets the content of the resource. + * + * @return content of the resource + */ + public ResourceContentType getResourceContent(); + + /** + * Sets the content of the resource. + * + * @param content content of the resource + */ + public void setResourceContent(ResourceContentType content); + + /** + * Returns the list of attributes in the resource. + * + * @return the list of attributes in the resource + */ + public List getAttributes(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ResponseType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ResponseType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ResponseType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML context Response schema type. */ +public interface ResponseType extends XACMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Response"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ResponseType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** + * Returns the result of the response. + * + * @return the result of the response + */ + public ResultType getResult(); + + /** + * Sets the result of the response. + * + * @param newResult result of the response + */ + public void setResult(ResultType newResult); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ResultType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ResultType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/ResultType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,101 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.policy.ObligationsType; + +/** XACML context Result schema type. */ +public interface ResultType extends XACMLObject { + + /** Local name of the element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Result"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ResultType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** ResourceId attribute name. */ + public static final String RESOURCE_ID_ATTTRIB_NAME = "ResourceId"; + + /** + * Returns the decision in the result. + * + * @return XACMLDecision the decision in the result + */ + public DecisionType getDecision(); + + /** + * Returns the list of Obligations in the result. + * + * @return the list of Obligations in the result + */ + public ObligationsType getObligations(); + + /** + * Sets the obligations for this result. + * + * @param obligations obligations for this result + */ + public void setObligations(ObligationsType obligations); + + /** + * Gets the ResourceId of the result. + * + * @return The ResourceId of the subject + */ + public String getResourceId(); + + /** + * Returns the status in the result. + * + * @return the status in the result + */ + public StatusType getStatus(); + + /** + * Sets the result status. + * + * @param status result status + */ + public void setStatus(StatusType status); + + /** + * Sets the decision in the result. + * + * @param newDecision The decision in the result + */ + public void setDecision(DecisionType newDecision); + + /** + * Sets the ResourceId. + * + * @param resourceId is the ResourceId + */ + public void setResourceId(String resourceId); +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/StatusCodeType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/StatusCodeType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/StatusCodeType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML context StatusCode schema type. */ +public interface StatusCodeType extends XACMLObject { + + /** Local name of the StatusCode element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "StatusCode"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "StatusCodeType"; + + /** QName of the XSI type XACML20. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Name of the Value attribute. */ + public static final String VALUE_ATTTRIB_NAME = "Value"; + + /** Missing attribute status code. */ + public static final String SC_MISSING_ATTRIBUTE = "urn:oasis:names:tc:xacml:1.0:status:missing-attribute"; + + /** Ok status code. */ + public static final String SC_OK = "urn:oasis:names:tc:xacml:1.0:status:ok"; + + /** Processing error status code. */ + public static final String SC_PROCESSING_ERROR = "urn:oasis:names:tc:xacml:1.0:status:processing-error"; + + /** Syntax error status code. */ + public static final String SC_SYNTAX_ERROR = "urn:oasis:names:tc:xacml:1.0:status:syntax-error"; + + /** + * Gets the status code. + * + * @return status code + */ + public StatusCodeType getStatusCode(); + + /** + * Sets the status code. + * + * @param code status code + */ + public void setStatusCode(StatusCodeType code); + + /** + * Gets the value of the attribute named value of the status element. + * + * @return The value of the attribute named value for the status element + */ + public String getValue(); + + /** + * Sets the attribute named value of the status elements. + * + * @param value The wanted value for the attribute value + */ + public void setValue(String value); +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/StatusDetailType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/StatusDetailType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/StatusDetailType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** XACML context StatusDetail schema type. */ +public interface StatusDetailType extends XACMLObject, ElementExtensibleXMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "StatusDetail"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "StatusDetailType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/StatusMessageType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/StatusMessageType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/StatusMessageType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xml.schema.XSString; + +/** XACML context StatusMessage schema type. */ +public interface StatusMessageType extends XSString, XACMLObject { + + /** Local name of the element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "StatusMessage"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/StatusType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/StatusType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/StatusType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML context Status schema type. */ +public interface StatusType extends XACMLObject { + + /** Local name of the StatusCode element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Status"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "StatusType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** + * Gets the status code of status. + * + * @return The status code of status + */ + public StatusCodeType getStatusCode(); + + /** + * Gets the status detail of status. + * + * @return The status detail of status + */ + public StatusDetailType getStatusDetail(); + + /** + * Gets the status message of status. + * + * @return The status message of status + */ + public StatusMessageType getStatusMessage(); + + /** + * Sets the status code for the Status. + * + * @param newStatusCode The new status code + */ + public void setStatusCode(StatusCodeType newStatusCode); + + /** + * Sets the status detail for the Status. + * + * @param statusDetail The new status message + */ + public void setStatusDetail(StatusDetailType statusDetail); + + /** + * Sets the status message for the Status. + * + * @param newStatusMessage The new status message + */ + public void setStatusMessage(StatusMessageType newStatusMessage); + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/SubjectType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/SubjectType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/SubjectType.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML context Subject schema type. */ +public interface SubjectType extends XACMLObject { + + /** Local name of the element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Subject"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20CTX_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "SubjectType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20CTX_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + + /** Name of the SubjectCategory attribute. */ + public static final String SUBJECT_CATEGORY_ATTTRIB_NAME = "SubjectCategory"; + + /** + * Returns the list of attributes in the subject. + * + * @return the list of attributes in the subject + */ + public List getAttributes(); + + /** + * Gets the subjectcategory of the subject. + * + * @return The subjectcategory of the subject + */ + public String getSubjectCategory(); + + /** + * Sets the subjectcategory. + * + * @param subjectCategory Sets the subjectcategory + */ + public void setSubjectCategory(String subjectCategory); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/provider/BaseObligationHandler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/provider/BaseObligationHandler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/provider/BaseObligationHandler.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,109 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.provider; + +import org.opensaml.xacml.policy.ObligationType; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Base class for all obligation handlers. + * + * Handlers are executed in order of precedence. Handlers with a higher precedence are executed before those with a + * lower precedence. Handlers with the same precedence are executed in random order. + * + * Obligation handlers must be stateless. + */ +public abstract class BaseObligationHandler { + + /** ID of the handled obligation. */ + private String id; + + /** Precedence of this handler. */ + private int precedence; + + /** + * Constructor. Obligation has the lowest precedence + * + * @param obligationId ID of the handled obligation + */ + protected BaseObligationHandler(String obligationId) { + this(obligationId, Integer.MIN_VALUE); + } + + /** + * Constructor. + * + * @param obligationId ID of the handled obligation + * @param handlerPrecedence precedence of this handler + */ + protected BaseObligationHandler(String obligationId, int handlerPrecedence) { + id = DatatypeHelper.safeTrimOrNullString(obligationId); + if (id == null) { + throw new IllegalArgumentException("Provided obligation ID may not be null or empty"); + } + + precedence = handlerPrecedence; + } + + /** + * Gets the ID of the handled obligation. + * + * @return ID of the handled obligation + */ + public String getObligationId() { + return id; + } + + /** + * Gets the precedence of the handler. + * + * @return precedence of the handler + */ + public int getHandlerPrecedence() { + return precedence; + } + + /** + * Evaluates the obligation represented by this handler. + * + * @param context current processing context + * @param obligation the obligation as returned by the PDP + * + * @throws ObligationProcessingException thrown if there is a problem evaluating this handler + */ + public abstract void evaluateObligation(ObligationProcessingContext context, ObligationType obligation) + throws ObligationProcessingException; + + /** {@inheritDoc} */ + public int hashCode() { + return getObligationId().hashCode(); + } + + /** {@inheritDoc} */ + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (obj instanceof BaseObligationHandler) { + return DatatypeHelper.safeEquals(getObligationId(), ((BaseObligationHandler) obj).getObligationId()); + } + + return false; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/provider/ObligationProcessingContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/provider/ObligationProcessingContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/provider/ObligationProcessingContext.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.provider; + +import org.opensaml.xacml.ctx.ResultType; + +/** + * A context for processing obligations. + */ +public class ObligationProcessingContext { + + /** Result of a XACML authorization request. */ + private ResultType result; + + /** + * Constructor. + * + * @param authzResult result of a XACML authorization request + */ + public ObligationProcessingContext(ResultType authzResult) { + if (authzResult == null) { + throw new IllegalArgumentException("Authorization request result may not be null"); + } + result = authzResult; + } + + /** + * Gets the result of a XACML authorization request. + * + * @return result of a XACML authorization request + */ + public ResultType getAuthorizationDecisionResult() { + return result; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/provider/ObligationProcessingException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/provider/ObligationProcessingException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/provider/ObligationProcessingException.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.provider; + +/** Exception thrown if there is a problem evaluating an obligation. */ +public class ObligationProcessingException extends Exception { + + /** Serial version UID. */ + private static final long serialVersionUID = -8978474052544318919L; + + /** Constructor. */ + public ObligationProcessingException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public ObligationProcessingException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public ObligationProcessingException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public ObligationProcessingException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/provider/ObligationService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/provider/ObligationService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/provider/ObligationService.java 17 Aug 2012 15:04:52 -0000 1.1 @@ -0,0 +1,201 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.provider; + +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import org.opensaml.xacml.ctx.DecisionType.DECISION; +import org.opensaml.xacml.policy.EffectType; +import org.opensaml.xacml.policy.ObligationType; +import org.opensaml.xacml.policy.ObligationsType; + +/** A service for evaluating the obligations within a context. */ +public class ObligationService { + + /** Read/write lock around the registered obligation handlers. */ + private ReentrantReadWriteLock rwLock; + + /** Registered obligation handlers. */ + private Set obligationHandlers; + + /** Constructor. */ + public ObligationService() { + rwLock = new ReentrantReadWriteLock(true); + obligationHandlers = new TreeSet(new ObligationHandlerComparator()); + } + + /** + * Gets the registered obligation handlers. + * + * @return registered obligation handlers + */ + public Set getObligationHandlers() { + return Collections.unmodifiableSet(obligationHandlers); + } + + /** + * Adds an obligation handler to the list of registered handlers + * + * This method waits until a write lock is obtained for the set of registered obligation handlers. + * + * @param handler the handler to add to the list of registered handlers. + */ + public void addObligationhandler(BaseObligationHandler handler) { + if (handler == null) { + return; + } + + Lock writeLock = rwLock.writeLock(); + writeLock.lock(); + try { + obligationHandlers.add(handler); + } finally { + writeLock.unlock(); + } + } + + /** + * Adds a collection of obligation handler to the list of registered handlers + * + * This method waits until a write lock is obtained for the set of registered obligation handlers. + * + * @param handlers the collection of handlers to add to the list of registered handlers. + */ + public void addObligationhandler(Collection handlers) { + if (handlers == null || handlers.isEmpty()) { + return; + } + + Lock writeLock = rwLock.writeLock(); + writeLock.lock(); + try { + obligationHandlers.addAll(handlers); + } finally { + writeLock.unlock(); + } + } + + /** + * Removes an obligation handler from the list of registered handlers + * + * This method waits until a write lock is obtained for the set of registered obligation handlers. + * + * @param handler the handler to remove from the list of registered handlers. + */ + public void removeObligationHandler(BaseObligationHandler handler) { + if (handler == null) { + return; + } + + Lock writeLock = rwLock.writeLock(); + writeLock.lock(); + try { + obligationHandlers.remove(handler); + } finally { + writeLock.unlock(); + } + } + + /** + * Processes the obligations within the effective XACML policy. + * + * This method waits until a read lock is obtained for the set of registered obligation handlers. + * + * @param context current processing context + * + * @throws ObligationProcessingException thrown if there is a problem evaluating an obligation + */ + public void processObligations(ObligationProcessingContext context) throws ObligationProcessingException { + Lock readLock = rwLock.readLock(); + readLock.lock(); + try { + Iterator handlerItr = obligationHandlers.iterator(); + Map effectiveObligations = preprocessObligations(context); + + BaseObligationHandler handler; + while (handlerItr.hasNext()) { + handler = handlerItr.next(); + if (effectiveObligations.containsKey(handler.getObligationId())) { + handler.evaluateObligation(context, effectiveObligations.get(handler.getObligationId())); + } + } + } finally { + readLock.unlock(); + } + } + + /** + * Preprocesses the obligations returned within the result. This preprocessing determines the active effect, based + * on {@link org.opensaml.xacml.ctx.ResultType#getDecision()}, and creates an index that maps obligation IDs to the + * {@link ObligationType} returned by the PDP. + * + * @param context current processing context + * + * @return preprocessed obligations + */ + protected Map preprocessObligations(ObligationProcessingContext context) { + HashMap effectiveObligations = new HashMap(); + + ObligationsType obligations = context.getAuthorizationDecisionResult().getObligations(); + if (obligations == null || obligations.getObligations() == null) { + return effectiveObligations; + } + + EffectType activeEffect; + if (context.getAuthorizationDecisionResult().getDecision().getDecision() == DECISION.Permit) { + activeEffect = EffectType.Permit; + } else { + activeEffect = EffectType.Deny; + } + + for (ObligationType obligation : obligations.getObligations()) { + if (obligation != null && obligation.getFulfillOn() == activeEffect) { + effectiveObligations.put(obligation.getObligationId(), obligation); + } + } + + return effectiveObligations; + } + + /** Comparator used to order obligation handlers by precedence. */ + private class ObligationHandlerComparator implements Comparator { + + /** {@inheritDoc} */ + public int compare(BaseObligationHandler o1, BaseObligationHandler o2) { + if (o1.getHandlerPrecedence() == o2.getHandlerPrecedence()) { + // If they have the same precedence sort lexigraphically + return o1.getObligationId().compareTo(o2.getObligationId()); + } + + if (o1.getHandlerPrecedence() < o2.getHandlerPrecedence()) { + return -1; + } + + return 1; + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/impl/AbstractXACMLObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/impl/AbstractXACMLObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/impl/AbstractXACMLObject.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.impl; + +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xml.validation.AbstractValidatingXMLObject; + +/** + * An abstract implementation of XACMLObject. + */ +public abstract class AbstractXACMLObject extends AbstractValidatingXMLObject implements XACMLObject { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AbstractXACMLObject(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/impl/AbstractXACMLObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/impl/AbstractXACMLObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/impl/AbstractXACMLObjectBuilder.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.impl; + +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.XACMLObjectBuilder; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * Base builder for {@link XACMLObject}. + * + * @param the SAML object type built + */ +public abstract class AbstractXACMLObjectBuilder extends + AbstractXMLObjectBuilder implements XACMLObjectBuilder { + + /** + * Builds a XACMLObject using the default name and namespace information provided XACML specifications. + * + * @return built XACMLObject + */ + public abstract XACMLObjectType buildObject(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/impl/AbstractXACMLObjectMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/impl/AbstractXACMLObjectMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/impl/AbstractXACMLObjectMarshaller.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe, abstract implementation of the {@link org.opensaml.xml.io.Marshaller} interface that handles most of + * the boilerplate code for Marshallers. + */ +public abstract class AbstractXACMLObjectMarshaller extends AbstractXMLObjectMarshaller { + + /** + * Constructor. + * + */ + public AbstractXACMLObjectMarshaller() { + super(); + } + + /** + * Constructor. + * + * @deprecated no replacement + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected AbstractXACMLObjectMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** + * No-op method. Extending implementations should override this method if they have attributes to marshall into the + * Element. + * + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + + } + + /** + * No-op method. Extending implementations should override this method if they have text content to marshall into + * the Element. + * + * {@inheritDoc} + */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/impl/AbstractXACMLObjectUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/impl/AbstractXACMLObjectUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/impl/AbstractXACMLObjectUnmarshaller.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.impl; + +import org.opensaml.xml.XMLObject; + +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * An thread safe abstract unmarshaller. This abstract marshaller only works with + * {@link AbstractXACMLObject}. + */ +public abstract class AbstractXACMLObjectUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** + * Constructor. + * + * @deprecated no replacement + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected AbstractXACMLObjectUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + + /** + * Constructor. + */ + public AbstractXACMLObjectUnmarshaller() { + super(); + } + + /** + * {@inheritDoc} + */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + } + + /** + * {@inheritDoc} + */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + } + + /** + * {@inheritDoc} + */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/ReferencedPoliciesTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/ReferencedPoliciesTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/ReferencedPoliciesTypeImpl.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.xacml.policy.PolicySetType; +import org.opensaml.xacml.policy.PolicyType; +import org.opensaml.xacml.profile.saml.ReferencedPoliciesType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation of {@link ReferencedPoliciesType}. + */ +public class ReferencedPoliciesTypeImpl extends AbstractSAMLObject implements ReferencedPoliciesType { + + /**List of policies.*/ + private XMLObjectChildrenList policies; + + /**List of policieSets.*/ + private XMLObjectChildrenList policieSets; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ReferencedPoliciesTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + policies = new XMLObjectChildrenList(this); + policieSets = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getPolicySets() { + return policieSets; + } + + /** {@inheritDoc} */ + public List getPolicies() { + return policies; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if(!policies.isEmpty()) { + children.addAll(policies); + } + if(!policieSets.isEmpty()) { + children.addAll(policieSets); + } + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/ReferencedPoliciesTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/ReferencedPoliciesTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/ReferencedPoliciesTypeImplBuilder.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.xacml.XACMLObjectBuilder; +import org.opensaml.xacml.profile.saml.ReferencedPoliciesType; + +/** + * Builder for {@link ReferencedPoliciesType}. + */ +public class ReferencedPoliciesTypeImplBuilder extends AbstractSAMLObjectBuilder +implements XACMLObjectBuilder{ + + /** {@inheritDoc} */ + public ReferencedPoliciesType buildObject() { + return null; + } + + /** {@inheritDoc} */ + public ReferencedPoliciesType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ReferencedPoliciesTypeImpl(namespaceURI,localName,namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/ReferencedPoliciesTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/ReferencedPoliciesTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/ReferencedPoliciesTypeMarshaller.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * Marshaller for {@link org.opensaml.xacml.profile.saml.ReferencedPoliciesType}. + */ +public class ReferencedPoliciesTypeMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/ReferencedPoliciesTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/ReferencedPoliciesTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/ReferencedPoliciesTypeUnmarshaller.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.xacml.policy.PolicySetType; +import org.opensaml.xacml.policy.PolicyType; +import org.opensaml.xacml.profile.saml.ReferencedPoliciesType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for {@link ReferencedPoliciesType}. + */ +public class ReferencedPoliciesTypeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + ReferencedPoliciesType referencedpoliciesType = (ReferencedPoliciesType) parentObject; + + if (childObject instanceof PolicyType) { + referencedpoliciesType.getPolicies().add((PolicyType) childObject); + } else if (childObject instanceof PolicySetType) { + referencedpoliciesType.getPolicySets().add((PolicySetType) childObject); + } + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionQueryTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionQueryTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionQueryTypeImpl.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,214 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.impl.RequestAbstractTypeImpl; +import org.opensaml.xacml.ctx.RequestType; +import org.opensaml.xacml.policy.PolicySetType; +import org.opensaml.xacml.policy.PolicyType; +import org.opensaml.xacml.profile.saml.ReferencedPoliciesType; +import org.opensaml.xacml.profile.saml.XACMLAuthzDecisionQueryType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** A concrete implementation of {@link XACMLAuthzDecisionQueryType}. */ +public class XACMLAuthzDecisionQueryTypeImpl extends RequestAbstractTypeImpl implements XACMLAuthzDecisionQueryType { + + /** Policy children. */ + private List policies; + + /** PolicySet children. */ + private List policySets; + + /** ReeferencedPolicies child. */ + private ReferencedPoliciesType referencedPolicies; + + /** The xacml-context:Request. */ + private RequestType request; + + /** InputContextOnly attribute value. Default = false. */ + private XSBooleanValue inputContextOnly; + + /** ReturnContext attribute value.Default = false. */ + private XSBooleanValue returnContext; + + /** CombinePolicies attribute value. Default = true. */ + private XSBooleanValue combinePolicies; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected XACMLAuthzDecisionQueryTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + setElementNamespacePrefix(namespacePrefix); + policies = new XMLObjectChildrenList(this); + policySets = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public XSBooleanValue getCombinePoliciesXSBooleanValue() { + return combinePolicies; + } + + /** {@inheritDoc} */ + public XSBooleanValue getInputContextOnlyXSBooleanValue() { + return inputContextOnly; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + if (request != null) { + children.add(request); + } + + if (!policies.isEmpty()) { + children.addAll(policies); + } + + if (!policySets.isEmpty()) { + children.addAll(policySets); + } + + if (referencedPolicies != null) { + children.add(referencedPolicies); + } + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public RequestType getRequest() { + return request; + } + + /** {@inheritDoc} */ + public XSBooleanValue getReturnContextXSBooleanValue() { + return returnContext; + } + + /** {@inheritDoc} */ + public Boolean isCombinePolicies() { + if (combinePolicies != null) { + return combinePolicies.getValue(); + } + + return Boolean.TRUE; + } + + /** {@inheritDoc} */ + public Boolean isInputContextOnly() { + if (inputContextOnly != null) { + return inputContextOnly.getValue(); + } + + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public Boolean isReturnContext() { + if (returnContext != null) { + return returnContext.getValue(); + } + + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public void setCombinePolicies(XSBooleanValue combinePolicies) { + this.combinePolicies = prepareForAssignment(this.combinePolicies, combinePolicies); + } + + /** {@inheritDoc} */ + public void setCombinePolicies(Boolean combinePolicies) { + if (combinePolicies != null) { + this.combinePolicies = prepareForAssignment(this.combinePolicies, + new XSBooleanValue(combinePolicies, false)); + } else { + this.combinePolicies = prepareForAssignment(this.combinePolicies, null); + } + + } + + /** {@inheritDoc} */ + public void setInputContextOnly(XSBooleanValue inputContextOnly) { + this.inputContextOnly = prepareForAssignment(this.inputContextOnly, inputContextOnly); + } + + /** {@inheritDoc} */ + public void setInputContextOnly(Boolean inputContextOnly) { + if (inputContextOnly != null) { + this.inputContextOnly = prepareForAssignment(this.inputContextOnly, new XSBooleanValue(inputContextOnly, + false)); + } else { + this.inputContextOnly = prepareForAssignment(this.inputContextOnly, null); + } + } + + /** {@inheritDoc} */ + public void setRequest(RequestType request) { + this.request = prepareForAssignment(this.request, request); + } + + /** {@inheritDoc} */ + public void setReturnContext(XSBooleanValue returnContext) { + this.returnContext = prepareForAssignment(this.returnContext, returnContext); + } + + /** {@inheritDoc} */ + public void setReturnContext(Boolean returnContext) { + if (returnContext != null) { + this.returnContext = prepareForAssignment(this.returnContext, new XSBooleanValue(returnContext, false)); + } else { + this.returnContext = prepareForAssignment(this.returnContext, null); + } + } + + /** {@inheritDoc} */ + public List getPolicies() { + return policies; + } + + /** {@inheritDoc} */ + public List getPolicySets() { + return policySets; + } + + /** {@inheritDoc} */ + public ReferencedPoliciesType getReferencedPolicies() { + return referencedPolicies; + } + + /** {@inheritDoc} */ + public void setReferencedPolicies(ReferencedPoliciesType policies) { + referencedPolicies = prepareForAssignment(referencedPolicies, policies); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionQueryTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionQueryTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionQueryTypeImplBuilder.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.xacml.XACMLObjectBuilder; +import org.opensaml.xacml.profile.saml.XACMLAuthzDecisionQueryType; + +/** Builder for {@link XACMLAuthzDecisionQueryType} objects. */ +public class XACMLAuthzDecisionQueryTypeImplBuilder extends AbstractSAMLObjectBuilder + implements XACMLObjectBuilder { + + /** Constructor. */ + public XACMLAuthzDecisionQueryTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public XACMLAuthzDecisionQueryType buildObject() { + return null; + } + + /** {@inheritDoc} */ + public XACMLAuthzDecisionQueryType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new XACMLAuthzDecisionQueryTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionQueryTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionQueryTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionQueryTypeMarshaller.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.saml2.core.impl.RequestAbstractTypeMarshaller; +import org.opensaml.xacml.profile.saml.XACMLAuthzDecisionQueryType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.xacml.profile.saml.XACMLAuthzDecisionQueryType} objects. + */ +public class XACMLAuthzDecisionQueryTypeMarshaller extends RequestAbstractTypeMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + XACMLAuthzDecisionQueryType query = (XACMLAuthzDecisionQueryType) samlObject; + + if (query.getInputContextOnlyXSBooleanValue() != null) { + domElement.setAttributeNS(null, XACMLAuthzDecisionQueryType.INPUTCONTEXTONLY_ATTRIB_NAME, query + .getInputContextOnlyXSBooleanValue().toString()); + } + + if (query.getReturnContextXSBooleanValue() != null) { + domElement.setAttributeNS(null, XACMLAuthzDecisionQueryType.RETURNCONTEXT_ATTRIB_NAME, query + .getReturnContextXSBooleanValue().toString()); + } + + if (query.getCombinePoliciesXSBooleanValue() != null) { + domElement.setAttributeNS(null, XACMLAuthzDecisionQueryType.COMBINEPOLICIES_ATTRIB_NAME, query + .getCombinePoliciesXSBooleanValue().toString()); + } + + super.marshallAttributes(samlObject, domElement); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionQueryTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionQueryTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionQueryTypeUnmarshaller.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.saml2.core.impl.RequestAbstractTypeUnmarshaller; +import org.opensaml.xacml.ctx.RequestType; +import org.opensaml.xacml.policy.PolicySetType; +import org.opensaml.xacml.policy.PolicyType; +import org.opensaml.xacml.profile.saml.ReferencedPoliciesType; +import org.opensaml.xacml.profile.saml.XACMLAuthzDecisionQueryType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.xacml.profile.saml.XACMLAuthzDecisionQueryType} objects. + */ +public class XACMLAuthzDecisionQueryTypeUnmarshaller extends RequestAbstractTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + XACMLAuthzDecisionQueryType xacmlauthzdecisionquery = (XACMLAuthzDecisionQueryType) parentObject; + + if (childObject instanceof RequestType) { + xacmlauthzdecisionquery.setRequest((RequestType) childObject); + } else if (childObject instanceof PolicyType) { + xacmlauthzdecisionquery.getPolicies().add((PolicyType) childObject); + } else if (childObject instanceof PolicySetType) { + xacmlauthzdecisionquery.getPolicySets().add((PolicySetType) childObject); + } else if (childObject instanceof ReferencedPoliciesType) { + xacmlauthzdecisionquery.setReferencedPolicies((ReferencedPoliciesType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + XACMLAuthzDecisionQueryType authzDS = (XACMLAuthzDecisionQueryType) samlObject; + + if (attribute.getLocalName().equals(XACMLAuthzDecisionQueryType.INPUTCONTEXTONLY_ATTRIB_NAME)) { + authzDS.setInputContextOnly(XSBooleanValue.valueOf(attribute.getValue())); + } + + if (attribute.getLocalName().equals(XACMLAuthzDecisionQueryType.RETURNCONTEXT_ATTRIB_NAME)) { + authzDS.setReturnContext(XSBooleanValue.valueOf(attribute.getValue())); + } + + if (attribute.getLocalName().equals(XACMLAuthzDecisionQueryType.COMBINEPOLICIES_ATTRIB_NAME)) { + authzDS.setCombinePolicies(XSBooleanValue.valueOf(attribute.getValue())); + } + + super.processAttribute(samlObject, attribute); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionStatementTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionStatementTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionStatementTypeImpl.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.xacml.ctx.RequestType; +import org.opensaml.xacml.ctx.ResponseType; +import org.opensaml.xacml.profile.saml.XACMLAuthzDecisionStatementType; +import org.opensaml.xml.XMLObject; + +/** A concrete implementation of {@link org.opensaml.xacml.profile.saml.XACMLAuthzDecisionStatementType}. */ +public class XACMLAuthzDecisionStatementTypeImpl extends AbstractSAMLObject implements XACMLAuthzDecisionStatementType { + + /** The request of the authorization request. */ + private RequestType request; + + /** The response of the authorization request. */ + private ResponseType response; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected XACMLAuthzDecisionStatementTypeImpl(String namespaceURI, String elementLocalName, + String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public RequestType getRequest() { + return request; + } + + /** {@inheritDoc} */ + public ResponseType getResponse() { + return response; + } + + /** {@inheritDoc} */ + public void setRequest(RequestType request) { + this.request = prepareForAssignment(this.request, request); + } + + /** {@inheritDoc} */ + public void setResponse(ResponseType response) { + this.response = prepareForAssignment(this.response, response); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (request != null) { + children.add(request); + } + if (response != null) { + children.add(response); + } + + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionStatementTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionStatementTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionStatementTypeImplBuilder.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.saml2.core.Statement; +import org.opensaml.xacml.profile.saml.XACMLAuthzDecisionStatementType; + +/** vBuilder for {@link org.opensaml.xacml.profile.saml.impl.XACMLAuthzDecisionStatementTypeImpl} objects. */ +public class XACMLAuthzDecisionStatementTypeImplBuilder extends + AbstractSAMLObjectBuilder { + + /** Constructor. */ + public XACMLAuthzDecisionStatementTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public XACMLAuthzDecisionStatementType buildObject() { + return buildObject(Statement.DEFAULT_ELEMENT_NAME, XACMLAuthzDecisionStatementType.TYPE_NAME); + } + + /** {@inheritDoc} */ + public XACMLAuthzDecisionStatementType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new XACMLAuthzDecisionStatementTypeImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionStatementTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionStatementTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionStatementTypeMarshaller.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread-safe Marshaller for {@link org.opensaml.xacml.profile.saml.XACMLAuthzDecisionStatementType}. New 27/07/2007 + */ +public class XACMLAuthzDecisionStatementTypeMarshaller extends AbstractSAMLObjectMarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionStatementTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionStatementTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLAuthzDecisionStatementTypeUnmarshaller.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.xacml.ctx.RequestType; +import org.opensaml.xacml.ctx.ResponseType; +import org.opensaml.xacml.profile.saml.XACMLAuthzDecisionStatementType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.xacml.profile.saml.XACMLAuthzDecisionStatementType}. + */ +public class XACMLAuthzDecisionStatementTypeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + XACMLAuthzDecisionStatementType xacmlauthzdecisionstatement = (XACMLAuthzDecisionStatementType) parentObject; + + if (childObject instanceof RequestType) { + xacmlauthzdecisionstatement.setRequest((RequestType) childObject); + } else if (childObject instanceof ResponseType) { + xacmlauthzdecisionstatement.setResponse((ResponseType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyQueryTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyQueryTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyQueryTypeImpl.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,79 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.impl.RequestAbstractTypeImpl; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.ctx.RequestType; +import org.opensaml.xacml.policy.IdReferenceType; +import org.opensaml.xacml.profile.saml.XACMLPolicyQueryType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Concrete implementation of {@link XACMLPolicyQueryType}. */ +public class XACMLPolicyQueryTypeImpl extends RequestAbstractTypeImpl implements XACMLPolicyQueryType { + + /** Choice group for the element. */ + private IndexedXMLObjectChildrenList choiceGroup; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + public XACMLPolicyQueryTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + setElementNamespacePrefix(namespacePrefix); + choiceGroup = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getRequests() { + return (List) choiceGroup.subList(RequestType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getPolicySetIdReferences() { + return (List) choiceGroup.subList(IdReferenceType.POLICY_SET_ID_REFERENCE_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getPolicyIdReferences() { + return (List) choiceGroup.subList(IdReferenceType.POLICY_ID_REFERENCE_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + ArrayList children = new ArrayList(); + + if(super.getOrderedChildren() != null){ + children.addAll(super.getOrderedChildren()); + } + + children.addAll(choiceGroup); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyQueryTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyQueryTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyQueryTypeImplBuilder.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.xacml.profile.saml.XACMLPolicyQueryType; + +/** Builder for {@link org.opensaml.xacml.profile.saml.XACMLPolicyQueryType} objects. */ +public class XACMLPolicyQueryTypeImplBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public XACMLPolicyQueryTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public XACMLPolicyQueryType buildObject() { + return null; + } + + /** {@inheritDoc} */ + public XACMLPolicyQueryType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new XACMLPolicyQueryTypeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyQueryTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyQueryTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyQueryTypeMarshaller.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.saml2.core.impl.RequestAbstractTypeMarshaller; + +/** Marshaller for {@link org.opensaml.xacml.profile.saml.XACMLPolicyQueryType}. */ +public class XACMLPolicyQueryTypeMarshaller extends RequestAbstractTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyQueryTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyQueryTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyQueryTypeUnmarshaller.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.saml2.core.impl.RequestAbstractTypeUnmarshaller; +import org.opensaml.xacml.ctx.RequestType; +import org.opensaml.xacml.policy.IdReferenceType; +import org.opensaml.xacml.profile.saml.XACMLPolicyQueryType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** Unmarshaller for {@link XACMLPolicyQueryType}. */ +public class XACMLPolicyQueryTypeUnmarshaller extends RequestAbstractTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + XACMLPolicyQueryType xacmlpolicyquery = (XACMLPolicyQueryType) parentObject; + + if (childObject instanceof RequestType) { + xacmlpolicyquery.getRequests().add((RequestType) childObject); + } else if (childObject.getElementQName().equals(IdReferenceType.POLICY_ID_REFERENCE_ELEMENT_NAME)) { + xacmlpolicyquery.getPolicyIdReferences().add((IdReferenceType) childObject); + } else if (childObject.getElementQName().equals(IdReferenceType.POLICY_SET_ID_REFERENCE_ELEMENT_NAME)) { + xacmlpolicyquery.getPolicySetIdReferences().add((IdReferenceType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyStatementTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyStatementTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyStatementTypeImpl.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,86 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.policy.PolicySetType; +import org.opensaml.xacml.policy.PolicyType; +import org.opensaml.xacml.profile.saml.ReferencedPoliciesType; +import org.opensaml.xacml.profile.saml.XACMLPolicyStatementType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Concrete implementation of {@link XACMLPolicyStatementType}. */ +public class XACMLPolicyStatementTypeImpl extends AbstractSAMLObject implements XACMLPolicyStatementType { + + /** Choice group in element. */ + private IndexedXMLObjectChildrenList choiceGroup; + + /** ReferencedPolicie child. */ + private ReferencedPoliciesType referencedPolicies; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected XACMLPolicyStatementTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + choiceGroup = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(choiceGroup); + + if (referencedPolicies != null) { + children.add(referencedPolicies); + } + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public List getPolicies() { + return (List) choiceGroup.subList(PolicyType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getPolicySets() { + return (List) choiceGroup.subList(PolicySetType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ReferencedPoliciesType getReferencedPolicies() { + return referencedPolicies; + } + + /** {@inheritDoc} */ + public void setReferencedPolicies(ReferencedPoliciesType policies) { + referencedPolicies = prepareForAssignment(referencedPolicies, policies); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyStatementTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyStatementTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyStatementTypeImplBuilder.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.saml2.core.Statement; +import org.opensaml.xacml.profile.saml.XACMLPolicyStatementType; + +/** Builder for {@link org.opensaml.xacml.profile.saml.impl.XACMLPolicyStatementTypeImpl} objects. */ +public class XACMLPolicyStatementTypeImplBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public XACMLPolicyStatementTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public XACMLPolicyStatementType buildObject() { + return buildObject(Statement.DEFAULT_ELEMENT_NAME, XACMLPolicyStatementType.TYPE_NAME); + } + + /** {@inheritDoc} */ + public XACMLPolicyStatementType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new XACMLPolicyStatementTypeImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyStatementTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyStatementTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyStatementTypeMarshaller.java 17 Aug 2012 15:04:54 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** A thread-safe Marshaller for {@link org.opensaml.xacml.profile.saml.XACMLAuthzDecisionStatementType}. */ +public class XACMLPolicyStatementTypeMarshaller extends AbstractSAMLObjectMarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyStatementTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyStatementTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/impl/XACMLPolicyStatementTypeUnmarshaller.java 17 Aug 2012 15:04:53 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.xacml.policy.PolicySetType; +import org.opensaml.xacml.policy.PolicyType; +import org.opensaml.xacml.profile.saml.ReferencedPoliciesType; +import org.opensaml.xacml.profile.saml.XACMLPolicyStatementType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.xacml.profile.saml.XACMLAuthzDecisionStatementType}. + */ +public class XACMLPolicyStatementTypeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + XACMLPolicyStatementType xacmlpolicystatement = (XACMLPolicyStatementType) parentObject; + + if (childObject instanceof PolicyType) { + xacmlpolicystatement.getPolicies().add((PolicyType) childObject); + } else if (childObject instanceof PolicySetType) { + xacmlpolicystatement.getPolicySets().add((PolicySetType) childObject); + } else if (childObject instanceof ReferencedPoliciesType) { + xacmlpolicystatement.setReferencedPolicies((ReferencedPoliciesType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/util/SimpleURLCanonicalizer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/SimpleURLCanonicalizer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/SimpleURLCanonicalizer.java 17 Aug 2012 15:09:10 -0000 1.1 @@ -0,0 +1,119 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util; + +import java.util.HashMap; +import java.util.Map; + +/** + * This class performs simple canonicalization of a URL as follows: + * + *

+ *

+ *

+ * + *

+ *

+ */ +public final class SimpleURLCanonicalizer { + + /** The scheme-to-port mapping data. */ + private static Map schemePortMap = new HashMap(); + + /** Constructor to prevent instantiation. */ + private SimpleURLCanonicalizer() {} + + /** + * Register a new scheme-to-port mapping. + * + * @param scheme the scheme to register + * @param port the default port for that scheme + */ + public static void registerSchemePortMapping(String scheme, Integer port) { + if (scheme == null || port == null) { + throw new IllegalArgumentException("Scheme and port may not be null"); + } + schemePortMap.put(scheme.toLowerCase(), port); + } + + /** + * Deregister a scheme-to-port mapping. + * + * @param scheme the scheme to deregister + */ + public static void deregisterSchemePortMapping(String scheme) { + if (scheme == null) { + throw new IllegalArgumentException("Scheme may not be null"); + } + schemePortMap.remove(scheme.toLowerCase()); + } + + /** + * Obtain the default port registered for a scheme. + * + * @param scheme the scheme to look up + * @return the default port registered for the scheme, or null if none registered + */ + public static Integer getRegisteredPort(String scheme) { + return schemePortMap.get(scheme.toLowerCase()); + } + + /** + * Canonicalize the supplied URL. + * + * @param url the URL to canonicalize + * @return the canonicalized URL + */ + public static String canonicalize(String url) { + URLBuilder urlBuilder = new URLBuilder(url); + canonicalize(urlBuilder); + return urlBuilder.buildURL(); + } + + /** + * Canonicalize the supplied URLBuilder data. + * + * @param url the URLBuilder to canonicalize + */ + private static void canonicalize(URLBuilder url) { + if (url.getScheme() != null) { + url.setScheme(url.getScheme().toLowerCase()); + + String scheme = url.getScheme(); + Integer port = getRegisteredPort(scheme); + if (port != null && port == url.getPort()) { + url.setPort(0); + } + } + + if (url.getHost() != null) { + url.setHost(url.getHost().toLowerCase()); + } + } + + static { + registerSchemePortMapping("ftp", 23); + registerSchemePortMapping("http", 80); + registerSchemePortMapping("https", 443); + } + +} Index: 3rdParty_sources/openws/org/opensaml/util/URLBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/URLBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/URLBuilder.java 17 Aug 2012 15:09:10 -0000 1.1 @@ -0,0 +1,346 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.ws.transport.http.HTTPTransportUtils; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.Pair; + +/** + * Utility class for building URLs. May also be used to parse a URL into its invidual components. All components will be + * converted UTF-8 encoding and then application/x-www-form-urlencoded when built. + * + * This class is not thread-safe. + */ +public class URLBuilder { + + /** URL schema (http, https, etc). */ + private String scheme; + + /** User name in the URL. */ + private String username; + + /** Password in the URL. */ + private String password; + + /** Host for the URL. */ + private String host; + + /** URL port number. */ + private int port; + + /** URL path. */ + private String path; + + /** Parameters in the query string. */ + private List> queryParams; + + /** URL fragment. */ + private String fragement; + + /** + * Constructor. + */ + public URLBuilder() { + queryParams = new ArrayList>(); + } + + /** + * Constructor. + * + * @param baseURL URL to parse and use as basis for creating other URLs + * + * @throws IllegalArgumentException thrown if the given base URL is not well formed + */ + public URLBuilder(String baseURL) { + try { + URL url = new URL(baseURL); + + setScheme(url.getProtocol()); + + String userInfo = url.getUserInfo(); + if (!DatatypeHelper.isEmpty(userInfo)) { + if (userInfo.contains(":")) { + String[] userInfoComps = userInfo.split(":"); + setUsername(HTTPTransportUtils.urlDecode(userInfoComps[0])); + setPassword(HTTPTransportUtils.urlDecode(userInfoComps[1])); + } else { + setUsername(userInfo); + } + } + + setHost(url.getHost()); + setPort(url.getPort()); + setPath(url.getPath()); + + queryParams = new ArrayList>(); + String queryString = url.getQuery(); + if (!DatatypeHelper.isEmpty(queryString)) { + String[] queryComps = queryString.split("&"); + String queryComp; + String[] paramComps; + String paramName; + String paramValue; + for (int i = 0; i < queryComps.length; i++) { + queryComp = queryComps[i]; + if (!queryComp.contains("=")) { + paramName = HTTPTransportUtils.urlDecode(queryComp); + queryParams.add(new Pair(paramName, null)); + } else { + paramComps = queryComp.split("="); + paramName = HTTPTransportUtils.urlDecode(paramComps[0]); + paramValue = HTTPTransportUtils.urlDecode(paramComps[1]); + queryParams.add(new Pair(paramName, paramValue)); + } + } + } + + setFragment(url.getRef()); + } catch (MalformedURLException e) { + throw new IllegalArgumentException("Given URL is not well formed", e); + } + } + + /** + * Gets the URL fragment in its decoded form. + * + * @return URL fragment in its decoded form + */ + public String getFragment() { + return fragement; + } + + /** + * Sets the URL fragment in its decoded form. + * + * @param newFragment URL fragment in its decoded form + */ + public void setFragment(String newFragment) { + fragement = DatatypeHelper.safeTrimOrNullString(newFragment); + } + + /** + * Gets the host component of the URL. + * + * @return host component of the URL + */ + public String getHost() { + return host; + } + + /** + * Sets the host component of the URL. + * + * @param newHost host component of the URL + */ + public void setHost(String newHost) { + host = DatatypeHelper.safeTrimOrNullString(newHost); + } + + /** + * Gets the user's password in the URL. + * + * @return user's password in the URL + */ + public String getPassword() { + return password; + } + + /** + * Sets the user's password in the URL. + * + * @param newPassword user's password in the URL + */ + public void setPassword(String newPassword) { + password = DatatypeHelper.safeTrimOrNullString(newPassword); + } + + /** + * Gets the path component of the URL. + * + * @return path component of the URL + */ + public String getPath() { + return path; + } + + /** + * Sets the path component of the URL. + * + * @param newPath path component of the URL + */ + public void setPath(String newPath) { + path = DatatypeHelper.safeTrimOrNullString(newPath); + } + + /** + * Gets the port component of the URL. + * + * @return port component of the URL + */ + public int getPort() { + return port; + } + + /** + * Sets the port component of the URL. + * + * @param newPort port component of the URL + */ + public void setPort(int newPort) { + port = newPort; + } + + /** + * Gets the query string parameters for the URL. Params may be added and removed through the map interface. + * + * @return query string parameters for the URL + */ + public List> getQueryParams() { + return queryParams; + } + + /** + * Gets the URL scheme (http, https, etc). + * + * @return URL scheme (http, https, etc) + */ + public String getScheme() { + return scheme; + } + + /** + * Sets the URL scheme (http, https, etc). + * + * @param newScheme URL scheme (http, https, etc) + */ + public void setScheme(String newScheme) { + scheme = DatatypeHelper.safeTrimOrNullString(newScheme); + } + + /** + * Gets the user name component of the URL. + * + * @return user name component of the URL + */ + public String getUsername() { + return username; + } + + /** + * Sets the user name component of the URL. + * + * @param newUsername user name component of the URL + */ + public void setUsername(String newUsername) { + username = DatatypeHelper.safeTrimOrNullString(newUsername); + } + + /** + * Builds a URL from the given data. The constructured URL may not be valid if sufficient information is not + * provided. The returned URL will be appropriately encoded using application/x-www-form-urlencoded with appropriate + * encoding of UTF-8 characters. + * + * @return URL built from the given data + */ + public String buildURL() { + StringBuilder builder = new StringBuilder(); + + if (!DatatypeHelper.isEmpty(scheme)) { + builder.append(scheme); + builder.append("://"); + } + + if (!DatatypeHelper.isEmpty(username)) { + builder.append(username); + if (!DatatypeHelper.isEmpty(password)) { + builder.append(":"); + builder.append(password); + } + + builder.append("@"); + } + + if (!DatatypeHelper.isEmpty(host)) { + builder.append(host); + if (port > 0) { + builder.append(":"); + builder.append(Integer.toString(port)); + } + } + + if (!DatatypeHelper.isEmpty(path)) { + if (!path.startsWith("/")) { + builder.append("/"); + } + builder.append(path); + } + + String queryString = buildQueryString(); + if (!DatatypeHelper.isEmpty(queryString)) { + builder.append("?"); + builder.append(queryString); + } + + if (!DatatypeHelper.isEmpty(fragement)) { + builder.append("#"); + builder.append(fragement); + } + + return builder.toString(); + } + + /** + * Builds the query string for the URL. + * + * @return query string for the URL or null if there are now query parameters + */ + public String buildQueryString() { + StringBuilder builder = new StringBuilder(); + if (queryParams.size() > 0) { + String name; + String value; + + Pair param; + for (int i = 0; i < queryParams.size(); i++) { + param = queryParams.get(i); + name = DatatypeHelper.safeTrimOrNullString(param.getFirst()); + + if (name != null) { + builder.append(HTTPTransportUtils.urlEncode(name)); + value = DatatypeHelper.safeTrimOrNullString(param.getSecond()); + if (value != null) { + builder.append("="); + builder.append(HTTPTransportUtils.urlEncode(value)); + } + if (i < queryParams.size() - 1) { + builder.append("&"); + } + } + } + return builder.toString(); + } + + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/package.html 17 Aug 2012 15:09:10 -0000 1.1 @@ -0,0 +1,5 @@ + + +General utility classes. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/AbstractFilteredResource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/AbstractFilteredResource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/AbstractFilteredResource.java 17 Aug 2012 15:09:13 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.resource; + +import java.io.InputStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** A {@link Resource} whose contents may be run through a filter as it is being read. */ +public abstract class AbstractFilteredResource implements Resource { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(AbstractFilteredResource.class); + + /** Associated resource filter. */ + private ResourceFilter resourceFilter; + + /** Constructor. */ + protected AbstractFilteredResource() { + + } + + /** + * Constructor. + * + * @param filter the filter used on the resource + * + * @deprecated use {@link #setResourceFilter(ResourceFilter)} instead + */ + protected AbstractFilteredResource(ResourceFilter filter) { + resourceFilter = filter; + } + + /** + * Gets the resource filter associated with this resource. + * + * @return resource filter associated with this resource + */ + public ResourceFilter getResourceFilter() { + return resourceFilter; + } + + /** + * Sets the resource filter associated with this resource. + * + * @param filter filter associated with this resource + */ + public void setResourceFilter(ResourceFilter filter){ + resourceFilter = filter; + } + + /** + * Applies the filter to the given stream resulting in the returned stream. If no filter is set than the given + * stream is the returned stream. + * + * @param stream the stream to filter + * + * @return the filtered stream + * + * @throws ResourceException thrown if the filter can not be applied to the stream + */ + protected InputStream applyFilter(InputStream stream) throws ResourceException { + ResourceFilter filter = getResourceFilter(); + if (filter != null) { + log.debug("Apply filter '{}' to resource '{}'", filter.getClass(), this.getLocation()); + return getResourceFilter().applyFilter(stream); + } else { + return stream; + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/ChainingResourceFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/ChainingResourceFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/ChainingResourceFilter.java 17 Aug 2012 15:09:13 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.resource; + +import java.io.InputStream; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Resource filter that executes a list of resource filters in order. */ +public class ChainingResourceFilter implements ResourceFilter { + + /** Class logger. */ + private Logger log = LoggerFactory.getLogger(ChainingResourceFilter.class); + + /** Registered resource filters. */ + private List resourceFilters; + + /** + * Constructor. + * + * @param filters resource filters to execute in order + */ + public ChainingResourceFilter(List filters) { + resourceFilters = filters; + } + + /** {@inheritDoc} */ + public InputStream applyFilter(InputStream resource) throws ResourceException { + if (resourceFilters == null || resourceFilters.isEmpty()) { + log.debug("No resource filters configured, nothing to do"); + return resource; + } + + for (ResourceFilter filter : resourceFilters) { + log.debug("Applying filter '{}'", filter.getClass().getName()); + resource = filter.applyFilter(resource); + } + + return resource; + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/ClasspathResource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/ClasspathResource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/ClasspathResource.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,139 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.resource; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import org.joda.time.DateTime; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Resource that represents a resource found on the classpath. + * + * Because object on the classpath are not meant to change during runtime the last modification is set to the time the + * {@link ClasspathResource} is created and is never changed. + */ +public class ClasspathResource extends AbstractFilteredResource { + + /** Classpath location of resource. */ + private URL resource; + + /** Last modification time, set to when resources is created. */ + private DateTime lastModTime; + + /** + * Constructor. + * + * @param path the path to the file for this resource + * + * @throws ResourceException thrown if the resource path is null or empty or if the resource does not exist + */ + public ClasspathResource(String path) throws ResourceException { + super(); + + if (DatatypeHelper.isEmpty(path)) { + throw new ResourceException("Resource path may not be null or empty"); + } + + resource = getClass().getResource(path); + if (resource == null) { + throw new ResourceException("Classpath resource does not exist: " + path); + } + + lastModTime = new DateTime(); + } + + /** + * Constructor. + * + * @param path the path to the file for this resource + * @param resourceFilter filter to apply to this resource + * + * @throws ResourceException thrown if the resource path is null or empty or if the resource does not exist + * + * @deprecated use {@link #setResourceFilter(ResourceFilter)} instead + */ + public ClasspathResource(String path, ResourceFilter resourceFilter) throws ResourceException { + super(resourceFilter); + + if (DatatypeHelper.isEmpty(path)) { + throw new ResourceException("Resource path may not be null or empty"); + } + + resource = getClass().getResource(path); + if (resource == null) { + throw new ResourceException("Classpath resource does not exist: " + path); + } + + lastModTime = new DateTime(); + } + + /** {@inheritDoc} */ + public boolean exists() throws ResourceException { + if (resource != null) { + return true; + } + + return false; + } + + /** {@inheritDoc} */ + public InputStream getInputStream() throws ResourceException { + try { + InputStream ins = resource.openStream(); + return applyFilter(ins); + } catch (IOException e) { + throw new ResourceException("Unable to open resource: " + resource); + } + } + + /** {@inheritDoc} */ + public DateTime getLastModifiedTime() throws ResourceException { + return lastModTime; + } + + /** {@inheritDoc} */ + public String getLocation() { + return resource.toString(); + } + + /** {@inheritDoc} */ + public String toString() { + return getLocation(); + } + + /** {@inheritDoc} */ + public int hashCode() { + return getLocation().hashCode(); + } + + /** {@inheritDoc} */ + public boolean equals(Object o) { + if (o == this) { + return true; + } + + if (o instanceof ClasspathResource) { + return getLocation().equals(((ClasspathResource) o).getLocation()); + } + + return false; + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/FileBackedHttpResource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/FileBackedHttpResource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/FileBackedHttpResource.java 17 Aug 2012 15:09:13 -0000 1.1 @@ -0,0 +1,181 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.resource; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; + +import org.apache.commons.httpclient.methods.GetMethod; +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * A resource representing a file read from an HTTP(S) location. Every time the file is successfully read from the URL + * location it is written to a backing file. If the file can not be read from the URL it is read from this backing file, + * if available. + * + * Note, large files should not be accessed in this manner as the entire file is read into memory before being written + * to disk and then returned. + */ +public class FileBackedHttpResource extends HttpResource { + + /** Backing resource file. */ + private File resourceFile; + + /** + * Constructor. + * + * @param resource HTTP(S) URL of the resource + * @param backingFile filesystem location to store the resource + */ + public FileBackedHttpResource(String resource, String backingFile) { + super(resource); + + if (DatatypeHelper.isEmpty(backingFile)) { + throw new IllegalArgumentException("Backing file path may not be null or empty"); + } + + resourceFile = new File(backingFile); + } + + /** + * Constructor. + * + * @param resource HTTP(S) URL of the resource + * @param backingFile file: URI location to store the resource + * + * @since 1.2 + */ + public FileBackedHttpResource(String resource, URI backingFile) { + super(resource); + + if (backingFile == null) { + throw new IllegalArgumentException("Backing file path may not be null or empty"); + } + + resourceFile = new File(backingFile); + } + + /** + * Constructor. + * + * @param resource HTTP(S) URL of the resource + * @param backingFile filesystem location to store the resource + * @param resourceFilter filter to apply to this resource + * + * @deprecated use {@link #setResourceFilter(ResourceFilter)} instead + */ + public FileBackedHttpResource(String resource, String backingFile, ResourceFilter resourceFilter) { + super(resource, resourceFilter); + + if (DatatypeHelper.isEmpty(backingFile)) { + throw new IllegalArgumentException("Backing file path may not be null or empty"); + } + + resourceFile = new File(backingFile); + } + + /** + * Constructor. + * + * @param resource HTTP(S) URL of the resource + * @param backingFile filesystem location to store the resource + * @param resourceFilter filter to apply to this resource + * + * @since 1.2 + * @deprecated use {@link #setResourceFilter(ResourceFilter)} instead + */ + public FileBackedHttpResource(String resource, URI backingFile, ResourceFilter resourceFilter) { + super(resource, resourceFilter); + + if (backingFile == null) { + throw new IllegalArgumentException("Backing file path may not be null or empty"); + } + + resourceFile = new File(backingFile); + } + + /** {@inheritDoc} */ + public boolean exists() throws ResourceException { + if (!super.exists()) { + return resourceFile.exists(); + } + + return true; + } + + /** {@inheritDoc} */ + public InputStream getInputStream() throws ResourceException { + InputStream ins = null; + try { + GetMethod getMethod = super.getResource(); + byte[] response = getMethod.getResponseBody(); + saveToResourceFile(response); + ins = getMethod.getResponseBodyAsStream(); + } catch (Exception e) { + try { + ins = new FileInputStream(resourceFile); + } catch (IOException ioe) { + throw new ResourceException("Unable to read resource URL or backing file " + + resourceFile.getAbsolutePath(), ioe); + } + } + + return applyFilter(ins); + } + + /** {@inheritDoc} */ + public DateTime getLastModifiedTime() throws ResourceException { + try { + return super.getLastModifiedTime(); + } catch (ResourceException e) { + long lastModifiedTime = resourceFile.lastModified(); + if (lastModifiedTime == 0) { + throw new ResourceException("URL resource is not reachable and backing file is not readable"); + } + + return new DateTime(lastModifiedTime, ISOChronology.getInstanceUTC()); + } + } + + /** {@inheritDoc} */ + public String getLocation() { + return super.getLocation(); + } + + /** + * Saves a resource to the backing file. + * + * @param resource the string representation of the resource + * + * @throws ResourceException thrown if the resource backing file can not be written to + */ + protected void saveToResourceFile(byte[] resource) throws ResourceException { + try { + FileOutputStream out = new FileOutputStream(resourceFile); + out.write(resource); + } catch (IOException e) { + throw new ResourceException("Unable to write resource to backing file " + resourceFile.getAbsolutePath(), e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/FilesystemResource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/FilesystemResource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/FilesystemResource.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,166 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.resource; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.net.URI; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * A resource representing a file on the local filesystem. + */ +public class FilesystemResource extends AbstractFilteredResource { + + /** The file represented by this resource. */ + private File resource; + + /** + * Constructor. + * + * @param resourcePath the path to the file for this resource + * + * @throws ResourceException thrown if the resource path is null or empty + */ + public FilesystemResource(String resourcePath) throws ResourceException { + super(); + + if (DatatypeHelper.isEmpty(resourcePath)) { + throw new ResourceException("Resource path may not be null or empty"); + } + + resource = new File(resourcePath); + } + + /** + * Constructor. + * + * @param resourceURI file: URI to the file + * + * @throws ResourceException thrown if the resource path is null or empty + * + * @since 1.2.0 + */ + public FilesystemResource(URI resourceURI) throws ResourceException { + super(); + + if (resourceURI == null) { + throw new ResourceException("Resource URL may not be null"); + } + + resource = new File(resourceURI); + } + + /** + * Constructor. + * + * @param resourcePath the path to the file for this resource + * @param resourceFilter filter to apply to this resource + * + * @throws ResourceException thrown if the resource path is null or empty + * + * @deprecated use {@link #setResourceFilter(ResourceFilter)} instead + */ + public FilesystemResource(String resourcePath, ResourceFilter resourceFilter) throws ResourceException { + super(resourceFilter); + + if (DatatypeHelper.isEmpty(resourcePath)) { + throw new ResourceException("Resource path may not be null or empty"); + } + + resource = new File(resourcePath); + } + + /** + * Constructor. + * + * @param resourceURI the file: URI to the file for this resource + * @param resourceFilter filter to apply to this resource + * + * @throws ResourceException thrown if the resource path is null or empty + * + * @since 1.2.0 + * @deprecated use {@link #setResourceFilter(ResourceFilter)} instead + */ + public FilesystemResource(URI resourceURI, ResourceFilter resourceFilter) throws ResourceException { + super(resourceFilter); + + if (resourceURI == null) { + throw new ResourceException("Resource URI may not be null"); + } + + resource = new File(resourceURI); + } + + /** {@inheritDoc} */ + public boolean exists() throws ResourceException { + return resource.exists(); + } + + /** {@inheritDoc} */ + public InputStream getInputStream() throws ResourceException { + try { + FileInputStream ins = new FileInputStream(resource); + return applyFilter(ins); + } catch (FileNotFoundException e) { + throw new ResourceException("Resource file does not exist: " + resource.getAbsolutePath()); + } + } + + /** {@inheritDoc} */ + public DateTime getLastModifiedTime() throws ResourceException { + if (!resource.exists()) { + throw new ResourceException("Resource file does not exist: " + resource.getAbsolutePath()); + } + + return new DateTime(resource.lastModified(), ISOChronology.getInstanceUTC()); + } + + /** {@inheritDoc} */ + public String getLocation() { + return resource.getAbsolutePath(); + } + + /** {@inheritDoc} */ + public String toString() { + return getLocation(); + } + + /** {@inheritDoc} */ + public int hashCode() { + return getLocation().hashCode(); + } + + /** {@inheritDoc} */ + public boolean equals(Object o) { + if (o == this) { + return true; + } + + if (o instanceof FilesystemResource) { + return getLocation().equals(((FilesystemResource) o).getLocation()); + } + + return false; + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/HttpResource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/HttpResource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/HttpResource.java 17 Aug 2012 15:09:13 -0000 1.1 @@ -0,0 +1,179 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.resource; + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.HeadMethod; +import org.apache.commons.httpclient.util.DateParseException; +import org.apache.commons.httpclient.util.DateUtil; +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * A resource representing a file retrieved from a URL using Apache Commons HTTPClient. + */ +public class HttpResource extends AbstractFilteredResource { + + /** HTTP URL of the resource. */ + private String resourceUrl; + + /** HTTP client. */ + private HttpClient httpClient; + + /** + * Constructor. + * + * @param resource HTTP(S) URL of the resource + */ + public HttpResource(String resource) { + super(); + + resourceUrl = DatatypeHelper.safeTrimOrNullString(resource); + if (resourceUrl == null) { + throw new IllegalArgumentException("Resource URL may not be null or empty"); + } + + httpClient = new HttpClient(); + } + + /** + * Constructor. + * + * @param resource HTTP(S) URL of the resource + * @param resourceFilter filter to apply to this resource + * + * @deprecated use {@link #setResourceFilter(ResourceFilter)} instead + */ + public HttpResource(String resource, ResourceFilter resourceFilter) { + super(resourceFilter); + + resourceUrl = DatatypeHelper.safeTrimOrNullString(resource); + if (resourceUrl == null) { + throw new IllegalArgumentException("Resource URL may not be null or empty"); + } + + httpClient = new HttpClient(); + } + + /** {@inheritDoc} */ + public boolean exists() throws ResourceException { + HeadMethod headMethod = new HeadMethod(resourceUrl); + + try { + httpClient.executeMethod(headMethod); + if (headMethod.getStatusCode() != HttpStatus.SC_OK) { + return false; + } + + return true; + } catch (IOException e) { + throw new ResourceException("Unable to contact resource URL: " + resourceUrl, e); + } + } + + /** {@inheritDoc} */ + public InputStream getInputStream() throws ResourceException { + GetMethod getMethod = getResource(); + try { + return applyFilter(getMethod.getResponseBodyAsStream()); + } catch (IOException e) { + throw new ResourceException("Unable to read response", e); + } + } + + /** {@inheritDoc} */ + public DateTime getLastModifiedTime() throws ResourceException { + HeadMethod headMethod = new HeadMethod(resourceUrl); + + try { + httpClient.executeMethod(headMethod); + if (headMethod.getStatusCode() != HttpStatus.SC_OK) { + throw new ResourceException("Unable to retrieve resource URL " + resourceUrl + + ", received HTTP status code " + headMethod.getStatusCode()); + } + Header lastModifiedHeader = headMethod.getResponseHeader("Last-Modified"); + if (lastModifiedHeader != null && ! DatatypeHelper.isEmpty(lastModifiedHeader.getValue())) { + long lastModifiedTime = DateUtil.parseDate(lastModifiedHeader.getValue()).getTime(); + return new DateTime(lastModifiedTime, ISOChronology.getInstanceUTC()); + } + + return new DateTime(); + } catch (IOException e) { + throw new ResourceException("Unable to contact resource URL: " + resourceUrl, e); + } catch (DateParseException e) { + throw new ResourceException("Unable to parse last modified date for resource:" + resourceUrl, e); + } + } + + /** {@inheritDoc} */ + public String getLocation() { + return resourceUrl; + } + + /** {@inheritDoc} */ + public String toString() { + return getLocation(); + } + + /** {@inheritDoc} */ + public int hashCode() { + return getLocation().hashCode(); + } + + /** {@inheritDoc} */ + public boolean equals(Object o) { + if (o == this) { + return true; + } + + if (o instanceof HttpResource) { + return getLocation().equals(((HttpResource) o).getLocation()); + } + + return false; + } + + /** + * Gets remote resource. + * + * @return the remove resource + * + * @throws ResourceException thrown if the resource could not be fetched + */ + protected GetMethod getResource() throws ResourceException { + GetMethod getMethod = new GetMethod(resourceUrl); + + try { + httpClient.executeMethod(getMethod); + if (getMethod.getStatusCode() != HttpStatus.SC_OK) { + throw new ResourceException("Unable to retrieve resource URL " + resourceUrl + + ", received HTTP status code " + getMethod.getStatusCode()); + } + return getMethod; + } catch (IOException e) { + throw new ResourceException("Unable to contact resource URL: " + resourceUrl, e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/PropertyReplacementResourceFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/PropertyReplacementResourceFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/PropertyReplacementResourceFilter.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.resource; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Iterator; +import java.util.Properties; + +import org.opensaml.xml.util.DatatypeHelper; + +/** + * A resource filter that buffers a resource into a string and replaces instance of macros with properties read from a + * file. Macros are of the syntax '${MACRO_NAME}', the same syntax used within the Java Expression Language. + * + * The property file is read at invocation of this filter. + * + * The {@link InputStream} should be a character stream as {@link InputStreamReader} will be used to convert the stream + * into a string. + */ +public class PropertyReplacementResourceFilter implements ResourceFilter { + + /** Location of the property file. */ + private File propertyFilePath; + + /** + * Constructor. + * + * @param propertyFile property file whose properties will be expanded within the resource + */ + public PropertyReplacementResourceFilter(File propertyFile) { + if (propertyFile == null) { + throw new IllegalArgumentException("Property file may not be null"); + } + propertyFilePath = propertyFile; + } + + /** {@inheritDoc} */ + @SuppressWarnings("unchecked") + public InputStream applyFilter(InputStream resource) throws ResourceException { + Properties props = new Properties(); + try { + props.load(new FileInputStream(propertyFilePath)); + } catch (IOException e) { + throw new ResourceException("Unable to read property file", e); + } + + if(props.isEmpty()){ + return resource; + } + + try { + String resourceString = DatatypeHelper.inputstreamToString(resource, null); + + Iterator keyItr = (Iterator) props.propertyNames(); + String key; + while (keyItr.hasNext()) { + key = keyItr.next(); + resourceString = resourceString.replace("${" + key + "}", props.getProperty(key)); + } + + resourceString.trim(); + return new ByteArrayInputStream(resourceString.getBytes()); + } catch (IOException e) { + throw new ResourceException("Unable to read contents of resource", e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/Resource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/Resource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/Resource.java 17 Aug 2012 15:09:13 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.resource; + +import java.io.InputStream; + +import org.joda.time.DateTime; + +/** An interface representing an data resource. */ +public interface Resource { + + /** + * Gets resource location information. Examples might be filesystem path, URL, etc. + * + * @return resource location information + */ + public String getLocation(); + + /** + * Checks whether the resource exists. + * + * @return true if the resource exists, false if not + * + * @throws ResourceException thrown if there is a problem determining if the resource exists + */ + public boolean exists() throws ResourceException; + + /** + * Gets the inputstream to the resource's data. + * + * @return inputstream to the resource's data + * + * @throws ResourceException thrown if an input stream can not be created for the resource + */ + public InputStream getInputStream() throws ResourceException; + + /** + * Gets the date and time the resource was last modified. + * + * @return date and time the resource was last modified + * + * @throws ResourceException thrown if the last modified time can not be determined + */ + public DateTime getLastModifiedTime() throws ResourceException; +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/ResourceChangeListener.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/ResourceChangeListener.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/ResourceChangeListener.java 17 Aug 2012 15:09:13 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.resource; + +/** + * A resource change listener. + */ +public interface ResourceChangeListener{ + + /** Types of change events; creation, update, and deletion. */ + public enum ResourceChange{ CREATION, UPDATE, DELETE}; + + /** + * Called when a resource is created. + * + * @param resource the resource that was created + */ + public void onResourceCreate(Resource resource); + + /** + * Called when a resource is update. + * + * @param resource the resource that was updated + */ + public void onResourceUpdate(Resource resource); + + /** + * Called when a resource is deleted. + * + * @param resource the resource that was deleted + */ + public void onResourceDelete(Resource resource); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/ResourceChangeWatcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/ResourceChangeWatcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/ResourceChangeWatcher.java 17 Aug 2012 15:09:13 -0000 1.1 @@ -0,0 +1,209 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.resource; + +import java.util.ArrayList; +import java.util.List; +import java.util.TimerTask; + +import org.joda.time.DateTime; +import org.opensaml.util.resource.ResourceChangeListener.ResourceChange; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A watcher that invokes a callback when a resource update/deletion has been detected. + */ +public class ResourceChangeWatcher extends TimerTask { + + /** Default polling frequency, 12 hours. */ + public static final long DEFAULT_POLL_FREQUENCY = 1000 * 60 * 60 * 12; + + /** Default maximum retry attempts, 0. */ + public static final int DEFAULT_MAX_RETRY_ATTEMPTS = 0; + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(ResourceChangeWatcher.class); + + /** Resource being watched. */ + private Resource watchedResource; + + /** Frequency, in milliseconds, the resource is polled for changes. */ + private long pollFrequency; + + /** Max number of polls to try before considering the resource inaccessible. */ + private int maxRetryAttempts; + + /** Number of times the resource has been polled but generated an error. */ + private int currentRetryAttempts; + + /** Whether the resource currently exists. */ + private boolean resourceExist; + + /** Last time the resource was modified. */ + private DateTime lastModification; + + /** Registered listeners of resource change notifications. */ + private List resourceListeners; + + /** + * Constructor. + * + * @param resource the resource to be watched + * + * @throws ResourceException thrown if resource existence or last modification time can not be determined + */ + public ResourceChangeWatcher(Resource resource) throws ResourceException { + this(resource, DEFAULT_POLL_FREQUENCY, DEFAULT_MAX_RETRY_ATTEMPTS); + } + + /** + * Constructor. + * + * @param resource the resource to be watched + * @param pollingFrequency the frequency, in milliseconds, to poll the resource for changes + * + * @throws ResourceException thrown if resource existence or last modification time can not be determined + */ + public ResourceChangeWatcher(Resource resource, long pollingFrequency) throws ResourceException { + this(resource, pollingFrequency, DEFAULT_MAX_RETRY_ATTEMPTS); + } + + /** + * Constructor. + * + * @param resource the resource to be watched + * @param pollingFrequency the frequency, in milliseconds, to poll the resource for changes + * @param retryAttempts maximum number of poll attempts before the resource is considered inaccessible + * + * @throws ResourceException thrown if resource existence or last modification time can not be determined + */ + public ResourceChangeWatcher(Resource resource, long pollingFrequency, int retryAttempts) throws ResourceException { + if (resource == null) { + throw new NullPointerException("Watched resource is null"); + } + + if (pollingFrequency <= 0) { + throw new IllegalArgumentException("Polling frequency must be greater than zero"); + } + + if (retryAttempts < 0) { + throw new IllegalArgumentException("Max retry attempts must be greater than, or equal to, zero"); + } + + watchedResource = resource; + pollFrequency = pollingFrequency; + maxRetryAttempts = retryAttempts; + currentRetryAttempts = 0; + + if (watchedResource.exists()) { + resourceExist = true; + lastModification = watchedResource.getLastModifiedTime(); + } else { + resourceExist = false; + } + + resourceListeners = new ArrayList(5); + log.debug("Watching resource: " + watchedResource.getLocation() + + ", polling frequency: {}ms, max retry attempts: {}", pollFrequency, maxRetryAttempts); + } + + /** + * Gets the frequency, in milliseconds, the watched resource should be polled. + * + * @return frequency the watched resource should be polled + */ + public long getPollingFrequency() { + return pollFrequency; + } + + /** + * Gets the list of registered resource listeners. New listeners may be registered with the list or old ones + * removed. + * + * @return list of registered resource listeners + */ + public List getResourceListeners() { + return resourceListeners; + } + + /** {@inheritDoc} */ + public void run() { + try { + log.trace("Checking resource for changes: {}", watchedResource.getLocation()); + if (watchedResource.exists()) { + if (!resourceExist) { + resourceExist = true; + signalListeners(ResourceChange.CREATION); + lastModification = watchedResource.getLastModifiedTime(); + } else { + if (lastModification.isBefore(watchedResource.getLastModifiedTime())) { + signalListeners(ResourceChange.UPDATE); + lastModification = watchedResource.getLastModifiedTime(); + } + } + } else { + if (resourceExist) { + resourceExist = false; + signalListeners(ResourceChange.DELETE); + } + } + currentRetryAttempts = 0; + } catch (ResourceException e) { + log.warn("Resource " + watchedResource.getLocation() + " could not be accessed", e); + currentRetryAttempts++; + if (currentRetryAttempts >= maxRetryAttempts) { + cancel(); + log.error("Resource " + watchedResource.getLocation() + + " was not accessible for max number of retry attempts. This resource will no longer be watched"); + } + } + } + + /** + * Signals all registered listeners of a resource change. + * + * @param changeType the resource change type + */ + protected void signalListeners(ResourceChange changeType) { + synchronized (resourceListeners) { + switch (changeType) { + case CREATION: + log.debug("Publishing creation event for resource: {}", watchedResource.getLocation()); + for (ResourceChangeListener listener : resourceListeners) { + listener.onResourceCreate(watchedResource); + } + break; + case UPDATE: + log.debug("Publishing update event for resource: {}", watchedResource.getLocation()); + for (ResourceChangeListener listener : resourceListeners) { + listener.onResourceUpdate(watchedResource); + } + break; + case DELETE: + log.debug("Publishing delete event for resource: {}", watchedResource.getLocation()); + for (ResourceChangeListener listener : resourceListeners) { + listener.onResourceDelete(watchedResource); + } + break; + default: + break; + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/ResourceException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/ResourceException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/ResourceException.java 17 Aug 2012 15:09:13 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.resource; + +/** + * Indicates a problem accessing a resource. + */ +public class ResourceException extends Exception { + + /** Serial version UID. */ + private static final long serialVersionUID = -3347987371630094896L; + + /** + * Constructor. + */ + public ResourceException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public ResourceException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public ResourceException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public ResourceException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/ResourceFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/ResourceFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/ResourceFilter.java 17 Aug 2012 15:09:13 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.resource; + +import java.io.InputStream; + +/** Filter that operates over a resource. Filters may perform any logic on the incoming stream. */ +public interface ResourceFilter { + + /** + * Applies this filter to the given stream. + * + * @param resource Resource to which the filter should apply. + * + * @return filtered stream + * + * @throws ResourceException thrown is there if a problem applying the filter + */ + public InputStream applyFilter(InputStream resource) throws ResourceException; +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/resource/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/resource/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/resource/package.html 17 Aug 2012 15:09:13 -0000 1.1 @@ -0,0 +1,7 @@ + + +Utility classes that represent readable, stream based, resources such as local filesystem and classpath resources as +well as remote resources such as documents retrieved via HTTP(S). Also contains support for monitoring such resources +for changes. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/storage/AbstractExpiringObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/storage/AbstractExpiringObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/storage/AbstractExpiringObject.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.storage; + +import java.io.Serializable; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; + +/** Base implementation for {@link ExpiringObject}. */ +public abstract class AbstractExpiringObject implements ExpiringObject, Serializable { + + /** Moment of expiration in UTC. */ + private long expiration; + + /** + * Constructor. + * + * @param expirationTime time this object should expire + */ + public AbstractExpiringObject(DateTime expirationTime) { + expiration = expirationTime.toDateTime(ISOChronology.getInstanceUTC()).getMillis(); + } + + /** {@inheritDoc} */ + public DateTime getExpirationTime() { + return new DateTime(expiration, ISOChronology.getInstanceUTC()); + } + + /** {@inheritDoc} */ + public boolean isExpired() { + return getExpirationTime().isBeforeNow(); + } + + /** {@inheritDoc} */ + public void onExpire() { + // no-op, implementations should override if they need to do something + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/storage/ExpiringObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/storage/ExpiringObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/storage/ExpiringObject.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.storage; + +import org.joda.time.DateTime; + +/** + * A simple interface for objects that may expire at a given time. + */ +public interface ExpiringObject { + + /** + * Gets the time the object expires. + * + * @return time the object expires + */ + public DateTime getExpirationTime(); + + /** + * Gets whether this object has expired. + * + * @return true if the expiration time has passed, false if not + */ + public boolean isExpired(); + + /** + * A callback method invoked when this object is expiring. Note, this method may not be invoked at the exact instant + * of expiration but may, instead, be invoked the next time the object is read and noticed to have expired. + */ + public void onExpire(); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/storage/ExpiringObjectStorageServiceSweeper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/storage/ExpiringObjectStorageServiceSweeper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/storage/ExpiringObjectStorageServiceSweeper.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,116 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.storage; + +import java.util.Iterator; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A simple task that periodically sweeps over a {@link StorageService} and removes expired entries. + */ +public class ExpiringObjectStorageServiceSweeper extends TimerTask { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(ExpiringObjectStorageServiceSweeper.class); + + /** Interval between sweeps. */ + private long sweepInterval; + + /** Storage service whose entries will be periodically checked. */ + private StorageService store; + + /** Storage partitions to sweep. */ + private Set partitions; + + /** + * Constructor. Registers this task with the given timer. + * + * @param taskTimer timer that will sweep the given storage service + * @param interval interval, in milliseconds, that the storage service will be swept + * @param sweptStore storage service that will be swept + */ + public ExpiringObjectStorageServiceSweeper(Timer taskTimer, long interval, StorageService sweptStore) { + store = sweptStore; + sweepInterval = interval; + taskTimer.schedule(this, interval, interval); + partitions = null; + } + + /** + * Constructor. Registers this task with the given timer. + * + * @param taskTimer timer that will sweep the given storage service + * @param interval interval, in milliseconds, that the storage service will be swept + * @param sweptStore storage service that will be swept + * @param sweptPartitions the partitions to sweep, if null or empty all partitions are swept + */ + public ExpiringObjectStorageServiceSweeper(Timer taskTimer, long interval, StorageService sweptStore, + Set sweptPartitions) { + store = sweptStore; + if (sweptPartitions != null || sweptPartitions.isEmpty()) { + partitions = sweptPartitions; + } else { + partitions = null; + } + sweepInterval = interval; + taskTimer.schedule(this, interval, interval); + } + + /** {@inheritDoc} */ + public void run() { + try { + Iterator sweepPartitions; + if (partitions != null && !partitions.isEmpty()) { + sweepPartitions = partitions.iterator(); + } else { + sweepPartitions = store.getPartitions(); + } + + String currentParition; + Iterator partitionKeys; + Object partitionKey; + Object partitionValue; + while (sweepPartitions.hasNext()) { + currentParition = sweepPartitions.next(); + log.trace("Sweeping storage service partition {}", currentParition); + partitionKeys = store.getKeys(currentParition); + if (partitionKeys == null) { + continue; + } + + while (partitionKeys.hasNext()) { + partitionKey = partitionKeys.next(); + partitionValue = store.get(currentParition, partitionKey); + if (partitionValue instanceof ExpiringObject) { + if (((ExpiringObject) partitionValue).isExpired()) { + log.trace("Removing expired object from storage service partition {}", currentParition); + partitionKeys.remove(); + } + } + } + } + } catch (Throwable t) { + log.error("Caught unexpected error, sweeper will execute again in " + sweepInterval + "ms", t); + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/storage/MapBasedStorageService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/storage/MapBasedStorageService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/storage/MapBasedStorageService.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,128 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.storage; + +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * A simple {@link Map} based {@link StorageService} implementation. + * + * @param object type of the keys + * @param object type of the values + */ +public class MapBasedStorageService implements StorageService { + + /** Backing map. */ + private Map> store; + + /** Constructor. */ + public MapBasedStorageService() { + store = new ConcurrentHashMap>(); + } + + /** + * Constructor. + * + * @param serviceStore the map to use as storage + */ + protected MapBasedStorageService(Map> serviceStore) { + store = serviceStore; + } + + /** {@inheritDoc} */ + public Iterator getPartitions() { + Set keys = store.keySet(); + if (keys != null) { + return keys.iterator(); + } + + return null; + } + + /** {@inheritDoc} */ + public Iterator getKeys(String partition) { + if (store.containsKey(partition)) { + Set keys = store.get(partition).keySet(); + if (keys != null) { + return keys.iterator(); + } + } + + return null; + } + + /** {@inheritDoc} */ + public boolean contains(String partition, KeyType key) { + if (key == null) { + return false; + } + + if (store.containsKey(partition)) { + return store.get(partition).containsKey(key); + } + + return false; + } + + /** {@inheritDoc} */ + public ValueType get(String partition, KeyType key) { + if (key == null) { + return null; + } + + if (store.containsKey(partition)) { + return store.get(partition).get(key); + } + + return null; + } + + /** {@inheritDoc} */ + public ValueType put(String partition, KeyType key, ValueType value) { + if (key == null) { + return null; + } + + Map partitionMap; + synchronized (store) { + partitionMap = store.get(partition); + if (partitionMap == null) { + partitionMap = new ConcurrentHashMap(); + } + store.put(partition, partitionMap); + } + + return partitionMap.put(key, value); + } + + /** {@inheritDoc} */ + public ValueType remove(String partition, KeyType key) { + if (key == null) { + return null; + } + + if (store.containsKey(partition)) { + return store.get(partition).remove(key); + } + + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/storage/ReplayCache.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/storage/ReplayCache.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/storage/ReplayCache.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,135 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.storage; + +import java.util.concurrent.locks.ReentrantLock; + +import org.joda.time.DateTime; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Class that uses an underlying {@link StorageService} to track information associated with messages in order to detect + * message replays. + * + * This class is thread-safe and uses a basic reentrant lock to avoid corruption of the underlying store, as well as to + * prevent race conditions with respect to replay checking. + */ +public class ReplayCache { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(ReplayCache.class); + + /** Backing storage for the replay cache. */ + private StorageService storage; + + /** Storage service partition used by this cache. default: replay */ + private String partition; + + /** Time, in milliseconds, that message state is valid. */ + private long entryDuration; + + /** Replay cache lock. */ + private ReentrantLock cacheLock; + + /** + * Constructor. + * + * @param storageService the StorageService which serves as the backing store for the cache + * @param duration default length of time that message state is valid + */ + public ReplayCache(StorageService storageService, long duration) { + storage = storageService; + entryDuration = duration; + partition = "replay"; + cacheLock = new ReentrantLock(true); + } + + /** + * Constructor. + * + * @param storageService the StorageService which serves as the backing store for the cache + * @param storageParition name of storage service partition to use + * @param duration default length of time that message state is valid + */ + public ReplayCache(StorageService storageService, String storageParition, long duration) { + storage = storageService; + entryDuration = duration; + if (!DatatypeHelper.isEmpty(storageParition)) { + partition = DatatypeHelper.safeTrim(storageParition); + } else { + partition = "replay"; + } + cacheLock = new ReentrantLock(true); + } + + /** + * Checks if the message has been replayed. If the message has not been seen before then it is added to the list of + * seen of messages for the default duration. + * + * @param issuerId unique ID of the message issuer + * @param messageId unique ID of the message + * + * @return true if the given message ID has been seen before + */ + public boolean isReplay(String issuerId, String messageId) { + log.debug("Attempting to acquire lock for replay cache check"); + cacheLock.lock(); + log.debug("Lock acquired"); + + try { + boolean replayed = true; + String entryHash = issuerId + messageId; + + ReplayCacheEntry cacheEntry = storage.get(partition, entryHash); + + if (cacheEntry == null || cacheEntry.isExpired()) { + if (log.isDebugEnabled()) { + if (cacheEntry == null) { + log.debug("Message ID {} was not a replay", messageId); + } else if (cacheEntry.isExpired()) { + log.debug("Message ID {} expired in replay cache at {}", messageId, cacheEntry + .getExpirationTime().toString()); + storage.remove(partition, entryHash); + } + } + replayed = false; + addMessageID(entryHash, new DateTime().plus(entryDuration)); + } else { + log.debug("Replay of message ID {} detected in replay cache, will expire at {}", messageId, cacheEntry + .getExpirationTime().toString()); + } + + return replayed; + } finally { + cacheLock.unlock(); + } + } + + /** + * Accquires a write lock and adds the message state to the underlying storage service. + * + * @param messageId unique ID of the message + * @param expiration time the message state expires + */ + protected void addMessageID(String messageId, DateTime expiration) { + log.debug("Writing message ID {} to replay cache with expiration time {}", messageId, expiration.toString()); + storage.put(partition, messageId, new ReplayCacheEntry(messageId, expiration)); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/storage/ReplayCacheEntry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/storage/ReplayCacheEntry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/storage/ReplayCacheEntry.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.storage; + +import java.io.Serializable; + +import org.joda.time.DateTime; + +/** Replay cache storage service entry. */ +public class ReplayCacheEntry extends AbstractExpiringObject implements Serializable { + + /** Serial version UID. */ + private static final long serialVersionUID = 1066201734851002196L; + + /** ID of the message that may not be replayed. */ + private String messageId; + + /** + * Constructor. + * + * @param id ID of the message that may not be replayed + * @param expiration time when this entry expires + */ + public ReplayCacheEntry(String id, DateTime expiration) { + super(expiration); + messageId = id; + } + + /** + * Gets the ID of the message that may not be replayed. + * + * @return ID of the message that may not be replayed + */ + public String getMessageId() { + return messageId; + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/storage/StorageService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/storage/StorageService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/storage/StorageService.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,94 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.util.storage; + +import java.util.Iterator; + +/** + * Generic data storage facility for use by services that require some degree of persistence. + * + * The storage service is partitioned. This is to allow different objects to use the service, each with its own + * partition, without the worry of conflicting keys. + * + * @param object type of the keys + * @param object type of the values + */ +public interface StorageService { + + /** + * Checks if a given key exists. + * + * @param partition partition on which to operate + * @param key the key to check + * + * @return true of the given key exists, false if not + */ + public boolean contains(String partition, KeyType key); + + /** + * Gets the partitions within the service. Removal of a partition identifier from the iterator removes the partition + * from the storage service. + * + * @return partitions within the service + */ + public Iterator getPartitions(); + + /** + * Gets the keys for entries in the storage service. Removal of a key from the iterator removes the the key and + * associated value from the store. + * + * Note: this operation may be very expensive + * + * @param partition partition on which to operate + * + * @return list of keys currently within the store + */ + public Iterator getKeys(String partition); + + /** + * Gets the value stored under a particular key. + * + * @param partition partition on which to operate + * @param key the key + * + * @return the value for that key, or null if there is no value for the given key + */ + public ValueType get(String partition, KeyType key); + + /** + * Adds a value, indexed by a key, in to storage. Note that implementations of this service may determine, on its + * own, when to evict items from storage, the expiration time given here is meant only as a system provided hint. + * + * @param partition partition on which to operate + * @param key the key + * @param value the value + * + * @return the value that was registered under that key previously, if there was a previous value + */ + public ValueType put(String partition, KeyType key, ValueType value); + + /** + * Removes an item from storage. + * + * @param partition partition on which to operate + * @param key the key to the value to remove + * + * @return the value that was removed + */ + public ValueType remove(String partition, KeyType key); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/util/storage/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/util/storage/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/util/storage/package.html 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,6 @@ + + +Interfaces and classes for storing state data of the type used in replay caches, conversation identifiers, etc. Through +these interfaces such data may be stored in memory, to a database, or replicated across cluster nodes. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/Version.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/Version.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/Version.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,105 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws; + +/** Class for printing the version of this library. */ +public final class Version { + + /** Name of the library. */ + private static final String NAME; + + /** Library version. */ + private static final String VERSION; + + /** Library major version number. */ + private static final int MAJOR_VERSION; + + /** Library minor version number. */ + private static final int MINOR_VERSION; + + /** Library micro version number. */ + private static final int MICRO_VERSION; + + /** Constructor. */ + private Version() { + } + + /** + * Main entry point to program. + * + * @param args command line arguments + */ + public static void main(String[] args) { + System.out.println(NAME + " version " + VERSION); + } + + /** + * Gets the name of the library. + * + * @return name of the library + */ + public static String getName() { + return NAME; + } + + /** + * Gets the version of the library. + * + * @return version of the library + */ + public static String getVersion() { + return VERSION; + } + + /** + * Gets the major version number of the library. + * + * @return major version number of the library + */ + public static int getMajorVersion() { + return MAJOR_VERSION; + } + + /** + * Gets the minor version number of the library. + * + * @return minor version number of the library + */ + public static int getMinorVersion() { + return MINOR_VERSION; + } + + /** + * Gets the micro version number of the library. + * + * @return micro version number of the library + */ + public static int getMicroVersion() { + return MICRO_VERSION; + } + + static { + Package pkg = Version.class.getPackage(); + NAME = pkg.getImplementationTitle().intern(); + VERSION = pkg.getImplementationVersion().intern(); + String[] versionParts = VERSION.split("\\."); + MAJOR_VERSION = Integer.parseInt(versionParts[0]); + MINOR_VERSION = Integer.parseInt(versionParts[1]); + MICRO_VERSION = Integer.parseInt(versionParts[2]); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/WSException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/WSException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/WSException.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws; + +/** + * General OpenWS exception class. + */ +public class WSException extends Exception { + + /** + * Serial version UID. + */ + private static final long serialVersionUID = 257983691332151160L; + + /** + * Constructor. + */ + public WSException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public WSException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public WSException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public WSException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/package.html 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,5 @@ + + +Objects dealing directly with SOAP-based web services. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/BaseMessageContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/BaseMessageContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/BaseMessageContext.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,179 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message; + +import org.opensaml.ws.message.handler.HandlerChainResolver; +import org.opensaml.ws.security.SecurityPolicyResolver; +import org.opensaml.ws.transport.InTransport; +import org.opensaml.ws.transport.OutTransport; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Base class for message context implementations. + */ +public class BaseMessageContext implements MessageContext { + + /** Unique id of the communication profile in use. */ + private String communicationProfile; + + /** The inbound message. */ + private XMLObject inboundMessage; + + /** Issuer of the inbound message. */ + private String inboundMessageIssuer; + + /** Inbound message transport. */ + private InTransport inboundTransport; + + /** Outbound message. */ + private XMLObject outboundMessage; + + /** Issuer of the outbound message. */ + private String outboundMessageIssuer; + + /** Outbound message transport. */ + private OutTransport outboundTransport; + + /** Resolver used to determine active security policy. */ + private SecurityPolicyResolver securityPolicyResolver; + + /** Pre-SecurityPolicy inbound handler chain. */ + private HandlerChainResolver preSecurityInboundHandlerChainResolver; + + /** Post-SecurityPolicy inbound handler chain. */ + private HandlerChainResolver postSecurityInboundHandlerChainResolver; + + /** Inbound handler chain. */ + private HandlerChainResolver outboundHandlerChainResolver; + + /** {@inheritDoc} */ + public String getCommunicationProfileId() { + return communicationProfile; + } + + /** {@inheritDoc} */ + public XMLObject getInboundMessage() { + return inboundMessage; + } + + /** {@inheritDoc} */ + public String getInboundMessageIssuer() { + return inboundMessageIssuer; + } + + /** {@inheritDoc} */ + public InTransport getInboundMessageTransport() { + return inboundTransport; + } + + /** {@inheritDoc} */ + public XMLObject getOutboundMessage() { + return outboundMessage; + } + + /** {@inheritDoc} */ + public String getOutboundMessageIssuer() { + return outboundMessageIssuer; + } + + /** {@inheritDoc} */ + public OutTransport getOutboundMessageTransport() { + return outboundTransport; + } + + /** {@inheritDoc} */ + public SecurityPolicyResolver getSecurityPolicyResolver() { + return securityPolicyResolver; + } + + /** {@inheritDoc} */ + public void setCommunicationProfileId(String id) { + communicationProfile = DatatypeHelper.safeTrimOrNullString(id); + } + + /** {@inheritDoc} */ + public void setInboundMessage(XMLObject message) { + inboundMessage = message; + } + + /** {@inheritDoc} */ + public void setInboundMessageIssuer(String issuer) { + inboundMessageIssuer = issuer; + } + + /** {@inheritDoc} */ + public void setInboundMessageTransport(InTransport transport) { + inboundTransport = transport; + } + + /** {@inheritDoc} */ + public void setOutboundMessage(XMLObject message) { + outboundMessage = message; + } + + /** {@inheritDoc} */ + public void setOutboundMessageIssuer(String issuer) { + outboundMessageIssuer = issuer; + } + + /** {@inheritDoc} */ + public void setOutboundMessageTransport(OutTransport transport) { + outboundTransport = transport; + } + + /** {@inheritDoc} */ + public void setSecurityPolicyResolver(SecurityPolicyResolver resolver) { + securityPolicyResolver = resolver; + } + + /** {@inheritDoc} */ + public boolean isIssuerAuthenticated() { + return getInboundMessageTransport().isAuthenticated(); + } + + /** {@inheritDoc} */ + public HandlerChainResolver getPreSecurityInboundHandlerChainResolver() { + return preSecurityInboundHandlerChainResolver; + } + + /** {@inheritDoc} */ + public HandlerChainResolver getPostSecurityInboundHandlerChainResolver() { + return postSecurityInboundHandlerChainResolver; + } + + /** {@inheritDoc} */ + public HandlerChainResolver getOutboundHandlerChainResolver() { + return outboundHandlerChainResolver; + } + + /** {@inheritDoc} */ + public void setPreSecurityInboundHandlerChainResolver(HandlerChainResolver newHandlerChainResolver) { + preSecurityInboundHandlerChainResolver = newHandlerChainResolver; + } + + /** {@inheritDoc} */ + public void setPostSecurityInboundHandlerChainResolver(HandlerChainResolver newHandlerChainResolver) { + postSecurityInboundHandlerChainResolver = newHandlerChainResolver; + } + + /** {@inheritDoc} */ + public void setOutboundHandlerChainResolver(HandlerChainResolver newHandlerChainResolver) { + outboundHandlerChainResolver = newHandlerChainResolver; + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/MessageContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/MessageContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/MessageContext.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,196 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message; + +import org.opensaml.ws.message.handler.HandlerChainResolver; +import org.opensaml.ws.security.SecurityPolicyResolver; +import org.opensaml.ws.transport.InTransport; +import org.opensaml.ws.transport.OutTransport; +import org.opensaml.xml.XMLObject; + +/** + * A message context represents the entire context for a given message through the receive, process, and/or response + * phases. It is a basic unit of work within the library. + * + * Message contexts are NOT thread safe. + */ +public interface MessageContext { + + /** + * Gets the unique id of the communication profile in use. + * + * @return unique id of the communication profile in use + */ + public String getCommunicationProfileId(); + + /** + * Gets the inbound message. + * + * @return the inbound message + */ + public XMLObject getInboundMessage(); + + /** + * Gets the issuer of the inbound message. + * + * @return issuer of the inbound message + */ + public String getInboundMessageIssuer(); + + /** + * Gets the transport used to receive the message. + * + * @return transport used to receive the message + */ + public InTransport getInboundMessageTransport(); + + /** + * Gets the outbound message. + * + * @return the outbound message + */ + public XMLObject getOutboundMessage(); + + /** + * Gets the issuer of the outbound message. + * + * @return issuer of the outbound message + */ + public String getOutboundMessageIssuer(); + + /** + * Gets the transport used to respond to the message. + * + * @return transport used to respond to the message + */ + public OutTransport getOutboundMessageTransport(); + + /** + * Gets the resolver used to determine active SecurityPolicy. + * + * @return resolver used to determine active SecurityPolicy + */ + public SecurityPolicyResolver getSecurityPolicyResolver(); + + /** + * Gets whether the issuer of the inbound message represented by this context has been authenticated. + * What it means for the message issuer to be authenticate will vary by use and + * employed authentication mechanisms. + * + * @return whether the issuer of the inbound message represented by this context has been authenticated + */ + public boolean isIssuerAuthenticated(); + + /** + * Sets the unique id of the communication profile in use. + * + * @param id unique id of the communication profile in use + */ + public void setCommunicationProfileId(String id); + + /** + * Sets the inbound message. + * + * @param message the inbound message + */ + public void setInboundMessage(XMLObject message); + + /** + * Sets the issuer of the inbound message. + * + * @param issuer issuer of the inbound message + */ + public void setInboundMessageIssuer(String issuer); + + /** + * Sets the transport used to used to receive the message. + * + * @param transport the transport used to receive the message + */ + public void setInboundMessageTransport(InTransport transport); + + /** + * Sets the outbound message. + * + * @param message the outbound message + */ + public void setOutboundMessage(XMLObject message); + + /** + * Sets the issuer of the outbound message. + * + * @param issuer issuer of the outbound message + */ + public void setOutboundMessageIssuer(String issuer); + + /** + * Sets the transport used to respond to the message. + * + * @param transport the transport used to respond to the message + */ + public void setOutboundMessageTransport(OutTransport transport); + + /** + * Sets the resolver used to determine active SecurityPolicy. + * + * @param resolver resolver used to determine active SecurityPolicy + */ + public void setSecurityPolicyResolver(SecurityPolicyResolver resolver); + + /** + * Get the pre-SecurityPolicy inbound handler chain resolver. + * + * @return the pre-security inbound handler chain resolver. + */ + public HandlerChainResolver getPreSecurityInboundHandlerChainResolver(); + + /** + * Set the pre-SecurityPolicy inbound handler chain resolver. + * + * @param newHandlerChainResolver the new pre-SecurityPolicy inbound handler chain. + */ + public void setPreSecurityInboundHandlerChainResolver(HandlerChainResolver newHandlerChainResolver); + + /** + * Get the post-SecurityPolicy inbound handler chain resolver. + * + * @return the pre-SecurityPolicy inbound handler chain resolver. + */ + public HandlerChainResolver getPostSecurityInboundHandlerChainResolver(); + + /** + * Set the post-SecurityPolicy inbound handler chain resolver. + * + * @param newHandlerChainResolver the new post-SecurityPolicy inbound handler chain resolver. + */ + public void setPostSecurityInboundHandlerChainResolver(HandlerChainResolver newHandlerChainResolver); + + /** + * Get the outbound handler chain resolver. + * + * @return the outbound handler chain resolver. + */ + public HandlerChainResolver getOutboundHandlerChainResolver(); + + /** + * Set the outbound handler chain resolver. + * + * @param newHandlerChainResolver the new outbound handler chain resolver. + */ + public void setOutboundHandlerChainResolver(HandlerChainResolver newHandlerChainResolver); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/MessageContextEvaluatingFunctor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/MessageContextEvaluatingFunctor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/MessageContextEvaluatingFunctor.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message; + + +/** + * An interface for components which evaluate a message context as the basis for extracting, calculating, + * or otherwise producing a specific data value. + * + *

+ * Implementations should not have side effects and should not modify any data in the + * underlying message context. For a component that is intended to allow message context + * modification, see {@link MessageContextMutatingFunctor}. + *

+ * + * @param the type of product of the component + */ +public interface MessageContextEvaluatingFunctor { + + /** + * Using the specified MessageContext as the evaluation context, + * produce a data value product of the appropriate type. + * + * @param msgContext the message context to evaluate + * @return value product based on the message context, or null + * + * @throws MessageException if there is a fatal error evaluating the context + */ + public T evaluate(MessageContext msgContext) throws MessageException; + +} Index: 3rdParty_sources/openws/org/opensaml/ws/message/MessageContextMutatingFunctor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/MessageContextMutatingFunctor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/MessageContextMutatingFunctor.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message; + + +/** + * An interface for components which mutate a message context, or data contained therein, + * based on an input value of a particular type. + * + * @param the type of input to the operation to be performed on the message context + */ +public interface MessageContextMutatingFunctor { + + /** + * Mutate the specified message context based on the supplied input value. + * + * @param msgContext the current message context + * @param input the input to the mutation operation + * + * @throws MessageException if there is a fatal error processing the context + */ + public void mutate(MessageContext msgContext, T input) throws MessageException; + +} Index: 3rdParty_sources/openws/org/opensaml/ws/message/MessageException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/MessageException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/MessageException.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message; + +import org.opensaml.ws.WSException; + +/** + * Base class for message related exceptions. + */ +public class MessageException extends WSException { + + /** Serial version UID. */ + private static final long serialVersionUID = 4437402731161754263L; + + /** + * Constructor. + */ + public MessageException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public MessageException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public MessageException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public MessageException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/package.html 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,5 @@ + + +Objects related to messages received and sent by web services. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/decoder/BaseMessageDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/decoder/BaseMessageDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/decoder/BaseMessageDecoder.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,215 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.decoder; + +import java.io.InputStream; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.security.SecurityPolicy; +import org.opensaml.ws.security.SecurityPolicyResolver; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.Marshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.io.Unmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.parse.BasicParserPool; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.parse.XMLParserException; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Base class for message decoders. + */ +public abstract class BaseMessageDecoder implements MessageDecoder { + + /** Used to log protocol messages. */ + private Logger protocolMessageLog = LoggerFactory.getLogger("PROTOCOL_MESSAGE"); + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(BaseMessageDecoder.class); + + /** Parser pool used to deserialize the message. */ + private ParserPool parserPool; + + /** Constructor. */ + public BaseMessageDecoder() { + parserPool = new BasicParserPool(); + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public BaseMessageDecoder(ParserPool pool) { + if (pool == null) { + throw new IllegalArgumentException("Parser pool may not be null"); + } + + parserPool = pool; + } + + /** {@inheritDoc} */ + public void decode(MessageContext messageContext) throws MessageDecodingException, SecurityException { + log.debug("Beginning to decode message from inbound transport of type: {}", messageContext + .getInboundMessageTransport().getClass().getName()); + + doDecode(messageContext); + + logDecodedMessage(messageContext); + + processSecurityPolicy(messageContext); + + log.debug("Successfully decoded message."); + } + + /** + * Log the decoded message to the protocol message logger. + * + * @param messageContext the message context to process + */ + protected void logDecodedMessage(MessageContext messageContext) { + if(protocolMessageLog.isDebugEnabled() && messageContext.getInboundMessage() != null){ + if (messageContext.getInboundMessage().getDOM() == null) { + XMLObject message = messageContext.getInboundMessage(); + Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(message); + if (marshaller != null) { + try { + marshaller.marshall(message); + } catch (MarshallingException e) { + log.error("Unable to marshall message for logging purposes: " + e.getMessage()); + } + } + else { + log.error("Unable to marshall message for logging purposes, no marshaller registered for message object: " + + message.getElementQName()); + } + if (message.getDOM() == null) { + return; + } + } + protocolMessageLog.debug("\n" + XMLHelper.prettyPrintXML(messageContext.getInboundMessage().getDOM())); + } + } + + /** + * Process any {@link SecurityPolicy}s which can be resolved for the message context. + * + * @param messageContext the message context to process + * @throws SecurityException thrown if the decoded message does not meet the required security constraints + */ + protected void processSecurityPolicy(MessageContext messageContext) throws SecurityException { + SecurityPolicyResolver policyResolver = messageContext.getSecurityPolicyResolver(); + if (policyResolver != null) { + Iterable securityPolicies = policyResolver.resolve(messageContext); + if (securityPolicies != null) { + for (SecurityPolicy policy : securityPolicies) { + if (policy != null) { + log.debug("Evaluating security policy of type '{}' for decoded message", policy.getClass() + .getName()); + policy.evaluate(messageContext); + } + } + } else { + log.debug("No security policy resolved for this message context, no security policy evaluation attempted"); + } + } else { + log.debug("No security policy resolver attached to this message context, no security policy evaluation attempted"); + } + } + + /** + * Decodes a message, updating the message context. Security policy evaluation is handled outside this method. + * + * @param messageContext current message context + * + * @throws MessageDecodingException thrown if there is a problem decoding the message + */ + protected abstract void doDecode(MessageContext messageContext) throws MessageDecodingException; + + /** + * Gets the parser pool used to deserialize incomming messages. + * + * @return parser pool used to deserialize incomming messages + */ + protected ParserPool getParserPool() { + return parserPool; + } + + /** + * Sets the parser pool used to deserialize incomming messages. + * + * @param pool parser pool used to deserialize incomming messages + */ + protected void setParserPool(ParserPool pool) { + if (pool == null) { + throw new IllegalArgumentException("Parser pool may not be null"); + } + parserPool = pool; + } + + /** + * Helper method that deserializes and unmarshalls the message from the given stream. + * + * @param messageStream input stream containing the message + * + * @return the inbound message + * + * @throws MessageDecodingException thrown if there is a problem deserializing and unmarshalling the message + */ + protected XMLObject unmarshallMessage(InputStream messageStream) throws MessageDecodingException { + log.debug("Parsing message stream into DOM document"); + + try { + Document messageDoc = parserPool.parse(messageStream); + Element messageElem = messageDoc.getDocumentElement(); + + if (log.isTraceEnabled()) { + log.trace("Resultant DOM message was:\n{}", XMLHelper.nodeToString(messageElem)); + } + + log.debug("Unmarshalling message DOM"); + Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(messageElem); + if (unmarshaller == null) { + log.error("Unable to unmarshall message, no unmarshaller registered for message element " + + XMLHelper.getNodeQName(messageElem)); + throw new MessageDecodingException( + "Unable to unmarshall message, no unmarshaller registered for message element " + + XMLHelper.getNodeQName(messageElem)); + } + + XMLObject message = unmarshaller.unmarshall(messageElem); + + log.debug("Message succesfully unmarshalled"); + return message; + } catch (XMLParserException e) { + log.error("Encountered error parsing message into its DOM representation", e); + throw new MessageDecodingException("Encountered error parsing message into its DOM representation", e); + } catch (UnmarshallingException e) { + log.error("Encountered error unmarshalling message from its DOM representation", e); + throw new MessageDecodingException("Encountered error unmarshalling message from its DOM representation", e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/decoder/MessageDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/decoder/MessageDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/decoder/MessageDecoder.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.decoder; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.xml.security.SecurityException; + +/** + * Decodes a message, from an inbound transport, in a binding specific manner. As the decode proceeds information is + * stored in the {@link MessageContext}. The decoding process deserializes the message from the inbound transport into + * its DOM representation, unmarshall the DOM into the appropriate XMLObject, and then evaluates the security policy + * against the inbound transport and decoded message. + * + * Message decoders MUST must be thread safe and stateless. + */ +public interface MessageDecoder { + + /** + * Decodes a message in a binding specific manner. + * + * @param messageContext current message context + * + * @throws MessageDecodingException thrown if the message can not be decoded + * @throws SecurityException thrown if the decoded message does not meet the required security constraints + */ + public void decode(MessageContext messageContext) throws MessageDecodingException, SecurityException; + +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/decoder/MessageDecodingException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/decoder/MessageDecodingException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/decoder/MessageDecodingException.java 17 Aug 2012 15:09:10 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.decoder; + +import org.opensaml.ws.message.MessageException; + +/** + * Exception thrown when a problem occurs decoding a message from an input transport. + */ +public class MessageDecodingException extends MessageException { + + /** Serial version UID. */ + private static final long serialVersionUID = 8151752605618631906L; + + /** + * Constructor. + */ + public MessageDecodingException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public MessageDecodingException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public MessageDecodingException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public MessageDecodingException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/decoder/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/decoder/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/decoder/package.html 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,5 @@ + + +Messages decoders are responsible for extracting an incomming web serivce message from the inbound transport. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/encoder/BaseMessageEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/encoder/BaseMessageEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/encoder/BaseMessageEncoder.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,118 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.encoder; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.Marshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Element; + +/** + * Base class for message decoders. + */ +public abstract class BaseMessageEncoder implements MessageEncoder { + + /** Used to log protocol messages. */ + private Logger protocolMessageLog = LoggerFactory.getLogger("PROTOCOL_MESSAGE"); + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(BaseMessageEncoder.class); + + /** Constructor. */ + public BaseMessageEncoder() { + + } + + /** {@inheritDoc} */ + public void encode(MessageContext messageContext) throws MessageEncodingException { + log.debug("Beginning encode message to outbound transport of type: {}", messageContext + .getOutboundMessageTransport().getClass().getName()); + + doEncode(messageContext); + + logEncodedMessage(messageContext); + + log.debug("Successfully encoded message."); + } + + /** + * Log the encoded message to the protocol message logger. + * + * @param messageContext the message context to process + */ + protected void logEncodedMessage(MessageContext messageContext) { + if(protocolMessageLog.isDebugEnabled() && messageContext.getOutboundMessage() != null){ + if (messageContext.getOutboundMessage().getDOM() == null) { + try { + marshallMessage(messageContext.getOutboundMessage()); + } catch (MessageEncodingException e) { + log.error("Unable to marshall message for logging purposes: " + e.getMessage()); + return; + } + } + protocolMessageLog.debug("\n" + XMLHelper.prettyPrintXML(messageContext.getOutboundMessage().getDOM())); + } + } + + /** + * Encodes the outbound message onto the outbound transport. + * + * @param messageContext current message context + * + * @throws MessageEncodingException thrown if there is a problem encoding the message + */ + protected abstract void doEncode(MessageContext messageContext) throws MessageEncodingException; + + /** + * Helper method that marshalls the given message. + * + * @param message message the marshall and serialize + * + * @return marshalled message + * + * @throws MessageEncodingException thrown if the give message can not be marshalled into its DOM representation + */ + protected Element marshallMessage(XMLObject message) throws MessageEncodingException { + log.debug("Marshalling message"); + + try { + Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(message); + if (marshaller == null) { + log.error("Unable to marshall message, no marshaller registered for message object: " + + message.getElementQName()); + throw new MessageEncodingException( + "Unable to marshall message, no marshaller registered for message object: " + + message.getElementQName()); + } + Element messageElem = marshaller.marshall(message); + if (log.isTraceEnabled()) { + log.trace("Marshalled message into DOM:\n{}", XMLHelper.nodeToString(messageElem)); + } + return messageElem; + } catch (MarshallingException e) { + log.error("Encountered error marshalling message to its DOM representation", e); + throw new MessageEncodingException("Encountered error marshalling message into its DOM representation", e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/encoder/MessageEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/encoder/MessageEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/encoder/MessageEncoder.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.encoder; + +import org.opensaml.ws.message.MessageContext; + +/** + * Encodes a message onto the outbound transport. + * + * Message encoders MUST must be thread safe and stateless. + */ +public interface MessageEncoder { + + /** + * Encodes the message in the binding specific manner. + * + * @param messageContext current message context + * + * @throws MessageEncodingException thrown if the problem can not be encoded + */ + public void encode(MessageContext messageContext) throws MessageEncodingException; + + /** + * Indicates whether this encoder, given the current message context, provides end-to-end message confidentiality. + * + * @param messageContext the current message context + * + * @return true if the encoder provides end-to-end message confidentiality, false if not + * + * @throws MessageEncodingException thrown if the encoder encounter an error while attempt to evaluate its ability + * to provide message confidentiality. + */ + public boolean providesMessageConfidentiality(MessageContext messageContext) throws MessageEncodingException; + + /** + * Indicates whether this encoder, given the current message context, provides end-to-end message integrity. + * + * @param messageContext the current message context + * + * @return true if the encoder provides end-to-end message integrity, false if not + * + * @throws MessageEncodingException thrown if the encoder encounter an error while attempt to evaluate its ability + * to provide message integrity. + */ + public boolean providesMessageIntegrity(MessageContext messageContext) throws MessageEncodingException; +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/encoder/MessageEncodingException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/encoder/MessageEncodingException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/encoder/MessageEncodingException.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.encoder; + +import org.opensaml.ws.message.MessageException; + +/** + * Exception thrown when a problem occurs encoding a message from to an output transport. + */ +public class MessageEncodingException extends MessageException { + + /** Serial version UID. */ + private static final long serialVersionUID = 5394876087412894874L; + + /** + * Constructor. + */ + public MessageEncodingException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public MessageEncodingException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public MessageEncodingException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public MessageEncodingException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/encoder/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/encoder/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/encoder/package.html 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,5 @@ + + +Messages encoders are responsible for encoding an outgoing web serivce message onto the outbound transport. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/handler/BaseHandlerChainAwareMessageDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/handler/BaseHandlerChainAwareMessageDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/handler/BaseHandlerChainAwareMessageDecoder.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,136 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.handler; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.BaseMessageDecoder; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.security.SecurityException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base class for message decoders which are capable of processing the message context's inbound {@link HandlerChain}. + */ +public abstract class BaseHandlerChainAwareMessageDecoder extends BaseMessageDecoder implements HandlerChainAware { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(BaseHandlerChainAwareMessageDecoder.class); + + /** + * Constructor. + * + */ + public BaseHandlerChainAwareMessageDecoder() { + super(); + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public BaseHandlerChainAwareMessageDecoder(ParserPool pool) { + super(pool); + } + + /** {@inheritDoc} */ + public void decode(MessageContext messageContext) throws MessageDecodingException, SecurityException { + log.debug("Beginning to decode message from inbound transport of type: {}", messageContext + .getInboundMessageTransport().getClass().getName()); + + doDecode(messageContext); + + logDecodedMessage(messageContext); + + processPreSecurityInboundHandlerChain(messageContext); + log.debug("Successfully processed pre-SecurityPolicy inbound handler chain."); + + processSecurityPolicy(messageContext); + + processPostSecurityInboundHandlerChain(messageContext); + log.debug("Successfully processed post-SecurityPolicy inbound handler chain."); + + log.debug("Successfully decoded message."); + } + + /** + * Process the pre-SecurityPolicy inbound {@link HandlerChain} for the message context, if any. + * + * @param messageContext the message context to process + * @throws MessageDecodingException thrown if a handler indicates a problem handling the message + */ + protected void processPreSecurityInboundHandlerChain(MessageContext messageContext) + throws MessageDecodingException { + HandlerChainResolver inboundHandlerChainResolver = messageContext.getPreSecurityInboundHandlerChainResolver(); + if (inboundHandlerChainResolver != null) { + log.debug("Invoking pre-SecurityPolicy inbound handler chain on message context"); + try { + for (HandlerChain inboundHandlerChain : inboundHandlerChainResolver.resolve(messageContext)) { + if (inboundHandlerChain != null) { + invokeHandlerChain(inboundHandlerChain, messageContext); + } + } + } catch (HandlerException e) { + log.error("Encountered pre-SecurityPolicy HandlerException when decoding message: {}", e.getMessage()); + throw new MessageDecodingException("Pre-SecurityPolicy Handler exception while decoding message", e); + } + } + } + + /** + * Process the post-SecurityPolicy inbound {@link HandlerChain} for the message context, if any. + * + * @param messageContext the message context to process + * @throws MessageDecodingException thrown if a handler indicates a problem handling the message + */ + protected void processPostSecurityInboundHandlerChain(MessageContext messageContext) + throws MessageDecodingException { + HandlerChainResolver inboundHandlerChainResolver = messageContext.getPostSecurityInboundHandlerChainResolver(); + if (inboundHandlerChainResolver != null) { + log.debug("Invoking post-SecurityPolicy inbound handler chain on message context"); + try { + for (HandlerChain inboundHandlerChain : inboundHandlerChainResolver.resolve(messageContext)) { + if (inboundHandlerChain != null) { + invokeHandlerChain(inboundHandlerChain, messageContext); + } + } + } catch (HandlerException e) { + log.error("Encountered post-SecurityPolicy HandlerException when decoding message: {}", e.getMessage()); + throw new MessageDecodingException("Handler exception while decoding message", e); + } + } + } + + /** + * Invoke a handler chain on the specified message context. + * + * @param handlerChain the handle chain to invoke + * @param messageContext the message context to process + * + * @throws HandlerException if handler chain encountered a problem handling the message context + */ + protected void invokeHandlerChain(HandlerChain handlerChain, MessageContext messageContext) + throws HandlerException { + if (handlerChain != null && messageContext != null) { + handlerChain.invoke(messageContext); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/message/handler/BaseHandlerChainAwareMessageEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/handler/BaseHandlerChainAwareMessageEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/handler/BaseHandlerChainAwareMessageEncoder.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,109 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.handler; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.encoder.BaseMessageEncoder; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base class for message encoders which are capable of processing the message context's outbound {@link HandlerChain}. + */ +public abstract class BaseHandlerChainAwareMessageEncoder extends BaseMessageEncoder implements HandlerChainAware { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(BaseHandlerChainAwareMessageEncoder.class); + + /** {@inheritDoc} */ + protected void doEncode(MessageContext messageContext) throws MessageEncodingException { + prepareMessageContext(messageContext); + + processOutboundHandlerChain(messageContext); + + encodeToTransport(messageContext); + } + + /** + * Perform final binding-specific processing of message context and prepare it for encoding + * to the transport. + * + *

+ * This should include constructing and populating all binding-specific structure and data that needs to be + * reflected by the message context's properties. + *

+ * + *

+ * This method is called prior to {@link #processOutboundHandlerChain(MessageContext)}. + *

+ * + * @param messageContext the message context to process + * @throws MessageEncodingException thrown if there is a problem preparing the message context + * for encoding + */ + protected abstract void prepareMessageContext(MessageContext messageContext) throws MessageEncodingException; + + /** + * Encode the message context to the transport. + * + * @param messageContext the message context to process + * @throws MessageEncodingException thrown if there is a problem encoding the message context + * to the transport + */ + protected abstract void encodeToTransport(MessageContext messageContext) throws MessageEncodingException; + + /** + * Process the outbound {@link HandlerChain} for the message context, if any. + * + * @param messageContext the message context to process + * @throws MessageEncodingException thrown if a handler indicates a problem handling the message + */ + protected void processOutboundHandlerChain(MessageContext messageContext) throws MessageEncodingException { + HandlerChainResolver outboundHandlerChainResolver = messageContext.getOutboundHandlerChainResolver(); + if (outboundHandlerChainResolver != null) { + log.debug("Invoking outbound handler chain on message context"); + try { + for (HandlerChain outboundHandlerChain : outboundHandlerChainResolver.resolve(messageContext)) { + if (outboundHandlerChain != null) { + invokeHandlerChain(outboundHandlerChain, messageContext); + } + } + } catch (HandlerException e) { + log.error("Encountered HandlerException when encoding message: {}", e.getMessage()); + throw new MessageEncodingException("Handler exception while encoding message", e); + } + } + } + + /** + * Invoke a handler chain on the specified message context. + * + * @param handlerChain the handle chain to invoke + * @param messageContext the message context to process + * + * @throws HandlerException if handler chain encountered a problem handling the message context + */ + protected void invokeHandlerChain(HandlerChain handlerChain, MessageContext messageContext) + throws HandlerException { + if (handlerChain != null && messageContext != null) { + handlerChain.invoke(messageContext); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/message/handler/BasicHandlerChain.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/handler/BasicHandlerChain.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/handler/BasicHandlerChain.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.handler; + +import java.util.List; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.xml.util.LazyList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A basic implementation of {@link HandlerChain}. + */ +public class BasicHandlerChain implements HandlerChain { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(BasicHandlerChain.class); + + /** The handler chain. */ + private List handlers; + + /** Constructor. */ + public BasicHandlerChain() { + handlers = new LazyList(); + } + + /** {@inheritDoc} */ + public List getHandlers() { + return handlers; + } + + /** {@inheritDoc} */ + public void invoke(MessageContext msgContext) throws HandlerException { + log.trace("Invoking handler chain"); + for (Handler handler : getHandlers()) { + log.trace("Invoking handler: {}", handler.getClass().getName()); + handler.invoke(msgContext); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/message/handler/BasicPhasedHandlerChain.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/handler/BasicPhasedHandlerChain.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/handler/BasicPhasedHandlerChain.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.handler; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.opensaml.xml.util.LazyList; +import org.opensaml.xml.util.LazyMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A basic implementation of {@link PhasedHandlerChain}. + */ +public class BasicPhasedHandlerChain extends BasicHandlerChain implements PhasedHandlerChain { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(BasicPhasedHandlerChain.class); + + /** The ordered list of phases to invoke. */ + private List phaseOrder; + + /** Map of phases to corresponding Handler chain. */ + private Map phaseChains; + + /** Constructor. */ + public BasicPhasedHandlerChain() { + super(); + phaseOrder = new LazyList(); + phaseChains = new LazyMap(); + } + + /** {@inheritDoc} */ + public List getHandlers() { + ArrayList handlers = new ArrayList(); + for (String phaseName : getPhaseOrder()) { + HandlerChain phase = getPhaseChains().get(phaseName); + if (phase != null) { + List phaseHandlers = phase.getHandlers(); + if (!phaseHandlers.isEmpty()) { + handlers.addAll(phaseHandlers); + } else { + log.info("Specified phase name '{}' exists in PhasedHandlerChain, but contains no handlers", + phaseName); + } + } else { + log.warn("Specified phase name '{}' does not exist in PhasedHandlerChain: {}", + phaseName, getPhaseChains().keySet()); + } + } + return Collections.unmodifiableList(handlers); + } + + /** {@inheritDoc} */ + public Map getPhaseChains() { + return phaseChains; + } + + /** {@inheritDoc} */ + public List getPhaseOrder() { + return phaseOrder; + } + + /** {@inheritDoc} */ + public void setPhaseOrder(List newPhaseOrder) { + phaseOrder = newPhaseOrder; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/message/handler/Handler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/handler/Handler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/handler/Handler.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.handler; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecoder; +import org.opensaml.ws.message.encoder.MessageEncoder; + +/** + * A handler is invoked to implement specific business logic on a {@link MessageContext}. + * + *

+ * It is most commonly used to invoke logic within {@link MessageEncoder}'s and {@link MessageDecoder}'s, + * but could also be used outside of that framework. + *

+ * + */ +public interface Handler { + + /** + * Invoke the handler on the specified message context. + * + * @param msgContext the message context on which to invoke the handler + * @throws HandlerException if there is a problem handling the message context + */ + public void invoke(MessageContext msgContext) throws HandlerException; + +} Index: 3rdParty_sources/openws/org/opensaml/ws/message/handler/HandlerChain.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/handler/HandlerChain.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/handler/HandlerChain.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.handler; + +import java.util.List; + +import org.opensaml.ws.message.MessageContext; + +/** + * An ordered chain of {@link Handler} instances which may be invoked on a message context. + */ +public interface HandlerChain { + + /** + * Invoke the handler chain on the specified message context. + * + * @param msgContext the message context on which to invoke the handler chain + * @throws HandlerException if there is a problem handling the message context + */ + public void invoke(MessageContext msgContext) throws HandlerException; + + + /** + * Get the modifiable list of handlers in the handler chain. + * + * @return list of handlers + */ + public List getHandlers(); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/message/handler/HandlerChainAware.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/handler/HandlerChainAware.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/handler/HandlerChainAware.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.handler; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecoder; +import org.opensaml.ws.message.encoder.MessageEncoder; + +/** + * A marker interface for {@link MessageDecoder} and {@link MessageEncoder} implementations + * which process a message context's {@link Handler}'s. + * + *

+ * Specifically, it identifies those implementations which process the handlers produced by a message context's + * {@link MessageContext#getPreSecurityInboundHandlerChainResolver()} and + * {@link MessageContext#getPostSecurityInboundHandlerChainResolver()}, + * and {@link MessageContext#getOutboundHandlerChainResolver()}, for decoders and encoders respectively. + *

+ */ +public interface HandlerChainAware { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/message/handler/HandlerChainResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/handler/HandlerChainResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/handler/HandlerChainResolver.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.handler; + +import org.opensaml.ws.message.MessageContext; + +/** + * A resolver which uses the message context information to resolve and return instances of {@link HandlerChain}. + */ +public interface HandlerChainResolver { + + /** + * Resolve handler chain instances based on the message context. + * + * @param messageContext the message context to process + * @return resolved handler chains + * @throws HandlerException thrown if there is an error resolving the handler chain + */ + Iterable resolve(MessageContext messageContext) throws HandlerException; + +} Index: 3rdParty_sources/openws/org/opensaml/ws/message/handler/HandlerException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/handler/HandlerException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/handler/HandlerException.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.handler; + +import org.opensaml.ws.message.MessageException; + + +/** + * Base class for message handler related exceptions. + */ +public class HandlerException extends MessageException { + + /** Serial version UID. */ + private static final long serialVersionUID = -897750712163000591L; + + /** + * Constructor. + */ + public HandlerException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public HandlerException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public HandlerException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public HandlerException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/message/handler/PhasedHandlerChain.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/handler/PhasedHandlerChain.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/handler/PhasedHandlerChain.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.handler; + +import java.util.List; +import java.util.Map; + +/** + * A specialized type of {@link HandlerChain} which supports organizing multiple + * handler chains into a set of named handler chains called 'phases', which will be + * invoked in a specified order. + */ +public interface PhasedHandlerChain extends HandlerChain { + + /** + * Modifiable map of phase names to corresponding handler chains. + * + * @return the map of phase names to handler chains + */ + public Map getPhaseChains(); + + /** + * Get the order of phase invocation. Handler chains will be invoked in the order + * determined by this list. + * + * @return the ordered list of phase names + */ + public List getPhaseOrder(); + + /** + * Set the order of phase invocation. Handler chains will be invoked in the order + * determined by this list. + * + * @param newPhaseOrder a list of phase names + */ + public void setPhaseOrder(List newPhaseOrder); + + /** + * Get the complete effective list of ordered handlers in the handler chain. + * + *

+ * Note that unlike {@link HandlerChain}, the returned list is NOTmodifiable. + * {@link Handler} instances in the effective chain should be added and removed via + * membership in the appropriate handler chain phase, obtained via {@link #getPhaseChains()}. + *

+ * + * @return list of handlers + */ + public List getHandlers(); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/message/handler/StaticHandlerChainResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/message/handler/StaticHandlerChainResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/message/handler/StaticHandlerChainResolver.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.message.handler; + +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.xml.util.LazyList; + +/** A simple handler chain resolver implementation that returns a static list of handler chains. */ +public class StaticHandlerChainResolver implements HandlerChainResolver { + + /** Registered handler chains. */ + private List handlerChains; + + /** + * Constructor. + * + * @param newHandlerChain the static handler chain returned by this resolver + */ + public StaticHandlerChainResolver(HandlerChain newHandlerChain) { + handlerChains = new LazyList(); + if(newHandlerChain != null){ + handlerChains.add(newHandlerChain); + } + } + + /** + * Constructor. + * + * @param newHandlerChains the static list of handler chains returned by this resolver + */ + public StaticHandlerChainResolver(List newHandlerChains) { + handlerChains = new LazyList(); + if(newHandlerChains != null){ + handlerChains.addAll(newHandlerChains); + } + } + + /** {@inheritDoc} */ + public Iterable resolve(MessageContext messageContext) throws HandlerException { + return Collections.unmodifiableList(handlerChains); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/security/SecurityPolicy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/SecurityPolicy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/SecurityPolicy.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security; + +import java.util.List; + +import org.opensaml.ws.message.MessageContext; + +/** + * A security policy is a collection of {@link SecurityPolicyRule}, evaluated against a {@link MessageContext}, that + * is meant to determine if a message is well-formed, valid, and otherwise okay to process. + * + * Security policies MUST be thread safe and stateless. + */ +public interface SecurityPolicy { + + /** + * Gets the rules that are evaluated for this policy. + * + * @return rules that are evaluated for this policy + */ + public List getPolicyRules(); + + /** + * Evaluates this policy. Rules are evaluated in the order returned by {@link #getPolicyRules()}. + * + * @param messageContext the message context being evaluated + * + * @throws SecurityPolicyException thrown if the requirements of the security policy, including those of + * any of its rules, are not satisfied by the given message context. Also thrown if any error + * is encountered during evaluation + */ + public void evaluate(MessageContext messageContext) throws SecurityPolicyException; +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/security/SecurityPolicyException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/SecurityPolicyException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/SecurityPolicyException.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security; + +import org.opensaml.xml.security.SecurityException; + +/** + * Exception indicating a security policy failure. + */ +public class SecurityPolicyException extends SecurityException { + + /** + * Serial version UID. + */ + private static final long serialVersionUID = -1074554750436470084L; + + /** + * Constructor. + */ + public SecurityPolicyException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public SecurityPolicyException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public SecurityPolicyException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public SecurityPolicyException(String message, Exception wrappedException) { + super(message, wrappedException); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/security/SecurityPolicyResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/SecurityPolicyResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/SecurityPolicyResolver.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.xml.security.Resolver; + +/** + * A resolver which uses different criteria to resolve and return instances of {@link SecurityPolicy}. + */ +public interface SecurityPolicyResolver extends Resolver { + +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/security/SecurityPolicyRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/SecurityPolicyRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/SecurityPolicyRule.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security; + +import org.opensaml.ws.message.MessageContext; + +/** + * An individual rule that a message context is required to meet in order to be considered valid. + * + * Rules MUST be thread safe and stateless. + */ +public interface SecurityPolicyRule { + + /** + * Evaluates the message context against the rule. + * + * @param messageContext the message context being evaluated + * + * @throws SecurityPolicyException thrown if the message context does not meet the requirements of the rule, + * or if there is a non-recoverable error during evaluation + */ + public void evaluate(MessageContext messageContext) throws SecurityPolicyException; +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/security/ServletRequestX509CredentialAdapter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/ServletRequestX509CredentialAdapter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/ServletRequestX509CredentialAdapter.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security; + +import java.security.cert.X509Certificate; +import java.util.Arrays; + +import javax.servlet.ServletRequest; + +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.x509.BasicX509Credential; +import org.opensaml.xml.security.x509.X509Credential; + +/** + * An adapter that exposes the X.509 certificates contained in the servlet request attribute. + */ +public class ServletRequestX509CredentialAdapter extends BasicX509Credential implements X509Credential { + + /** Servlet request attribute to pull certificate info from. */ + public static final String X509_CERT_REQUEST_ATTRIBUTE = "javax.servlet.request.X509Certificate"; + + /** + * Constructor. + * + * @param request the servlet request + */ + public ServletRequestX509CredentialAdapter(ServletRequest request) { + X509Certificate[] chain = (X509Certificate[]) request.getAttribute(X509_CERT_REQUEST_ATTRIBUTE); + if (chain == null || chain.length == 0) { + throw new IllegalArgumentException("Servlet request does not contain X.509 certificates in attribute " + + X509_CERT_REQUEST_ATTRIBUTE); + } + + setEntityCertificate(chain[0]); + setEntityCertificateChain(Arrays.asList(chain)); + setUsageType(UsageType.SIGNING); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/security/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/package.html 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,7 @@ + + +Provides interfaces that may be used to implement policies that are evaluated against incoming messages. Such policies +may include things like message replay detection, SOAP version enforcement, SOAP "mustUnderstand" attribute enforcement, +etc. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/security/provider/BaseTrustEngineRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/provider/BaseTrustEngineRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/provider/BaseTrustEngineRule.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,111 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security.provider; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.ws.security.SecurityPolicyRule; +import org.opensaml.xml.security.CriteriaSet; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.trust.TrustEngine; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base rule which uses a trust engine to evaluate a token extracted from the request or message. + * + * @param type of token which is being evaluated by the underlying trust engine + */ +public abstract class BaseTrustEngineRule implements SecurityPolicyRule { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(BaseTrustEngineRule.class); + + /** Trust engine used to verify the particular token type. */ + private TrustEngine trustEngine; + + /** + * Constructor. + * + * @param engine Trust engine used to verify the particular token type + */ + public BaseTrustEngineRule(TrustEngine engine) { + trustEngine = engine; + } + + /** + * Gets the engine used to validate the untrusted token. + * + * @return engine engine used to validate the untrusted token + */ + protected TrustEngine getTrustEngine() { + return trustEngine; + } + + /** + * Subclasses are required to implement this method to build a criteria set for the trust engine + * according to trust engine and application-specific needs. + * + * @param entityID the candidate issuer entity ID which is being evaluated + * @param messageContext the message context which is being evaluated + * @return a newly constructly set of criteria suitable for the configured trust engine + * @throws SecurityPolicyException thrown if criteria set can not be constructed + */ + protected abstract CriteriaSet buildCriteriaSet(String entityID, MessageContext messageContext) + throws SecurityPolicyException; + + /** + * Evaluate the token using the configured trust engine against criteria built using + * the specified candidate issuer entity ID and message context information. + * + * @param token the token to be evaluated + * @param entityID the candidate issuer entity ID which is being evaluated + * @param messageContext the message context which is being evaluated + * @return true if the token satisfies the criteria as determined by the trust engine, otherwise false + * @throws SecurityPolicyException thrown if there is a fatal error during trust engine evaluation + */ + protected boolean evaluate(TokenType token, String entityID, MessageContext messageContext) + throws SecurityPolicyException { + + CriteriaSet criteriaSet = buildCriteriaSet(entityID, messageContext); + if (criteriaSet == null) { + log.error("Returned criteria set was null, can not perform trust engine evaluation of token"); + throw new SecurityPolicyException("Returned criteria set was null"); + } + + return evaluate(token, criteriaSet); + } + + /** + * Evaluate the token against the specified criteria using the configured trust engine. + * + * @param token the token to be evaluated + * @param criteriaSet the set of criteria against which to evaluate the token + * @return true if the token satisfies the criteria as determined by the trust engine, otherwise false + * @throws SecurityPolicyException thrown if there is a fatal error during trust engine evaluation + */ + protected boolean evaluate(TokenType token, CriteriaSet criteriaSet) throws SecurityPolicyException { + try { + return getTrustEngine().validate(token, criteriaSet); + } catch (SecurityException e) { + log.error("There was an error evaluating the request's token using the trust engine", e); + throw new SecurityPolicyException("Error during trust engine evaluation of the token", e); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/security/provider/BasicSecurityPolicy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/provider/BasicSecurityPolicy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/provider/BasicSecurityPolicy.java 17 Aug 2012 15:09:10 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security.provider; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicy; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.ws.security.SecurityPolicyRule; + +/** + * Basic security policy implementation which evaluates a given set of {@link SecurityPolicyRule} in an ordered manner. + * + * A policy evaluates successfully if, and only if, all policy rules evaluate successfully. + */ +public class BasicSecurityPolicy implements SecurityPolicy { + + /** Registered security rules. */ + private ArrayList rules; + + /** Constructor. */ + public BasicSecurityPolicy(){ + rules = new ArrayList(5); + } + + /** {@inheritDoc} */ + public List getPolicyRules() { + return rules; + } + + /** {@inheritDoc} */ + public void evaluate(MessageContext messageContext) throws SecurityPolicyException { + for(SecurityPolicyRule rule : getPolicyRules()){ + rule.evaluate(messageContext); + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/security/provider/CertificateNameOptions.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/provider/CertificateNameOptions.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/provider/CertificateNameOptions.java 17 Aug 2012 15:09:10 -0000 1.1 @@ -0,0 +1,161 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security.provider; + +import java.util.LinkedHashSet; + +import javax.security.auth.x500.X500Principal; + +import org.opensaml.xml.security.x509.InternalX500DNHandler; +import org.opensaml.xml.security.x509.X500DNHandler; + +/** + * Options for deriving message context issuer names from an X.509 certificate. Used by {@link ClientCertAuthRule}. + */ +public class CertificateNameOptions implements Cloneable { + + /** Evaluate the certificate subject DN as a derived issuer entity ID. */ + private boolean evaluateSubjectDN; + + /** Evaluate the certificate subject DN's common name (CN) as a derived issuer entity ID. */ + private boolean evaluateSubjectCommonName; + + /** The set of types of subject alternative names evaluate as derived issuer entity ID names. */ + private LinkedHashSet subjectAltNames; + + /** + * Responsible for serializing X.500 names to strings from certificate-derived {@link X500Principal} instances. + */ + private X500DNHandler x500DNHandler; + + /** The format specifier for serializaing X.500 subject names to strings. */ + private String x500SubjectDNFormat; + + /** Constructor. */ + public CertificateNameOptions() { + subjectAltNames = new LinkedHashSet(); + x500DNHandler = new InternalX500DNHandler(); + x500SubjectDNFormat = X500DNHandler.FORMAT_RFC2253; + } + + /** + * Get whether to evaluate the certificate subject DN's common name (CN) as a derived issuer entity ID. + * + * @return Returns the evaluateSubjectCommonName. + */ + public boolean evaluateSubjectCommonName() { + return evaluateSubjectCommonName; + } + + /** + * Set whether to evaluate the certificate subject DN's common name (CN) as a derived issuer entity ID. + * + * @param flag new new evaluateSubjectCommonName value. + */ + public void setEvaluateSubjectCommonName(boolean flag) { + evaluateSubjectCommonName = flag; + } + + /** + * Get whether to evaluate the certificate subject DN as a derived issuer entity ID. + * + * @return Returns the evaluateSubjectDN. + */ + public boolean evaluateSubjectDN() { + return evaluateSubjectDN; + } + + /** + * Set whether to evaluate the certificate subject DN as a derived issuer entity ID. + * + * @param flag the new evaluateSubjectDN value. + */ + public void setEvaluateSubjectDN(boolean flag) { + evaluateSubjectDN = flag; + } + + /** + * Get the set of types of subject alternative names evaluate as derived issuer entity ID names. + * + * @return Returns the subjectAltNames. + */ + public LinkedHashSet getSubjectAltNames() { + return subjectAltNames; + } + + /** + * Get the handler responsible for serializing X.500 names to strings from certificate-derived + * {@link X500Principal} instances. + * + * @return Returns the x500DNHandler. + */ + public X500DNHandler getX500DNHandler() { + return x500DNHandler; + } + + /** + * Set the handler responsible for serializing X.500 names to strings from certificate-derived + * {@link X500Principal} instances. + * + * @param handler the new x500DNHandler value. + */ + public void setX500DNHandler(X500DNHandler handler) { + if (handler == null) { + throw new IllegalArgumentException("X500DNHandler may not be null"); + } + x500DNHandler = handler; + } + + /** + * Get the the format specifier for serializaing X.500 subject names to strings. + * + * @return Returns the x500SubjectDNFormat. + */ + public String getX500SubjectDNFormat() { + return x500SubjectDNFormat; + } + + /** + * Set the the format specifier for serializaing X.500 subject names to strings. + * + * @param format the new x500SubjectDNFormat value. + */ + public void setX500SubjectDNFormat(String format) { + x500SubjectDNFormat = format; + } + + /** {@inheritDoc} */ + public CertificateNameOptions clone() { + CertificateNameOptions clonedOptions; + try { + clonedOptions = (CertificateNameOptions) super.clone(); + } catch (CloneNotSupportedException e) { + // we know we're cloneable, so this will never happen + return null; + } + + clonedOptions.subjectAltNames = new LinkedHashSet(); + clonedOptions.subjectAltNames.addAll(this.subjectAltNames); + + clonedOptions.x500DNHandler = this.x500DNHandler.clone(); + + return clonedOptions; + } + +} + Index: 3rdParty_sources/openws/org/opensaml/ws/security/provider/ClientCertAuthRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/provider/ClientCertAuthRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/provider/ClientCertAuthRule.java 17 Aug 2012 15:09:10 -0000 1.1 @@ -0,0 +1,503 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security.provider; + +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.xml.security.CriteriaSet; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.criteria.EntityIDCriteria; +import org.opensaml.xml.security.criteria.UsageCriteria; +import org.opensaml.xml.security.trust.TrustEngine; +import org.opensaml.xml.security.x509.X509Credential; +import org.opensaml.xml.security.x509.X509Util; +import org.opensaml.xml.util.Base64; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Policy rule that checks if the client cert used to authenticate the request is valid and trusted. + * + *

+ * This rule is only evaluated if the message context contains a peer {@link X509Credential} as returned from the + * inbound message context's inbound message transport {@link org.opensaml.ws.transport.Transport#getPeerCredential()}. + *

+ * + *

+ * The entity ID used to perform trust evaluation of the X509 credential is first retrieved via + * {@link #getCertificatePresenterEntityID(MessageContext)}. If this value is non-null, trust evaluation proceeds on + * that basis. If trust evaluation using this entity ID is successful, the message context's inbound transport + * authentication state will be set to true and processing is terminated. If unsuccessful, a + * {@link SecurityPolicyException} is thrown. + *

+ * + *

+ * If a non-null value was available from {@link #getCertificatePresenterEntityID(MessageContext)}, then rule evaluation + * will be attempted as described in {@link #evaluateCertificateNameDerivedPresenters(X509Credential, MessageContext)}, + * based on the currently configured certificate name evaluation options. If this method returns a non-null certificate + * presenter entity ID, it will be set on the message context by calling + * {@link #setAuthenticatedCertificatePresenterEntityID(MessageContext, String)} The message context's inbound transport + * authentication state will be set to true via + * {@link org.opensaml.ws.transport.InTransport#setAuthenticated(boolean)}. Rule processing is then terminated. If the + * method returns null, the client certificate presenter entity ID and inbound transport authentication state will + * remain unmodified and rule processing continues. + *

+ * + *

+ * Finally rule evaluation will proceed as described in + * {@link #evaluateDerivedPresenters(X509Credential, MessageContext)}. This is primarily an extension point by which + * subclasses may implement specific custom logic. If this method returns a non-null client certificate presenter entity + * ID, it will be set via {@link #setAuthenticatedCertificatePresenterEntityID(MessageContext, String)}, the message + * context's inbound transport authentication state will be set to true and rule processing is terminated. + * If the method returns null, the client certificate presenter entity ID and transport authentication state will remain + * unmodified. + *

+ */ +public class ClientCertAuthRule extends BaseTrustEngineRule { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(ClientCertAuthRule.class); + + /** Options for derving client cert presenter entity ID's from an X.509 certificate. */ + private CertificateNameOptions certNameOptions; + + /** + * Constructor. + * + * @param engine Trust engine used to verify the request X509Credential + * @param nameOptions options for deriving certificate presenter entity ID's from an X.509 certificate + * + */ + public ClientCertAuthRule(TrustEngine engine, CertificateNameOptions nameOptions) { + super(engine); + certNameOptions = nameOptions; + } + + /** {@inheritDoc} */ + public void evaluate(MessageContext messageContext) throws SecurityPolicyException { + + Credential peerCredential = messageContext.getInboundMessageTransport().getPeerCredential(); + + if (peerCredential == null) { + log.info("Inbound message transport did not contain a peer credential, " + + "skipping client certificate authentication"); + return; + } + if (!(peerCredential instanceof X509Credential)) { + log.info("Inbound message transport did not contain an X509Credential, " + + "skipping client certificate authentication"); + return; + } + + X509Credential requestCredential = (X509Credential) peerCredential; + if (log.isDebugEnabled()) { + try { + log.debug("Attempting to authenticate inbound connection that presented the certificate:"); + log.debug(Base64.encodeBytes(requestCredential.getEntityCertificate().getEncoded())); + } catch (CertificateEncodingException e) { + // do nothing + } + } + doEvaluate(requestCredential, messageContext); + } + + /** + * Get the currently configured certificate name options. + * + * @return the certificate name options + */ + protected CertificateNameOptions getCertificateNameOptions() { + return certNameOptions; + } + + /** + * Evaluate the request credential. + * + * @param requestCredential the X509Credential derived from the request + * @param messageContext the message context being evaluated + * @throws SecurityPolicyException thrown if a certificate presenter entity ID available from the message context + * and the client certificate token can not be establishd as trusted on that basis, or if there is error + * during evaluation processing + */ + protected void doEvaluate(X509Credential requestCredential, MessageContext messageContext) + throws SecurityPolicyException { + + String presenterEntityID = getCertificatePresenterEntityID(messageContext); + + if (presenterEntityID != null) { + log.debug("Attempting client certificate authentication using context presenter entity ID: {}", + presenterEntityID); + if (evaluate(requestCredential, presenterEntityID, messageContext)) { + log.info("Authentication via client certificate succeeded for context presenter entity ID: {}", + presenterEntityID); + messageContext.getInboundMessageTransport().setAuthenticated(true); + } else { + log.error("Authentication via client certificate failed for context presenter entity ID {}", + presenterEntityID); + throw new SecurityPolicyException( + "Client certificate authentication failed for context presenter entity ID"); + } + return; + } + + String derivedPresenter = evaluateCertificateNameDerivedPresenters(requestCredential, messageContext); + if (derivedPresenter != null) { + log.info("Authentication via client certificate succeeded for certificate-derived presenter entity ID {}", + derivedPresenter); + setAuthenticatedCertificatePresenterEntityID(messageContext, derivedPresenter); + messageContext.getInboundMessageTransport().setAuthenticated(true); + return; + } + + derivedPresenter = evaluateDerivedPresenters(requestCredential, messageContext); + if (derivedPresenter != null) { + log.info("Authentication via client certificate succeeded for derived presenter entity ID {}", + derivedPresenter); + setAuthenticatedCertificatePresenterEntityID(messageContext, derivedPresenter); + messageContext.getInboundMessageTransport().setAuthenticated(true); + return; + } + } + + /** + * Get the entity ID of the presenter of the client TLS certificate, as will be used for trust evaluation purposes. + * + *

+ * The default behavior is to return the value of {@link MessageContext#getInboundMessageIssuer()}. Subclasses may + * override to implement different logic. + *

+ * + * @param messageContext the current message context + * @return the entity ID of the client TLS certificate presenter + */ + protected String getCertificatePresenterEntityID(MessageContext messageContext) { + return messageContext.getInboundMessageIssuer(); + } + + /** + * Store the sucessfully authenticated derived entity ID of the certificate presenter in the message context. + * + *

+ * The default behavior is to set the value by calling {@link MessageContext#setInboundMessageIssuer(String)}. + * Subclasses may override to implement different logic. + *

+ * + * @param messageContext the current message context + * @param entityID the successfully authenticated derived entity ID of the client TLS certificate presenter + */ + protected void setAuthenticatedCertificatePresenterEntityID(MessageContext messageContext, String entityID) { + messageContext.setInboundMessageIssuer(entityID); + } + + /** {@inheritDoc} */ + protected CriteriaSet buildCriteriaSet(String entityID, MessageContext messageContext) + throws SecurityPolicyException { + + CriteriaSet criteriaSet = new CriteriaSet(); + if (!DatatypeHelper.isEmpty(entityID)) { + criteriaSet.add(new EntityIDCriteria(entityID)); + } + + criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); + + return criteriaSet; + } + + /** + * Evaluate any candidate presenter entity ID's which may be derived from the credential or other message context + * information. + * + *

+ * This serves primarily as an extension point for subclasses to implement application-specific logic. + *

+ * + *

+ * If multiple derived candidate entity ID's would satisfy the trust engine criteria, the choice of which one to + * return as the canonical presenter entity ID value is implementation-specific. + *

+ * + * @param requestCredential the X509Credential derived from the request + * @param messageContext the message context being evaluated + * @return a presenter entity ID which was successfully evaluated by the trust engine + * @throws SecurityPolicyException thrown if there is error during processing + * @deprecated Use {@link #evaluateDerivedPresenters(X509Credential,MessageContext)} instead + */ + protected String evaluateDerivedIssuers(X509Credential requestCredential, MessageContext messageContext) + throws SecurityPolicyException { + return evaluateDerivedPresenters(requestCredential, messageContext); + } + + /** + * Evaluate any candidate presenter entity ID's which may be derived from the credential or other message context + * information. + * + *

+ * This serves primarily as an extension point for subclasses to implement application-specific logic. + *

+ * + *

+ * If multiple derived candidate entity ID's would satisfy the trust engine criteria, the choice of which one to + * return as the canonical presenter entity ID value is implementation-specific. + *

+ * + * @param requestCredential the X509Credential derived from the request + * @param messageContext the message context being evaluated + * @return a presenter entity ID which was successfully evaluated by the trust engine + * @throws SecurityPolicyException thrown if there is error during processing + */ + protected String evaluateDerivedPresenters(X509Credential requestCredential, MessageContext messageContext) + throws SecurityPolicyException { + + return null; + } + + /** + * Evaluate candidate presenter entity ID's which may be derived from the request credential's entity certificate + * according to the options supplied via {@link CertificateNameOptions}. + * + *

+ * Configured certificate name types are derived as candidate presenter entity ID's and processed in the following + * order: + *

    + *
  1. The certificate subject DN string as serialized by the X500DNHandler obtained via + * {@link CertificateNameOptions#getX500DNHandler()} and using the output format indicated by + * {@link CertificateNameOptions#getX500SubjectDNFormat()}.
  2. + *
  3. Subject alternative names of the types configured via {@link CertificateNameOptions#getSubjectAltNames()}. + * Note that this is a LinkedHashSet, so the order of evaluation is the order of insertion.
  4. + *
  5. The first common name (CN) value appearing in the certificate subject DN.
  6. + *
+ *

+ * + *

+ * The first one of the above which is successfully evaluated by the trust engine using criteria built from + * {@link BaseTrustEngineRule#buildCriteriaSet(String, MessageContext)} will be returned. + *

+ * + * @param requestCredential the X509Credential derived from the request + * @param messageContext the message context being evaluated + * @return a certificate presenter entity ID which was successfully evaluated by the trust engine + * @throws SecurityPolicyException thrown if there is error during processing + * @deprecated Use {@link #evaluateCertificateNameDerivedPresenters(X509Credential,MessageContext)} instead + */ + protected String evaluateCertificateNameDerivedIssuers(X509Credential requestCredential, + MessageContext messageContext) throws SecurityPolicyException { + return evaluateCertificateNameDerivedPresenters(requestCredential, messageContext); + } + + /** + * Evaluate candidate presenter entity ID's which may be derived from the request credential's entity certificate + * according to the options supplied via {@link CertificateNameOptions}. + * + *

+ * Configured certificate name types are derived as candidate presenter entity ID's and processed in the following + * order: + *

    + *
  1. The certificate subject DN string as serialized by the X500DNHandler obtained via + * {@link CertificateNameOptions#getX500DNHandler()} and using the output format indicated by + * {@link CertificateNameOptions#getX500SubjectDNFormat()}.
  2. + *
  3. Subject alternative names of the types configured via {@link CertificateNameOptions#getSubjectAltNames()}. + * Note that this is a LinkedHashSet, so the order of evaluation is the order of insertion.
  4. + *
  5. The first common name (CN) value appearing in the certificate subject DN.
  6. + *
+ *

+ * + *

+ * The first one of the above which is successfully evaluated by the trust engine using criteria built from + * {@link BaseTrustEngineRule#buildCriteriaSet(String, MessageContext)} will be returned. + *

+ * + * @param requestCredential the X509Credential derived from the request + * @param messageContext the message context being evaluated + * @return a certificate presenter entity ID which was successfully evaluated by the trust engine + * @throws SecurityPolicyException thrown if there is error during processing + */ + protected String evaluateCertificateNameDerivedPresenters(X509Credential requestCredential, + MessageContext messageContext) throws SecurityPolicyException { + + String candidatePresenter = null; + + if (certNameOptions.evaluateSubjectDN()) { + candidatePresenter = evaluateSubjectDN(requestCredential, messageContext); + if (candidatePresenter != null) { + return candidatePresenter; + } + } + + if (!certNameOptions.getSubjectAltNames().isEmpty()) { + candidatePresenter = evaluateSubjectAltNames(requestCredential, messageContext); + if (candidatePresenter != null) { + return candidatePresenter; + } + } + + if (certNameOptions.evaluateSubjectCommonName()) { + candidatePresenter = evaluateSubjectCommonName(requestCredential, messageContext); + if (candidatePresenter != null) { + return candidatePresenter; + } + } + + return null; + } + + /** + * Evaluate the presenter entity ID as derived from the cert subject common name (CN). + * + * Only the first CN value from the subject DN is evaluated. + * + * @param requestCredential the X509Credential derived from the request + * @param messageContext the message context being evaluated + * @return a presenter entity ID which was successfully evaluated by the trust engine + * @throws SecurityPolicyException thrown if there is error during processing + */ + protected String evaluateSubjectCommonName(X509Credential requestCredential, MessageContext messageContext) + throws SecurityPolicyException { + + log.debug("Evaluating client cert by deriving presenter as cert CN"); + X509Certificate certificate = requestCredential.getEntityCertificate(); + String candidatePresenter = getCommonName(certificate); + if (candidatePresenter != null) { + if (evaluate(requestCredential, candidatePresenter, messageContext)) { + log.info("Authentication succeeded for presenter entity ID derived from CN {}", candidatePresenter); + return candidatePresenter; + } + } + return null; + } + + /** + * Evaluate the presenter entity ID as derived from the cert subject DN. + * + * @param requestCredential the X509Credential derived from the request + * @param messageContext the message context being evaluated + * @return a presenter entity ID which was successfully evaluated by the trust engine + * @throws SecurityPolicyException thrown if there is error during processing + */ + protected String evaluateSubjectDN(X509Credential requestCredential, MessageContext messageContext) + throws SecurityPolicyException { + + log.debug("Evaluating client cert by deriving presenter as cert subject DN"); + X509Certificate certificate = requestCredential.getEntityCertificate(); + String candidatePresenter = getSubjectName(certificate); + if (candidatePresenter != null) { + if (evaluate(requestCredential, candidatePresenter, messageContext)) { + log.info("Authentication succeeded for presenter entity ID derived from subject DN {}", + candidatePresenter); + return candidatePresenter; + } + } + return null; + } + + /** + * Evaluate the presenter entity ID as derived from the cert subject alternative names specified by types enumerated + * in {@link CertificateNameOptions#getSubjectAltNames()}. + * + * @param requestCredential the X509Credential derived from the request + * @param messageContext the message context being evaluated + * @return a presenter entity ID which was successfully evaluated by the trust engine + * @throws SecurityPolicyException thrown if there is error during processing + */ + protected String evaluateSubjectAltNames(X509Credential requestCredential, MessageContext messageContext) + throws SecurityPolicyException { + + log.debug("Evaluating client cert by deriving presenter from subject alt names"); + X509Certificate certificate = requestCredential.getEntityCertificate(); + for (Integer altNameType : certNameOptions.getSubjectAltNames()) { + log.debug("Evaluating alt names of type: {}", altNameType.toString()); + List altNames = getAltNames(certificate, altNameType); + for (String altName : altNames) { + if (evaluate(requestCredential, altName, messageContext)) { + log.info("Authentication succeeded for presenter entity ID derived from subject alt name {}", + altName); + return altName; + } + } + } + return null; + } + + /** + * Get the first common name (CN) value from the subject DN of the specified certificate. + * + * @param cert the certificate being processed + * @return the first CN value, or null if there are none + */ + protected String getCommonName(X509Certificate cert) { + List names = X509Util.getCommonNames(cert.getSubjectX500Principal()); + if (names != null && !names.isEmpty()) { + String name = names.get(0); + log.debug("Extracted common name from certificate: {}", name); + return name; + } + return null; + } + + /** + * Get subject name from a certificate, using the currently configured X500DNHandler and subject DN output format. + * + * @param cert the certificate being processed + * @return the subject name + */ + protected String getSubjectName(X509Certificate cert) { + if (cert == null) { + return null; + } + String name = null; + if (!DatatypeHelper.isEmpty(certNameOptions.getX500SubjectDNFormat())) { + name = certNameOptions.getX500DNHandler().getName(cert.getSubjectX500Principal(), + certNameOptions.getX500SubjectDNFormat()); + } else { + name = certNameOptions.getX500DNHandler().getName(cert.getSubjectX500Principal()); + } + log.debug("Extracted subject name from certificate: {}", name); + return name; + } + + /** + * Get the list of subject alt name values from the certificate which are of the specified alt name type. + * + * @param cert the certificate from which to extract alt names + * @param altNameType the type of alt name to extract + * + * @return the list of certificate subject alt names + */ + protected List getAltNames(X509Certificate cert, Integer altNameType) { + log.debug("Extracting alt names from certificate of type: {}", altNameType.toString()); + Integer[] nameTypes = new Integer[] { altNameType }; + List altNames = X509Util.getAltNames(cert, nameTypes); + List names = new ArrayList(); + for (Object altNameValue : altNames) { + if (!(altNameValue instanceof String)) { + log.debug("Skipping non-String certificate alt name value"); + } else { + names.add((String) altNameValue); + } + } + log.debug("Extracted alt names from certificate: {}", names.toString()); + return names; + } + +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/security/provider/HTTPRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/provider/HTTPRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/provider/HTTPRule.java 17 Aug 2012 15:09:10 -0000 1.1 @@ -0,0 +1,129 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security.provider; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.ws.security.SecurityPolicyRule; +import org.opensaml.ws.transport.http.HTTPTransport; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A security rule that checks basic HTTP connection properties. + */ +public class HTTPRule implements SecurityPolicyRule { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPRule.class); + + /** Expected content type of the request. */ + private String requiredContentType; + + /** Expected method of the request. */ + private String requiredRequestMethod; + + /** Whether the request must be secure. */ + private boolean requireSecured; + + /** + * Constructor. + * + * @param type expected content type + * @param method expected request method + * @param secured whether the request must be secured + */ + public HTTPRule(String type, String method, boolean secured) { + requiredContentType = DatatypeHelper.safeTrimOrNullString(type); + requiredRequestMethod = DatatypeHelper.safeTrimOrNullString(method); + requireSecured = secured; + } + + /** {@inheritDoc} */ + public void evaluate(MessageContext messageContext) throws SecurityPolicyException { + + if (!(messageContext.getInboundMessageTransport() instanceof HTTPTransport)) { + log.debug("Message context was did not contain an HTTP transport, unable to evaluate security rule"); + return; + } + + doEvaluate(messageContext); + } + + /** + * Evaluates if the message context transport, guaranteed to be of type {@link HTTPTransport}, meets all + * requirements. + * + * @param messageContext message context being evaluated + * + * @throws SecurityPolicyException thrown if the message context does not meet the requirements of an evaluated rule + */ + protected void doEvaluate(MessageContext messageContext) throws SecurityPolicyException { + HTTPTransport transport = (HTTPTransport) messageContext.getInboundMessageTransport(); + evaluateContentType(transport); + evaluateRequestMethod(transport); + evaluateSecured(transport); + } + + /** + * Checks if the transport is of the correct content type. + * + * @param transport transport being evalauted + * + * @throws SecurityPolicyException thrown if the content type was an unexpected value + */ + protected void evaluateContentType(HTTPTransport transport) throws SecurityPolicyException { + String transportContentType = transport.getHeaderValue("Content-Type"); + if (requiredContentType != null && !transportContentType.startsWith(requiredContentType)) { + log.error("Invalid content type, expected " + requiredContentType + " but was " + transportContentType); + throw new SecurityPolicyException("Invalid content type, expected " + requiredContentType + " but was " + + transportContentType); + } + } + + /** + * Checks if the transport is of the correct request method. + * + * @param transport transport being evalauted + * + * @throws SecurityPolicyException thrown if the request method was an unexpected value + */ + protected void evaluateRequestMethod(HTTPTransport transport) throws SecurityPolicyException { + String transportMethod = transport.getHTTPMethod(); + if (requiredRequestMethod != null && !transportMethod.equalsIgnoreCase(requiredRequestMethod)) { + log.error("Invalid request method, expected " + requiredRequestMethod + " but was " + transportMethod); + throw new SecurityPolicyException("Invalid request method, expected " + requiredRequestMethod + " but was " + + transportMethod); + } + } + + /** + * Checks if the transport is secured. + * + * @param transport transport being evalauted + * + * @throws SecurityPolicyException thrown if the transport is not secure and was required to be + */ + protected void evaluateSecured(HTTPTransport transport) throws SecurityPolicyException { + if (requireSecured && !transport.isConfidential()) { + log.error("Request was required to be secured but was not"); + throw new SecurityPolicyException("Request was required to be secured but was not"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/security/provider/MandatoryAuthenticatedMessageRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/provider/MandatoryAuthenticatedMessageRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/provider/MandatoryAuthenticatedMessageRule.java 17 Aug 2012 15:09:10 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security.provider; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.ws.security.SecurityPolicyRule; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Security policy rule that requires that a message has been authenticated. + */ +public class MandatoryAuthenticatedMessageRule implements SecurityPolicyRule { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(MandatoryAuthenticatedMessageRule.class); + + /** {@inheritDoc} */ + public void evaluate(MessageContext messageContext) throws SecurityPolicyException { + if(!messageContext.isIssuerAuthenticated()) { + log.error("Inbound message issuer was not authenticated."); + throw new SecurityPolicyException("Inbound message issuer was not authenticated."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/security/provider/MandatoryIssuerRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/provider/MandatoryIssuerRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/provider/MandatoryIssuerRule.java 17 Aug 2012 15:09:10 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security.provider; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.ws.security.SecurityPolicyRule; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Security policy rule implementation that which requires that an inbound message context issuer has been set by a + * previous rule. Should typically run at the end of the security policy rule chain. + */ +public class MandatoryIssuerRule implements SecurityPolicyRule { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(MandatoryIssuerRule.class); + + /** {@inheritDoc} */ + public void evaluate(MessageContext messageContext) throws SecurityPolicyException { + + if (DatatypeHelper.isEmpty(messageContext.getInboundMessageIssuer())) { + log.error("Mandatory inbound message context issuer was not present"); + throw new SecurityPolicyException("Mandatory inbound message context issuer not present"); + } + + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/security/provider/StaticSecurityPolicyResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/provider/StaticSecurityPolicyResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/provider/StaticSecurityPolicyResolver.java 17 Aug 2012 15:09:10 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.security.provider; + +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicy; +import org.opensaml.ws.security.SecurityPolicyResolver; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.util.LazyList; + +/** A simple security policy resolver implementation that returns a static list of policies. */ +public class StaticSecurityPolicyResolver implements SecurityPolicyResolver { + + /** Registered security policies. */ + private List securityPolicies; + + /** + * Constructor. + * + * @param policy the static policy returned by this resolver + */ + public StaticSecurityPolicyResolver(SecurityPolicy policy) { + securityPolicies = new LazyList(); + if(policy != null){ + securityPolicies.add(policy); + } + } + + /** + * Constructor. + * + * @param policies the static list of policies returned by this resolver + */ + public StaticSecurityPolicyResolver(List policies) { + securityPolicies = new LazyList(); + if(policies != null){ + securityPolicies.addAll(policies); + } + } + + /** {@inheritDoc} */ + public Iterable resolve(MessageContext criteria) throws SecurityException { + return Collections.unmodifiableList(securityPolicies); + } + + /** + * {@inheritDoc} + * + * If more than one policy is registered with this resolver this method returns the first policy in the list. + */ + public SecurityPolicy resolveSingle(MessageContext criteria) throws SecurityException { + if (!securityPolicies.isEmpty()) { + return securityPolicies.get(0); + } else { + return null; + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/security/provider/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/security/provider/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/security/provider/package.html 17 Aug 2012 15:09:10 -0000 1.1 @@ -0,0 +1,5 @@ + + +Basic implementations of some security policies. + + Index: 3rdParty_sources/openws/org/opensaml/ws/soap/client/BasicSOAPMessageContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/client/BasicSOAPMessageContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/client/BasicSOAPMessageContext.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.client; + +import org.opensaml.ws.message.BaseMessageContext; +import org.opensaml.ws.soap.client.SOAPClient.SOAPRequestParameters; + +/** Basic {@link SOAPMessageContext} implementation. */ +public class BasicSOAPMessageContext extends BaseMessageContext implements SOAPMessageContext { + + /** Binding/transport-specific SOAP request parameters. */ + private SOAPRequestParameters requestParameters; + + /** {@inheritDoc} */ + public SOAPRequestParameters getSOAPRequestParameters() { + return requestParameters; + } + + /** {@inheritDoc} */ + public void setSOAPRequestParameters(SOAPRequestParameters parameters) { + requestParameters = parameters; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/client/SOAPClient.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/client/SOAPClient.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/client/SOAPClient.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.client; + +import org.opensaml.ws.soap.common.SOAPException; +import org.opensaml.xml.security.SecurityException; + +import net.jcip.annotations.ThreadSafe; + +/** + * An interface for a very basic SOAP client. + * + * Implementations of this interface do NOT attempt to do intelligent things like figure out when and how to attach + * WS-Security headers. It is strictly meant to open sockets, shuttle messages over it, and return a response. + */ +@ThreadSafe +public interface SOAPClient { + + /** + * Sends a message and waits for a response. + * + * @param endpoint the endpoint to which to send the message + * @param messageContext the message context containing the outbound SOAP message + * + * @throws SOAPClientException thrown if there is a problem sending the message or receiving the response or if the + * response is a SOAP fault + * @throws SecurityException thrown if the response does not meet any security policy associated with the message + * context + */ + public void send(String endpoint, SOAPMessageContext messageContext) throws SOAPException, SecurityException; + + /** Marker interface for binding/transport request parameters. */ + public interface SOAPRequestParameters {}; +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/client/SOAPClientException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/client/SOAPClientException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/client/SOAPClientException.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.client; + +import org.opensaml.ws.soap.common.SOAPException; + +/** Exception indicating an error sending or receiving a SOAP message. */ +public class SOAPClientException extends SOAPException { + + /** Serial version UID. */ + private static final long serialVersionUID = 6203715340959992457L; + + /** Constructor. */ + public SOAPClientException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public SOAPClientException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public SOAPClientException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public SOAPClientException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/client/SOAPFaultException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/client/SOAPFaultException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/client/SOAPFaultException.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,82 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.client; + +import org.opensaml.ws.soap.common.SOAPException; +import org.opensaml.ws.soap.soap11.Fault; + +/** Exception indicating a SOAP fault. */ +public class SOAPFaultException extends SOAPException { + + /** Serial version UID. */ + private static final long serialVersionUID = 4770411452264097320L; + + /** The fault that caused this exception. */ + private Fault soapFault; + + /** Constructor. */ + public SOAPFaultException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public SOAPFaultException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public SOAPFaultException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public SOAPFaultException(String message, Exception wrappedException) { + super(message, wrappedException); + } + + /** + * Gets the fault that caused the exception. + * + * @return fault that caused the exception + */ + public Fault getFault() { + return soapFault; + } + + /** + * Sets the fault that caused the exception. + * + * @param fault fault that caused the exception + */ + public void setFault(Fault fault) { + soapFault = fault; + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/client/SOAPMessageContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/client/SOAPMessageContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/client/SOAPMessageContext.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.client; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.soap.client.SOAPClient.SOAPRequestParameters; + +/** Message context for SOAP messages. */ +public interface SOAPMessageContext extends MessageContext{ + + /** + * Gets a set of binding/transport-specific request parameters. + * + * @return set of binding/transport-specific request parameters + */ + public SOAPRequestParameters getSOAPRequestParameters(); + + /** + * Sets a set of binding/transport-specific request parameters. + * + * @param parameters a set of binding/transport-specific request parameters + */ + public void setSOAPRequestParameters(SOAPRequestParameters parameters); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/client/http/HttpClientBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/client/http/HttpClientBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/client/http/HttpClientBuilder.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,409 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.client.http; + +import net.jcip.annotations.NotThreadSafe; + +import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; +import org.apache.commons.httpclient.HostConfiguration; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; +import org.apache.commons.httpclient.UsernamePasswordCredentials; +import org.apache.commons.httpclient.auth.AuthScope; +import org.apache.commons.httpclient.params.HttpClientParams; +import org.apache.commons.httpclient.params.HttpConnectionManagerParams; +import org.apache.commons.httpclient.protocol.Protocol; +import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * A builder for {@link HttpClient}s. + * + * This builder will produce clients that employ the {@link MultiThreadedHttpConnectionManager} and as such users of the + * clients MUST be sure to invoke {@link org.apache.commons.httpclient.HttpMethod#releaseConnection()} after they have + * finished with the method. + */ +@NotThreadSafe +public class HttpClientBuilder { + + /** Host name of the HTTP proxy server through which connections will be made. */ + private String proxyHost; + + /** Port number of the HTTP proxy server through which connections will be made. */ + private int proxyPort; + + /** Username used to connect to the HTTP proxy server. */ + private String proxyUsername; + + /** Password used to connect to the HTTP proxy server. */ + private String proxyPassword; + + /** Whether authentication should be performed preemptively, defaults to false. */ + private boolean preemptiveAuthentication; + + /** Character set used for HTTP content, defaults to UTF-8. */ + private String contentCharSet; + + /** Amount of time, in milliseconds, to wait for a connection to be established, default is 5,000. */ + private int connectionTimeout; + + /** Size of the buffer, in bytes, used to hold outbound information, defaults to 4,096. */ + private int sendBufferSize; + + /** Size of the buffer, in bytes, used to hold inbound information, defaults to 16,384. */ + private int receiveBufferSize; + + /** Whether to use TCP No Delay algorithm, defaults to true. */ + private boolean tcpNoDelay; + + /** Total number of connections allowed to a specific host, defaults to 5. */ + private int maxConnectionsPerHost; + + /** Total number of connections allowed to all hosts, defaults to 20. */ + private int maxTotalConnectons; + + /** Number of times a failed connection to a host should be retried. */ + private int connectionRetryAttempts; + + /** Socket factory used for the 'https' scheme. */ + private SecureProtocolSocketFactory httpsProtocolSocketFactory; + + /** Constructor. */ + public HttpClientBuilder() { + resetDefaults(); + } + + /** Resets the builder to its default values. */ + public void resetDefaults() { + proxyPort = -1; + preemptiveAuthentication = false; + contentCharSet = "UTF-8"; + connectionTimeout = 5000; + sendBufferSize = 4096; + receiveBufferSize = 16384; + tcpNoDelay = true; + maxConnectionsPerHost = 5; + maxTotalConnectons = 20; + connectionRetryAttempts = 0; + } + + /** + * Builds an HTTP client with the given settings. Settings are NOT reset to their default values after a client has + * been created. + * + * @return the created client. + */ + public HttpClient buildClient() { + if (httpsProtocolSocketFactory != null) { + Protocol.registerProtocol("https", new Protocol("https", httpsProtocolSocketFactory, 443)); + } + + HttpClientParams clientParams = new HttpClientParams(); + clientParams.setAuthenticationPreemptive(isPreemptiveAuthentication()); + clientParams.setContentCharset(getContentCharSet()); + clientParams.setParameter(HttpClientParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler( + connectionRetryAttempts, false)); + + HttpConnectionManagerParams connMgrParams = new HttpConnectionManagerParams(); + connMgrParams.setConnectionTimeout(getConnectionTimeout()); + connMgrParams.setDefaultMaxConnectionsPerHost(getMaxConnectionsPerHost()); + connMgrParams.setMaxTotalConnections(getMaxTotalConnections()); + connMgrParams.setReceiveBufferSize(getReceiveBufferSize()); + connMgrParams.setSendBufferSize(getSendBufferSize()); + connMgrParams.setTcpNoDelay(isTcpNoDelay()); + + MultiThreadedHttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager(); + connMgr.setParams(connMgrParams); + + HttpClient httpClient = new HttpClient(clientParams, connMgr); + + if (proxyHost != null) { + HostConfiguration hostConfig = new HostConfiguration(); + hostConfig.setProxy(proxyHost, proxyPort); + httpClient.setHostConfiguration(hostConfig); + + if (proxyUsername != null) { + AuthScope proxyAuthScope = new AuthScope(proxyHost, proxyPort); + UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(proxyUsername, + proxyPassword); + httpClient.getState().setProxyCredentials(proxyAuthScope, proxyCredentials); + } + } + + return httpClient; + } + + /** + * Gets the host name of the HTTP proxy server through which connections will be made. + * + * @return host name of the HTTP proxy server through which connections will be made + */ + public String getProxyHost() { + return proxyHost; + } + + /** + * Sets the host name of the HTTP proxy server through which connections will be made. + * + * @param host host name of the HTTP proxy server through which connections will be made + */ + public void setProxyHost(String host) { + proxyHost = DatatypeHelper.safeTrimOrNullString(host); + } + + /** + * Gets the port of the HTTP proxy server through which connections will be made. + * + * @return port of the HTTP proxy server through which connections will be made + */ + public int getProxyPort() { + return proxyPort; + } + + /** + * Sets the port of the HTTP proxy server through which connections will be made. + * + * @param port port of the HTTP proxy server through which connections will be made + */ + public void setProxyPort(int port) { + proxyPort = port; + } + + /** + * Gets the username used to connect to the HTTP proxy server. + * + * @return username used to connect to the HTTP proxy server + */ + public String getProxyUsername() { + return proxyUsername; + } + + /** + * Sets the username used to connect to the HTTP proxy server. + * + * @param username username used to connect to the HTTP proxy server + */ + public void setProxyUsername(String username) { + proxyUsername = DatatypeHelper.safeTrimOrNullString(username); + } + + /** + * Gets the password used to connect to the HTTP proxy server. + * + * @return password used to connect to the HTTP proxy server + */ + public String getProxyPassword() { + return proxyPassword; + } + + /** + * Sets the password used to connect to the HTTP proxy server. + * + * @param password password used to connect to the HTTP proxy server + */ + public void setProxyPassword(String password) { + proxyPassword = DatatypeHelper.safeTrimOrNullString(password); + } + + /** + * Gets whether authentication is performed preemptively. Default value is false. + * + * @return whether authentication is performed preemptively + */ + public boolean isPreemptiveAuthentication() { + return preemptiveAuthentication; + } + + /** + * Sets whether authentication is performed preemptively. + * + * @param preemptive whether authentication is performed preemptively + */ + public void setPreemptiveAuthentication(boolean preemptive) { + preemptiveAuthentication = preemptive; + } + + /** + * Gets the character set used for HTTP content. Default value is UTF-8. + * + * @return character set used for HTTP content + */ + public String getContentCharSet() { + return contentCharSet; + } + + /** + * Sets the character set used for HTTP content. + * + * @param charSet character set used for HTTP content + */ + public void setContentCharSet(String charSet) { + contentCharSet = charSet; + } + + /** + * Gets the time, in milliseconds, to wait for connection establishments. Default value is 5,000. A value of 0 + * indicates there is no timeout. + * + * @return time, in milliseconds, to wait for connection establishments + */ + public int getConnectionTimeout() { + return connectionTimeout; + } + + /** + * Sets the time, in milliseconds, to wait for connection establishments. A value of 0 indicates there is no + * timeout. + * + * @param timeout time, in milliseconds, to wait for connection establishments + */ + public void setConnectionTimeout(int timeout) { + connectionTimeout = timeout; + } + + /** + * Gets the size of buffer, in bytes, used when sending content. Default value is 4,096. + * + * @return size of buffer, in bytes, used when sending content + */ + public int getSendBufferSize() { + return sendBufferSize; + } + + /** + * Sets the size of buffer, in bytes, used when sending content. + * + * @param size size of buffer, in bytes, used when sending content + */ + public void setSendBufferSize(int size) { + sendBufferSize = size; + } + + /** + * Gets the size of buffer, in bytes, used when receiving content. Default value is 16,384. + * + * @return size of buffer, in bytes, used when sending content + */ + public int getReceiveBufferSize() { + return receiveBufferSize; + } + + /** + * Sets the size of buffer, in bytes, used when sending content. + * + * @param size size of buffer, in bytes, used when sending content + */ + public void setReceiveBufferSize(int size) { + receiveBufferSize = size; + } + + /** + * Gets whether to use TCP No Delay when sending data. Default value is true. + * + * @return whether to use TCP No Delay when sending data + */ + public boolean isTcpNoDelay() { + return tcpNoDelay; + } + + /** + * Sets whether to use TCP No Delay when sending data. + * + * @param noDelay whether to use TCP No Delay when sending data + */ + public void setTcpNoDelay(boolean noDelay) { + tcpNoDelay = noDelay; + } + + /** + * Gets the maximum number of connections, per host, that the client will create. Default value is 5. A value of 0 + * indicates there is no maximum. + * + * @return maximum number of connections, per host, that the client will create + */ + public int getMaxConnectionsPerHost() { + return maxConnectionsPerHost; + } + + /** + * Sets the maximum number of connections, per host, that the client will create. A value of 0 indicates there is no + * maximum. + * + * @param max maximum number of connections, per host, that the client will create + */ + public void setMaxConnectionsPerHost(int max) { + maxConnectionsPerHost = max; + } + + /** + * Gets the maximum number of total connections the client will create. Default value is 20. + * + * @return maximum number of total connections the client will create + */ + public int getMaxTotalConnections() { + return maxTotalConnectons; + } + + /** + * Sets the maximum number of total connections the client will create. + * + * @param max maximum number of total connections the client will create, must be greater than zero + */ + public void setMaxTotalConnections(int max) { + if (max < 1) { + throw new IllegalArgumentException("Maximum total number of connections must be greater than zero."); + } + maxTotalConnectons = max; + } + + /** + * Gets the number of times a connection will be tried if a host is unreachable. + * + * @return number of times a connection will be tried if a host is unreachable + */ + public int getConnectionRetryAttempts() { + return connectionRetryAttempts; + } + + /** + * Sets the number of times a connection will be tried if a host is unreachable. + * + * @param attempts number of times a connection will be tried if a host is unreachable + */ + public void setConnectionRetryAttempts(int attempts) { + connectionRetryAttempts = attempts; + } + + /** + * Gets the protocol socket factory used for the https scheme. + * + * @return protocol socket factory used for the https scheme + */ + public SecureProtocolSocketFactory getHttpsProtocolSocketFactory() { + return httpsProtocolSocketFactory; + } + + /** + * Sets the protocol socket factory used for the https scheme. + * + * @param factory the httpsProtocolSocketFactory to set + */ + public void setHttpsProtocolSocketFactory(SecureProtocolSocketFactory factory) { + httpsProtocolSocketFactory = factory; + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/client/http/HttpSOAPClient.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/client/http/HttpSOAPClient.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/client/http/HttpSOAPClient.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,279 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.client.http; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.Charset; +import java.util.List; + +import net.jcip.annotations.ThreadSafe; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.methods.ByteArrayRequestEntity; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.RequestEntity; +import org.opensaml.ws.security.SecurityPolicy; +import org.opensaml.ws.security.SecurityPolicyResolver; +import org.opensaml.ws.soap.client.SOAPClient; +import org.opensaml.ws.soap.client.SOAPClientException; +import org.opensaml.ws.soap.client.SOAPFaultException; +import org.opensaml.ws.soap.client.SOAPMessageContext; +import org.opensaml.ws.soap.common.SOAPException; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.soap.soap11.Fault; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.Marshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.io.Unmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.parse.XMLParserException; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Element; + +/** + * SOAP client that uses HTTP as the underlying transport and POST as the binding. + * + * NOTE this client does not provide access to a {@link org.opensaml.ws.transport.InTransport} or + * {@link org.opensaml.ws.transport.OutTransport}. Therefore any {@link SecurityPolicy} which operates on these object + * can not be used with this client. + */ +@ThreadSafe +public class HttpSOAPClient implements SOAPClient { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HttpSOAPClient.class); + + /** HTTP client used to send requests and receive responses. */ + private HttpClient httpClient; + + /** Pool of XML parsers used to parser incoming responses. */ + private ParserPool parserPool; + + /** + * Constructor. + * + * @param client Client used to make outbound HTTP requests. This client SHOULD employ a + * {@link org.apache.commons.httpclient.MultiThreadedHttpConnectionManager} and may be shared with other + * objects. + * @param parser pool of XML parsers used to parse incoming responses + */ + public HttpSOAPClient(HttpClient client, ParserPool parser) { + if (client == null) { + throw new IllegalArgumentException("HtppClient may not be null"); + } + httpClient = client; + + if (parser == null) { + throw new IllegalArgumentException("ParserPool may not be null"); + } + parserPool = parser; + } + + /** {@inheritDoc} */ + public void send(String endpoint, SOAPMessageContext messageContext) throws SOAPException, SecurityException { + PostMethod post = null; + try { + post = createPostMethod(endpoint, (HttpSOAPRequestParameters) messageContext.getSOAPRequestParameters(), + (Envelope) messageContext.getOutboundMessage()); + + int result = httpClient.executeMethod(post); + log.debug("Received HTTP status code of {} when POSTing SOAP message to {}", result, endpoint); + + if (result == HttpStatus.SC_OK) { + processSuccessfulResponse(post, messageContext); + } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) { + processFaultResponse(post, messageContext); + } else { + throw new SOAPClientException("Received " + result + " HTTP response status code from HTTP request to " + + endpoint); + } + } catch (IOException e) { + throw new SOAPClientException("Unable to send request to " + endpoint, e); + } finally { + if (post != null) { + post.releaseConnection(); + } + } + } + + /** + * Creates the post method used to send the SOAP request. + * + * @param endpoint endpoint to which the message is sent + * @param requestParams HTTP request parameters + * @param message message to be sent + * + * @return the post method to be used to send this message + * + * @throws SOAPClientException thrown if the message could not be marshalled + */ + protected PostMethod createPostMethod(String endpoint, HttpSOAPRequestParameters requestParams, Envelope message) + throws SOAPClientException { + log.debug("POSTing SOAP message to {}", endpoint); + + PostMethod post = new PostMethod(endpoint); + post.setRequestEntity(createRequestEntity(message, Charset.forName("UTF-8"))); + if (requestParams != null && requestParams.getSoapAction() != null) { + post.setRequestHeader(HttpSOAPRequestParameters.SOAP_ACTION_HEADER, requestParams.getSoapAction()); + } + + return post; + } + + /** + * Creates the request entity that makes up the POST message body. + * + * @param message message to be sent + * @param charset character set used for the message + * + * @return request entity that makes up the POST message body + * + * @throws SOAPClientException thrown if the message could not be marshalled + */ + protected RequestEntity createRequestEntity(Envelope message, Charset charset) throws SOAPClientException { + try { + Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(message); + ByteArrayOutputStream arrayOut = new ByteArrayOutputStream(); + OutputStreamWriter writer = new OutputStreamWriter(arrayOut, charset); + + if (log.isDebugEnabled()) { + log.debug("Outbound SOAP message is:\n" + XMLHelper.prettyPrintXML(marshaller.marshall(message))); + } + XMLHelper.writeNode(marshaller.marshall(message), writer); + return new ByteArrayRequestEntity(arrayOut.toByteArray(), "text/xml"); + } catch (MarshallingException e) { + throw new SOAPClientException("Unable to marshall SOAP envelope", e); + } + } + + /** + * Processes a successful, as determined by an HTTP 200 status code, response. + * + * @param httpMethod the HTTP method used to send the request and receive the response + * @param messageContext current messages context + * + * @throws SOAPClientException thrown if there is a problem reading the response from the {@link PostMethod} + */ + protected void processSuccessfulResponse(PostMethod httpMethod, SOAPMessageContext messageContext) + throws SOAPClientException { + try { + Envelope response = unmarshallResponse(httpMethod.getResponseBodyAsStream()); + messageContext.setInboundMessage(response); + evaluateSecurityPolicy(messageContext); + } catch (IOException e) { + throw new SOAPClientException("Unable to read response", e); + } + } + + /** + * Processes a SOAP fault, as determined by an HTTP 500 status code, response. + * + * @param httpMethod the HTTP method used to send the request and receive the response + * @param messageContext current messages context + * + * @throws SOAPClientException thrown if the response can not be read from the {@link PostMethod} + * @throws SOAPFaultException an exception containing the SOAP fault + */ + protected void processFaultResponse(PostMethod httpMethod, SOAPMessageContext messageContext) + throws SOAPClientException, SOAPFaultException { + try { + Envelope response = unmarshallResponse(httpMethod.getResponseBodyAsStream()); + messageContext.setInboundMessage(response); + + List faults = response.getBody().getUnknownXMLObjects(Fault.DEFAULT_ELEMENT_NAME); + if (faults.size() < 1) { + throw new SOAPClientException("HTTP status code was 500 but SOAP response did not contain a Fault"); + } + Fault fault = (Fault) faults.get(0); + + log.debug("SOAP fault code {} with message {}", fault.getCode().getValue(), fault.getMessage().getValue()); + SOAPFaultException faultException = new SOAPFaultException("SOAP Fault: " + fault.getCode().getValue() + + " Fault Message: " + fault.getMessage().getValue()); + faultException.setFault(fault); + throw faultException; + } catch (IOException e) { + throw new SOAPClientException("Unable to read response", e); + } + } + + /** + * Unmarshalls the incoming response from a POST request. + * + * @param responseStream input stream bearing the response + * + * @return the response + * + * @throws SOAPClientException thrown if the incoming response can not be unmarshalled into an {@link Envelope} + */ + protected Envelope unmarshallResponse(InputStream responseStream) throws SOAPClientException { + try { + Element responseElem = parserPool.parse(responseStream).getDocumentElement(); + if (log.isDebugEnabled()) { + log.debug("Inbound SOAP message was:\n" + XMLHelper.prettyPrintXML(responseElem)); + } + Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(responseElem); + return (Envelope) unmarshaller.unmarshall(responseElem); + } catch (XMLParserException e) { + throw new SOAPClientException("Unable to parse the XML within the response", e); + } catch (UnmarshallingException e) { + throw new SOAPClientException("unable to unmarshall the response DOM", e); + } + } + + /** + * Evaluates the security policy associated with the given message context. If no policy resolver is registered or + * no policy is located during the resolution process then no policy is evaluated. Note that neither the inbound or + * outbound message transport is available. + * + * @param messageContext current message context + * + * @throws SOAPClientException thrown if there is a problem resolving or evaluating a security policy + */ + protected void evaluateSecurityPolicy(SOAPMessageContext messageContext) throws SOAPClientException { + SecurityPolicyResolver policyResolver = messageContext.getSecurityPolicyResolver(); + if (policyResolver == null) { + return; + } + + SecurityPolicy policy = null; + try { + policy = policyResolver.resolveSingle(messageContext); + if (policy == null) { + return; + } + } catch (SecurityException e) { + throw new SOAPClientException("Unable to resolve security policy for inbound SOAP response", e); + } + + try { + log.debug("Evaluating security policy for inbound SOAP response"); + policy.evaluate(messageContext); + } catch (SecurityException e) { + throw new SOAPClientException("Inbound SOAP response does not meet security policy", e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/client/http/HttpSOAPRequestParameters.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/client/http/HttpSOAPRequestParameters.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/client/http/HttpSOAPRequestParameters.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.client.http; + +import net.jcip.annotations.ThreadSafe; + +import org.opensaml.ws.soap.client.SOAPClient.SOAPRequestParameters; +import org.opensaml.xml.util.DatatypeHelper; + +/** HTTP transported SOAP request parameters. */ +@ThreadSafe +public class HttpSOAPRequestParameters implements SOAPRequestParameters { + + /** Name of the HTTP SOAPAction header. */ + public static final String SOAP_ACTION_HEADER = "SOAPAction"; + + /** HTTP SOAPAction header. */ + private String soapAction; + + /** + * Constructor. + * + * @param action value for the SOAPAction HTTP header + */ + public HttpSOAPRequestParameters(String action) { + soapAction = DatatypeHelper.safeTrimOrNullString(action); + } + + /** + * Gets the HTTP SOAPAction header. + * + * @return HTTP SOAPAction header + */ + public String getSoapAction() { + return soapAction; + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/client/http/TLSProtocolSocketFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/client/http/TLSProtocolSocketFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/client/http/TLSProtocolSocketFactory.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,117 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.client.http; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.security.GeneralSecurityException; + +import javax.net.SocketFactory; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509KeyManager; +import javax.net.ssl.X509TrustManager; + +import net.jcip.annotations.ThreadSafe; + +import org.apache.commons.httpclient.params.HttpConnectionParams; +import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; + +/** An SSL/TLS socket factory that uses KeyStoreFactory's to get its key and trust material. */ +@ThreadSafe +public class TLSProtocolSocketFactory implements SecureProtocolSocketFactory { + + /** Manager used to retrieve client-cert authentication keys for a given host. */ + private X509KeyManager keyManager; + + /** Manager used to validate the X.509 credentials of a given host. */ + private X509TrustManager trustManager; + + /** Currently active SSL context. */ + private SSLContext sslContext; + + /** + * Constructor. + * + * @param keyMgr manager used to retrieve client-cert authentication keys for a given host + * @param trustMgr manager used to validate the X.509 credentials of a given host + * + * @throws IllegalArgumentException thrown if the given key or trust manager can not be used to create the + * {@link SSLContext} used to create new sockets + */ + public TLSProtocolSocketFactory(X509KeyManager keyMgr, X509TrustManager trustMgr) throws IllegalArgumentException { + keyManager = keyMgr; + trustManager = trustMgr; + + try { + sslContext = SSLContext.getInstance("SSL"); + sslContext.init(new KeyManager[] { keyManager }, new TrustManager[] { trustManager }, null); + } catch (GeneralSecurityException e) { + throw new IllegalArgumentException("Error create SSL context", e); + } + } + + /** {@inheritDoc} */ + public Socket createSocket(String host, int port) throws IOException { + return sslContext.getSocketFactory().createSocket(host, port); + } + + /** {@inheritDoc} */ + public Socket createSocket(String host, int port, InetAddress localHost, int clientPort) throws IOException { + return sslContext.getSocketFactory().createSocket(host, port, localHost, clientPort); + } + + /** {@inheritDoc} */ + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } + + /** {@inheritDoc} */ + public Socket createSocket(String host, int port, InetAddress localHost, int localPort, + HttpConnectionParams connParams) throws IOException { + if (connParams == null) { + throw new IllegalArgumentException("Parameters may not be null"); + } + int timeout = connParams.getConnectionTimeout(); + SocketFactory socketfactory = sslContext.getSocketFactory(); + if (timeout == 0) { + return socketfactory.createSocket(host, port, localHost, localPort); + } else { + Socket socket = socketfactory.createSocket(); + SocketAddress localaddr = new InetSocketAddress(localHost, localPort); + SocketAddress remoteaddr = new InetSocketAddress(host, port); + socket.bind(localaddr); + socket.connect(remoteaddr, timeout); + return socket; + } + } + + /** {@inheritDoc} */ + public boolean equals(Object obj) { + return (obj != null) && obj.getClass().equals(getClass()); + } + + /** {@inheritDoc} */ + public int hashCode() { + return getClass().hashCode(); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/common/AbstractExtensibleSOAPObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/common/AbstractExtensibleSOAPObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/common/AbstractExtensibleSOAPObject.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.common; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; +import org.opensaml.xml.validation.AbstractValidatingXMLObject; + +/** + * Abstract class implementating validation and element and attribute extensibility. + */ +public class AbstractExtensibleSOAPObject extends AbstractValidatingXMLObject implements SOAPObject, + AttributeExtensibleXMLObject, ElementExtensibleXMLObject { + + /** "Any" type children. */ + private IndexedXMLObjectChildrenList unknownXMLObjects; + + /** Attributes of the proxied Element. */ + private AttributeMap attributes; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + protected AbstractExtensibleSOAPObject(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributes = new AttributeMap(this); + unknownXMLObjects = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(unknownXMLObjects); + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownXMLObjects; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownXMLObjects.subList(typeOrName); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return attributes; + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/common/SOAPException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/common/SOAPException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/common/SOAPException.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.common; + +import org.opensaml.ws.WSException; + +/** + * Base SOAP exception. + */ +public class SOAPException extends WSException { + + /** Serial version UID. */ + private static final long serialVersionUID = 1374150092262909937L; + + /** + * Constructor. + */ + public SOAPException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public SOAPException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public SOAPException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public SOAPException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/common/SOAPHandler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/common/SOAPHandler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/common/SOAPHandler.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.common; + +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.message.handler.Handler; + +/** + * Interface for {@link Handler}'s that are specific to SOAP message processing. + */ +public interface SOAPHandler extends Handler { + + /** + * Get the set of SOAP header names that the handler + * indicates it understands. + * + * @return unmodifiable set of understood header names, possibly empty + */ + public Set understandsHeaders(); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/common/SOAPObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/common/SOAPObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/common/SOAPObject.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.common; + +import org.opensaml.xml.validation.ValidatingXMLObject; + +/** + * Base interface for all SOAP objects. + */ +public interface SOAPObject extends ValidatingXMLObject { + +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/common/SOAPObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/common/SOAPObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/common/SOAPObjectBuilder.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.common; + +import org.opensaml.xml.XMLObjectBuilder; + +/** + * Builder for SOAPObjects. + * + * @param the type of SOAPObject being built + */ +public interface SOAPObjectBuilder extends XMLObjectBuilder { + + /** + * Builds a SOAPObject using the default name and namespace information provided SOAP specifications. + * + * @return built SAMLObject + */ + public SOAPObjectType buildObject(); +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/common/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/common/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/common/package.html 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,5 @@ + + +Common classes shared across SOAP versions, clients, and transports. + + Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/ActorBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/ActorBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/ActorBearing.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.util.SOAPConstants; + +/** + * Interface for element having a @soap11:actor attribute. + */ +public interface ActorBearing { + + /** The soap11:@actor attribute local name. */ + public static final String SOAP11_ACTOR_ATTR_LOCAL_NAME = "actor"; + + /** The soap11:@actor qualified attribute name. */ + public static final QName SOAP11_ACTOR_ATTR_NAME = + new QName(SOAPConstants.SOAP11_NS, SOAP11_ACTOR_ATTR_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + + /** The specification-defined value 'http://schemas.xmlsoap.org/soap/actor/next'. */ + public static final String SOAP11_ACTOR_NEXT = "http://schemas.xmlsoap.org/soap/actor/next"; + + /** + * Get the attribute value. + * + * @return return the attribute vlue + */ + public String getSOAP11Actor(); + + /** + * Set the attribute value. + * + * @param newActor the new attribute value + */ + public void setSOAP11Actor(String newActor); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Body.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Body.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Body.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.common.SOAPObject; +import org.opensaml.ws.soap.util.SOAPConstants; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * SOAP 1.1 Body. + */ +public interface Body extends SOAPObject, ElementExtensibleXMLObject, AttributeExtensibleXMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Body"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SOAPConstants.SOAP11_NS, DEFAULT_ELEMENT_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "Body"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SOAPConstants.SOAP11_NS, TYPE_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Detail.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Detail.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Detail.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.common.SOAPObject; +import org.opensaml.ws.soap.util.SOAPConstants; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * SOAP 1.1 Detail. + */ +public interface Detail extends SOAPObject, ElementExtensibleXMLObject, AttributeExtensibleXMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "detail"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(DEFAULT_ELEMENT_LOCAL_NAME); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "detail"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SOAPConstants.SOAP11_NS, TYPE_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/EncodingStyleBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/EncodingStyleBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/EncodingStyleBearing.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.util.SOAPConstants; + +/** + * Interface for element having a @soap11:encodingStyle attribute. + */ +public interface EncodingStyleBearing { + + /** The soap11:@encodingStyle attribute local name. */ + public static final String SOAP11_ENCODING_STYLE_ATTR_LOCAL_NAME = "encodingStyle"; + + /** The soap11:@encodingStyle qualified attribute name. */ + public static final QName SOAP11_ENCODING_STYLE_ATTR_NAME = + new QName(SOAPConstants.SOAP11_NS, SOAP11_ENCODING_STYLE_ATTR_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + + /** + * Get the attribute value. + * + * @return return the list of attribute values + */ + public List getSOAP11EncodingStyles(); + + /** + * Set the attribute value. + * + * @param newEncodingStyles the new list of attribute values + */ + public void setSOAP11EncodingStyles(List newEncodingStyles); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Envelope.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Envelope.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Envelope.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.common.SOAPObject; +import org.opensaml.ws.soap.util.SOAPConstants; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * SOAP 1.1 Envelope. + */ +public interface Envelope extends SOAPObject, ElementExtensibleXMLObject, AttributeExtensibleXMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Envelope"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SOAPConstants.SOAP11_NS, DEFAULT_ELEMENT_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "Envelope"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SOAPConstants.SOAP11_NS, TYPE_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + + /** + * Gets the header of this envelope. + * + * @return the header of this envelope + */ + public Header getHeader(); + + /** + * Sets the header of this envelope. + * + * @param newHeader the header of this envelope + */ + public void setHeader(Header newHeader); + + /** + * Gets the body of this envelope. + * + * @return the body of this envelope + */ + public Body getBody(); + + /** + * Sets the body of this envelope. + * + * @param newBody the body of this envelope + */ + public void setBody(Body newBody); +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Fault.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Fault.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Fault.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,99 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.common.SOAPObject; +import org.opensaml.ws.soap.util.SOAPConstants; + +/** + * SOAP 1.1 Fault. + */ +public interface Fault extends SOAPObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Fault"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SOAPConstants.SOAP11_NS, DEFAULT_ELEMENT_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "Fault"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SOAPConstants.SOAP11_NS, TYPE_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + + /** + * Gets the fault code for this fault. + * + * @return the fault code for this fault + */ + public FaultCode getCode(); + + /** + * Sets the fault code for this fault. + * + * @param newFaultCode the fault code for this fault + */ + public void setCode(FaultCode newFaultCode); + + /** + * Gets the fault string for this fault. + * + * @return the fault string for this fault + */ + public FaultString getMessage(); + + /** + * Sets the fault string for this fault. + * + * @param newMessage the fault string for this fault + */ + public void setMessage(FaultString newMessage); + + /** + * Gets the URI of the fault actor for this fault. + * + * @return the URI of the fault actor for this fault + */ + public FaultActor getActor(); + + /** + * Sets the URI of the fault actor for this fault. + * + * @param newActor the URI of the fault actor for this fault + */ + public void setActor(FaultActor newActor); + + /** + * Gets details of this fault. + * + * @return details of this fault + */ + public Detail getDetail(); + + /** + * Sets details of this fault. + * + * @param newDetail details of this fault + */ + public void setDetail(Detail newDetail); +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/FaultActor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/FaultActor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/FaultActor.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.common.SOAPObject; +import org.opensaml.xml.schema.XSURI; + +/** + * SOAP 1.1 faultactor. + */ +public interface FaultActor extends SOAPObject, XSURI { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "faultactor"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(DEFAULT_ELEMENT_LOCAL_NAME); +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/FaultCode.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/FaultCode.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/FaultCode.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.common.SOAPObject; +import org.opensaml.ws.soap.util.SOAPConstants; +import org.opensaml.xml.schema.XSQName; + +/** + * SOAP 1.1 faultcode. + */ +public interface FaultCode extends SOAPObject, XSQName { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "faultcode"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(DEFAULT_ELEMENT_LOCAL_NAME); + + /** FaultCode value VersionMismatch. */ + public static final QName VERSION_MISMATCH = new QName(SOAPConstants.SOAP11_NS, "VersionMismatch", + SOAPConstants.SOAP11_PREFIX); + + /** FaultCode value MustUnderstand. */ + public static final QName MUST_UNDERSTAND = new QName(SOAPConstants.SOAP11_NS, "MustUnderstand", + SOAPConstants.SOAP11_PREFIX); + + /** FaultCode value Server. */ + public static final QName SERVER = new QName(SOAPConstants.SOAP11_NS, "Server", SOAPConstants.SOAP11_PREFIX); + + /** FaultCode value Client. */ + public static final QName CLIENT = new QName(SOAPConstants.SOAP11_NS, "Client", SOAPConstants.SOAP11_PREFIX); +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/FaultString.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/FaultString.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/FaultString.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.common.SOAPObject; +import org.opensaml.xml.schema.XSString; + +/** + * SOAP 1.1 faultstring. + */ +public interface FaultString extends SOAPObject, XSString { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "faultstring"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(DEFAULT_ELEMENT_LOCAL_NAME); +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Header.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Header.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/Header.java 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.common.SOAPObject; +import org.opensaml.ws.soap.util.SOAPConstants; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * SOAP 1.1 Header. + */ +public interface Header extends SOAPObject, ElementExtensibleXMLObject, AttributeExtensibleXMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Header"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SOAPConstants.SOAP11_NS, DEFAULT_ELEMENT_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "Header"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SOAPConstants.SOAP11_NS, TYPE_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/MustUnderstandBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/MustUnderstandBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/MustUnderstandBearing.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.util.SOAPConstants; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * Interface for element having a @soap11:mustUnderstand attribute. + */ +public interface MustUnderstandBearing { + + /** The soap11:@mustUnderstand attribute local name. */ + public static final String SOAP11_MUST_UNDERSTAND_ATTR_LOCAL_NAME = "mustUnderstand"; + + /** The soap11:@mustUnderstand qualified attribute name. */ + public static final QName SOAP11_MUST_UNDERSTAND_ATTR_NAME = + new QName(SOAPConstants.SOAP11_NS, SOAP11_MUST_UNDERSTAND_ATTR_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + + /** + * Get the attribute value. + * + * @return return the attribute vlue + */ + public Boolean isSOAP11MustUnderstand(); + + /** + * Get the attribute value. + * + * @return return the attribute vlue + */ + public XSBooleanValue isSOAP11MustUnderstandXSBoolean(); + + /** + * Set the attribute value. + * + * @param newMustUnderstand the new attribute value + */ + public void setSOAP11MustUnderstand(Boolean newMustUnderstand); + + /** + * Set the attribute value. + * + * @param newMustUnderstand the new attribute value + */ + public void setSOAP11MustUnderstand(XSBooleanValue newMustUnderstand); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/package.html 17 Aug 2012 15:09:09 -0000 1.1 @@ -0,0 +1,5 @@ + + +XMLObject interfaces for SOAP 1.1 elements. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/decoder/SOAP11Decoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/decoder/SOAP11Decoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/decoder/SOAP11Decoder.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,105 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.decoder ; + +import java.util.List; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.ws.message.handler.BaseHandlerChainAwareMessageDecoder; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.soap.soap11.Header; +import org.opensaml.ws.transport.InTransport; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.security.SecurityException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Basic SOAP 1.1 decoder. + */ +public class SOAP11Decoder extends BaseHandlerChainAwareMessageDecoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(SOAP11Decoder.class); + + /** Constructor. */ + public SOAP11Decoder() { + super(); + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public SOAP11Decoder(ParserPool pool) { + super(pool); + } + + /** {@inheritDoc} */ + protected void doDecode(MessageContext messageContext) throws MessageDecodingException { + + InTransport inTransport = messageContext.getInboundMessageTransport(); + + log.debug("Unmarshalling SOAP message"); + Envelope soapMessage = (Envelope) unmarshallMessage(inTransport.getIncomingStream()); + messageContext.setInboundMessage(soapMessage); + } + + + /** {@inheritDoc} */ + public void decode(MessageContext messageContext) throws MessageDecodingException, SecurityException { + super.decode(messageContext); + + // TODO enable once header checking support is completed + // checkUnderstoodSOAPHeaders(messageContext); + } + + /** + * Check that all headers which carry the soap11:mustUnderstand attribute + * and which are targeted to this SOAP node via the soap11:actor were understood by the + * decoder. + * + * @param messageContext the message context being processed + * + * @throws MessageDecodingException thrown if a SOAP header requires understanding by + * this node but was not understood + */ + private void checkUnderstoodSOAPHeaders(MessageContext messageContext) + throws MessageDecodingException { + + Envelope envelope = (Envelope) messageContext.getInboundMessage(); + Header soapHeader = envelope.getHeader(); + if (soapHeader == null) { + log.debug("SOAP Envelope contained no Header"); + return; + } + List headers = soapHeader.getUnknownXMLObjects(); + if (headers == null || headers.isEmpty()) { + log.debug("SOAP Envelope header list was either null or empty"); + return; + } + + for (XMLObject header : headers) { + //TODO + } + } + +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/decoder/http/HTTPSOAP11Decoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/decoder/http/HTTPSOAP11Decoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/decoder/http/HTTPSOAP11Decoder.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.decoder.http; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.ws.soap.soap11.decoder.SOAP11Decoder; +import org.opensaml.ws.transport.http.HTTPInTransport; +import org.opensaml.xml.parse.ParserPool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Basic SOAP 1.1 over decoder for HTTP transport. + */ +public class HTTPSOAP11Decoder extends SOAP11Decoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPSOAP11Decoder.class); + + /** Constructor. */ + public HTTPSOAP11Decoder() { + super(); + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public HTTPSOAP11Decoder(ParserPool pool) { + super(pool); + } + + /** {@inheritDoc} */ + protected void doDecode(MessageContext messageContext) throws MessageDecodingException { + + if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) { + log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport"); + throw new MessageDecodingException( + "Invalid inbound message transport type, this decoder only support HTTPInTransport"); + } + + HTTPInTransport inTransport = (HTTPInTransport) messageContext.getInboundMessageTransport(); + if (!inTransport.getHTTPMethod().equalsIgnoreCase("POST")) { + throw new MessageDecodingException("This message deocoder only supports the HTTP POST method"); + } + + super.doDecode(messageContext); + + } + +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/encoder/SOAP11Encoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/encoder/SOAP11Encoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/encoder/SOAP11Encoder.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,134 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.encoder; + +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.message.handler.BaseHandlerChainAwareMessageEncoder; +import org.opensaml.ws.soap.common.SOAPObjectBuilder; +import org.opensaml.ws.soap.soap11.Body; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.transport.OutTransport; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObjectBuilderFactory; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Element; + +/** + * Basic SOAP 1.1 encoder. + */ +public class SOAP11Encoder extends BaseHandlerChainAwareMessageEncoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(SOAP11Encoder.class); + + /** SOAP Envelope builder. */ + private SOAPObjectBuilder envBuilder; + + /** SOAP Body builder. */ + private SOAPObjectBuilder bodyBuilder; + + + /** Constructor. */ + @SuppressWarnings("unchecked") + public SOAP11Encoder() { + super(); + XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); + envBuilder = (SOAPObjectBuilder) builderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME); + bodyBuilder = (SOAPObjectBuilder) builderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public boolean providesMessageConfidentiality(MessageContext messageContext) throws MessageEncodingException { + return messageContext.getOutboundMessageTransport().isConfidential(); + } + + /** {@inheritDoc} */ + public boolean providesMessageIntegrity(MessageContext messageContext) throws MessageEncodingException { + return messageContext.getOutboundMessageTransport().isIntegrityProtected(); + } + + /** {@inheritDoc} */ + protected void prepareMessageContext(MessageContext messageContext) throws MessageEncodingException { + if (messageContext.getOutboundMessage() == null) { + messageContext.setOutboundMessage(buildSOAPEnvelope(messageContext)); + } + } + + /** {@inheritDoc} */ + protected void encodeToTransport(MessageContext messageContext) throws MessageEncodingException { + Element envelopeElem = marshallMessage(messageContext.getOutboundMessage()); + + preprocessTransport(messageContext); + + try { + OutTransport outTransport = messageContext.getOutboundMessageTransport(); + Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), "UTF-8"); + XMLHelper.writeNode(envelopeElem, out); + out.flush(); + } catch (UnsupportedEncodingException e) { + log.error("JVM does not support required UTF-8 encoding"); + throw new MessageEncodingException("JVM does not support required UTF-8 encoding"); + } catch (IOException e) { + log.error("Unable to write message content to outbound stream", e); + throw new MessageEncodingException("Unable to write message content to outbound stream", e); + } + } + + /** + * Perform any processing or fixup on the message context's outbound transport, prior to encoding the actual + * message. + * + *

+ * The default implementation does nothing. Subclasses should override to implement transport-specific + * behavior. + *

+ * + * @param messageContext the current message context being processed + * + * @throws MessageEncodingException thrown if there is a problem preprocessing the transport + */ + protected void preprocessTransport(MessageContext messageContext) throws MessageEncodingException { + } + + /** + * Builds the SOAP envelope and body skeleton to be encoded. + * + * @param messageContext the message context being processed + * + * @return the minimal SOAP message envelope skeleton + */ + protected Envelope buildSOAPEnvelope(MessageContext messageContext) { + log.debug("Building SOAP envelope"); + + Envelope envelope = envBuilder.buildObject(); + + Body body = bodyBuilder.buildObject(); + envelope.setBody(body); + + return envelope; + } + +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/encoder/http/HTTPSOAP11Encoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/encoder/http/HTTPSOAP11Encoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/encoder/http/HTTPSOAP11Encoder.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,120 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.encoder.http; + +import java.util.List; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.soap.soap11.Header; +import org.opensaml.ws.soap.soap11.encoder.SOAP11Encoder; +import org.opensaml.ws.transport.http.HTTPOutTransport; +import org.opensaml.ws.transport.http.HTTPTransportUtils; +import org.opensaml.ws.wsaddressing.Action; +import org.opensaml.xml.XMLObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Basic SOAP 1.1 encoder for HTTP transport. + */ +public class HTTPSOAP11Encoder extends SOAP11Encoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPSOAP11Encoder.class); + + + /** Constructor. */ + public HTTPSOAP11Encoder() { + super(); + } + + /** {@inheritDoc} */ + protected void doEncode(MessageContext messageContext) throws MessageEncodingException { + if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) { + log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + throw new MessageEncodingException( + "Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + } + + super.doEncode(messageContext); + } + + /** + *

+ * This implementation performs the following actions on the context's {@link HTTPOutTransport}: + *

    + *
  1. Adds the HTTP header: "Cache-control: no-cache, no-store"
  2. + *
  3. Adds the HTTP header: "Pragma: no-cache"
  4. + *
  5. Sets the character encoding to: "UTF-8"
  6. + *
  7. Sets the content type to: "text/xml"
  8. + *
  9. Sets the SOAPAction HTTP header the value returned by {@link #getSOAPAction(MessageContext)}, if + * that returns non-null.
  10. + *
+ *

+ * + *

+ * Subclasses should NOT set the SOAPAction HTTP header in this method. Instead, they should override + * the method {@link #getSOAPAction(MessageContext)}. + *

+ * + * @param messageContext the current message context being processed + * + * @throws MessageEncodingException thrown if there is a problem preprocessing the transport + */ + protected void preprocessTransport(MessageContext messageContext) throws MessageEncodingException { + HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport(); + HTTPTransportUtils.addNoCacheHeaders(outTransport); + HTTPTransportUtils.setUTF8Encoding(outTransport); + HTTPTransportUtils.setContentType(outTransport, "text/xml"); + + String soapAction = getSOAPAction(messageContext); + if (soapAction != null) { + outTransport.setHeader("SOAPAction", soapAction); + } else { + outTransport.setHeader("SOAPAction", ""); + } + } + + /** + * Determine the value of the SOAPAction HTTP header to send. + * + *

+ * The default behavior is to return the value of the SOAP Envelope's WS-Addressing Action header, + * if present. + *

+ * + * @param messageContext the current message context being processed + * @return a SOAPAction HTTP header URI value + */ + protected String getSOAPAction(MessageContext messageContext) { + Envelope env = (Envelope) messageContext.getOutboundMessage(); + Header header = env.getHeader(); + if (header == null) { + return null; + } + List objList = header.getUnknownXMLObjects(Action.ELEMENT_NAME); + if (objList == null || objList.isEmpty()) { + return null; + } else { + return ((Action)objList.get(0)).getValue(); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/BodyBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/BodyBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/BodyBuilder.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.common.SOAPObjectBuilder; +import org.opensaml.ws.soap.soap11.Body; +import org.opensaml.ws.soap.util.SOAPConstants; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * Builder of {@link org.opensaml.ws.soap.soap11.impl.BodyImpl} objects. + */ +public class BodyBuilder extends AbstractXMLObjectBuilder implements SOAPObjectBuilder { + + /** + * Creates an envelope object with the default SOAP 1.1 namespace, prefix and "Body" as the element local name. + * + * @return the build Envelope object + */ + public Body buildObject(){ + return buildObject(SOAPConstants.SOAP11_NS, Body.DEFAULT_ELEMENT_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + } + + /** {@inheritDoc} */ + public Body buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new BodyImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/BodyImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/BodyImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/BodyImpl.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.common.AbstractExtensibleSOAPObject; +import org.opensaml.ws.soap.soap11.Body; + +/** + * Concrete implemenation of {@link org.opensaml.ws.soap.soap11.Body}. + */ +public class BodyImpl extends AbstractExtensibleSOAPObject implements Body { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + protected BodyImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/BodyMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/BodyMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/BodyMarshaller.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.soap11.Body; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread-safe marshaller for {@link org.opensaml.ws.soap.soap11.Body}s. + */ +public class BodyMarshaller extends AbstractXMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Body body = (Body) xmlObject; + + Attr attribute; + for (Entry entry : body.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || body.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + // nothing to do, not element content + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/BodyUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/BodyUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/BodyUnmarshaller.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.soap11.Body; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.ws.soap.soap11.Body}s. + */ +public class BodyUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Body body = (Body) parentXMLObject; + body.getUnknownXMLObjects().add(childXMLObject); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Body body = (Body) xmlObject; + QName attribQName = XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute + .getPrefix()); + if (attribute.isId()) { + body.getUnknownAttributes().registerID(attribQName); + } + body.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + // do nothing, no child content + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/DetailBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/DetailBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/DetailBuilder.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.common.SOAPObjectBuilder; +import org.opensaml.ws.soap.soap11.Detail; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * Builder of {@link DetailImpl} objects. + */ +public class DetailBuilder extends AbstractXMLObjectBuilder implements SOAPObjectBuilder{ + + /** + * Creates an envelope object with the default SOAP 1.1 namespace, prefix and "Detail" as the element local name. + * + * @return the build Envelope object + */ + public Detail buildObject(){ + return buildObject(null, Detail.DEFAULT_ELEMENT_LOCAL_NAME, null); + } + + /** {@inheritDoc} */ + public Detail buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DetailImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/DetailImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/DetailImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/DetailImpl.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.common.AbstractExtensibleSOAPObject; +import org.opensaml.ws.soap.soap11.Detail; + +/** + * Concrete implementation of {@link org.opensaml.ws.soap.soap11.Detail}. + */ +public class DetailImpl extends AbstractExtensibleSOAPObject implements Detail { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + protected DetailImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/DetailMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/DetailMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/DetailMarshaller.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.soap11.Detail; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread-safe marshaller for {@link org.opensaml.ws.soap.soap11.Detail}s. + */ +public class DetailMarshaller extends AbstractXMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Detail detail = (Detail) xmlObject; + + Attr attribute; + for (Entry entry : detail.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || detail.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + // nothing to do, not element content + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/DetailUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/DetailUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/DetailUnmarshaller.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.soap11.Detail; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.ws.soap.soap11.Detail}s. + */ +public class DetailUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Detail detail = (Detail) parentXMLObject; + detail.getUnknownXMLObjects().add(childXMLObject); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Detail detail = (Detail) xmlObject; + QName attribQName = XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute + .getPrefix()); + if (attribute.isId()) { + detail.getUnknownAttributes().registerID(attribQName); + } + detail.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + // do nothing, no child content + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/EnvelopeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/EnvelopeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/EnvelopeBuilder.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.common.SOAPObjectBuilder; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.soap.util.SOAPConstants; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * Builder of {@link org.opensaml.ws.soap.soap11.impl.EnvelopeImpl} objects. + */ +public class EnvelopeBuilder extends AbstractXMLObjectBuilder implements SOAPObjectBuilder { + + /** + * Creates an envelope object with the default SOAP 1.1 namespace, prefix and "Envelope" as the element local name. + * + * @return the build Envelope object + */ + public Envelope buildObject(){ + return buildObject(SOAPConstants.SOAP11_NS, Envelope.DEFAULT_ELEMENT_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + } + + /** {@inheritDoc} */ + public Envelope buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EnvelopeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/EnvelopeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/EnvelopeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/EnvelopeImpl.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,82 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.soap.common.AbstractExtensibleSOAPObject; +import org.opensaml.ws.soap.soap11.Body; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.soap.soap11.Header; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.ws.soap.soap11.Envelope}. + */ +public class EnvelopeImpl extends AbstractExtensibleSOAPObject implements Envelope { + + /** SOAP header. */ + private Header header; + + /** SOAP body. */ + private Body body; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + protected EnvelopeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public Header getHeader() { + return header; + } + + /** {@inheritDoc} */ + public void setHeader(Header newHeader) { + header = prepareForAssignment(header, newHeader); + } + + /** {@inheritDoc} */ + public Body getBody() { + return body; + } + + /** {@inheritDoc} */ + public void setBody(Body newBody) { + body = prepareForAssignment(body, newBody); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.add(header); + children.add(body); + children.addAll(super.getOrderedChildren()); + + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/EnvelopeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/EnvelopeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/EnvelopeMarshaller.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.ws.soap.soap11.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread-safe marshaller for {@link org.opensaml.ws.soap.soap11.Envelope}s. + */ +public class EnvelopeMarshaller extends AbstractXMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Envelope envelope = (Envelope) xmlObject; + + Attr attribute; + for (Entry entry : envelope.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || envelope.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + // nothing to do, not element content + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/EnvelopeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/EnvelopeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/EnvelopeUnmarshaller.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.soap11.Body; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.soap.soap11.Header; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.ws.soap.soap11.Envelope}s. + */ +public class EnvelopeUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Envelope envelope = (Envelope) parentXMLObject; + + if (childXMLObject instanceof Header) { + envelope.setHeader((Header) childXMLObject); + } else if (childXMLObject instanceof Body) { + envelope.setBody((Body) childXMLObject); + } else { + envelope.getUnknownXMLObjects().add(childXMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Envelope envelope = (Envelope) xmlObject; + QName attribQName = XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute + .getPrefix()); + if (attribute.isId()) { + envelope.getUnknownAttributes().registerID(attribQName); + } + envelope.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + // do nothing, no child content + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultActorBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultActorBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultActorBuilder.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.common.SOAPObjectBuilder; +import org.opensaml.ws.soap.soap11.FaultActor; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * A builder of {@link org.opensaml.ws.soap.soap11.impl.FaultActorImpl} objects. + */ +public class FaultActorBuilder extends AbstractXMLObjectBuilder implements SOAPObjectBuilder { + + /** {@inheritDoc} */ + public FaultActor buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new FaultActorImpl(namespaceURI, localName, namespacePrefix); + } + + /** {@inheritDoc} */ + public FaultActor buildObject() { + return buildObject(null, FaultActor.DEFAULT_ELEMENT_LOCAL_NAME, null); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultActorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultActorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultActorImpl.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.soap11.FaultActor; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * Concrete implementation of {@link org.opensaml.ws.soap.soap11.FaultActor}. + */ +public class FaultActorImpl extends XSURIImpl implements FaultActor { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected FaultActorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultBuilder.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.common.SOAPObjectBuilder; +import org.opensaml.ws.soap.soap11.Fault; +import org.opensaml.ws.soap.util.SOAPConstants; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * Builder of {@link org.opensaml.ws.soap.soap11.impl.FaultImpl} objects. + */ +public class FaultBuilder extends AbstractXMLObjectBuilder implements SOAPObjectBuilder{ + + /** + * Creates an envelope object with the default SOAP 1.1 namespace, prefix and "Fault" as the element local name. + * + * @return the build Envelope object + */ + public Fault buildObject() { + return buildObject(SOAPConstants.SOAP11_NS, Fault.DEFAULT_ELEMENT_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + } + + /** {@inheritDoc} */ + public Fault buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new FaultImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultCodeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultCodeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultCodeBuilder.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.common.SOAPObjectBuilder; +import org.opensaml.ws.soap.soap11.FaultCode; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * Builder of {@link org.opensaml.ws.soap.soap11.impl.FaultCodeImpl} objects. + */ +public class FaultCodeBuilder extends AbstractXMLObjectBuilder implements SOAPObjectBuilder { + + /** {@inheritDoc} */ + public FaultCode buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new FaultCodeImpl(namespaceURI, localName, namespacePrefix); + } + + /** {@inheritDoc} */ + public FaultCode buildObject() { + return buildObject(null, FaultCode.DEFAULT_ELEMENT_LOCAL_NAME, null); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultCodeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultCodeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultCodeImpl.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.soap11.FaultCode; +import org.opensaml.xml.schema.impl.XSQNameImpl; + +/** + * Concrete implementation of {@link org.opensaml.ws.soap.soap11.FaultCode}. + */ +public class FaultCodeImpl extends XSQNameImpl implements FaultCode { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected FaultCodeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultImpl.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,111 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.soap.soap11.Detail; +import org.opensaml.ws.soap.soap11.Fault; +import org.opensaml.ws.soap.soap11.FaultActor; +import org.opensaml.ws.soap.soap11.FaultCode; +import org.opensaml.ws.soap.soap11.FaultString; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.validation.AbstractValidatingXMLObject; + +/** + * Concrete implemenation of {@link org.opensaml.ws.soap.soap11.Fault}. + */ +public class FaultImpl extends AbstractValidatingXMLObject implements Fault { + + /** Fault code. */ + private FaultCode faultCode; + + /** Fault message. */ + private FaultString message; + + /** Actor that faulted. */ + private FaultActor actor; + + /** Details of the fault. */ + private Detail detail; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + protected FaultImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public FaultCode getCode() { + return faultCode; + } + + /** {@inheritDoc} */ + public void setCode(FaultCode newFaultCode) { + faultCode = prepareForAssignment(faultCode, newFaultCode); + } + + /** {@inheritDoc} */ + public FaultString getMessage() { + return message; + } + + /** {@inheritDoc} */ + public void setMessage(FaultString newMessage) { + message = prepareForAssignment(message, newMessage); + } + + /** {@inheritDoc} */ + public FaultActor getActor() { + return actor; + } + + /** {@inheritDoc} */ + public void setActor(FaultActor newActor) { + actor = prepareForAssignment(actor, newActor); + } + + /** {@inheritDoc} */ + public Detail getDetail() { + return detail; + } + + /** {@inheritDoc} */ + public void setDetail(Detail newDetail) { + detail = prepareForAssignment(detail, newDetail); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.add(faultCode); + children.add(message); + children.add(actor); + children.add(detail); + + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultMarshaller.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe marshaller for {@link org.opensaml.ws.soap.soap11.Fault}s. + */ +public class FaultMarshaller extends AbstractXMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + // nothing to do, no attributes + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + // nothing to do, no content + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultStringBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultStringBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultStringBuilder.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.common.SOAPObjectBuilder; +import org.opensaml.ws.soap.soap11.FaultString; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * Builder of {@link org.opensaml.ws.soap.soap11.impl.FaultStringImpl} objects. + */ +public class FaultStringBuilder extends AbstractXMLObjectBuilder implements SOAPObjectBuilder { + + /** {@inheritDoc} */ + public FaultString buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new FaultStringImpl(namespaceURI, localName, namespacePrefix); + } + + /** {@inheritDoc} */ + public FaultString buildObject() { + return buildObject(null, FaultString.DEFAULT_ELEMENT_LOCAL_NAME, null); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultStringImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultStringImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultStringImpl.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.soap11.FaultString; +import org.opensaml.xml.schema.impl.XSStringImpl; + +/** + * Concrete implemenation of {@link org.opensaml.ws.soap.soap11.FaultString}. + */ +public class FaultStringImpl extends XSStringImpl implements FaultString { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected FaultStringImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/FaultUnmarshaller.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.soap11.Detail; +import org.opensaml.ws.soap.soap11.Fault; +import org.opensaml.ws.soap.soap11.FaultActor; +import org.opensaml.ws.soap.soap11.FaultCode; +import org.opensaml.ws.soap.soap11.FaultString; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSQName; +import org.opensaml.xml.schema.XSString; +import org.opensaml.xml.schema.XSURI; +import org.w3c.dom.Attr; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.ws.soap.soap11.Fault}s. + */ +public class FaultUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Fault fault = (Fault) parentXMLObject; + + if(childXMLObject instanceof XSQName){ + fault.setCode((FaultCode) childXMLObject); + }else if(childXMLObject instanceof XSString){ + fault.setMessage((FaultString) childXMLObject); + }else if(childXMLObject instanceof XSURI){ + fault.setActor((FaultActor) childXMLObject); + }else if(childXMLObject instanceof Detail){ + fault.setDetail((Detail) childXMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + // nothing to do, no attributes + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + //nothing to do, no element conent + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/HeaderBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/HeaderBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/HeaderBuilder.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.common.SOAPObjectBuilder; +import org.opensaml.ws.soap.soap11.Header; +import org.opensaml.ws.soap.util.SOAPConstants; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * Builder of {@link org.opensaml.ws.soap.soap11.impl.HeaderImpl} objects. + */ +public class HeaderBuilder extends AbstractXMLObjectBuilder
implements SOAPObjectBuilder
{ + + /** + * Creates an envelope object with the default SOAP 1.1 namespace, prefix and "Header" as the element local name. + * + * @return the build Envelope object + */ + public Header buildObject() { + return buildObject(SOAPConstants.SOAP11_NS, Header.DEFAULT_ELEMENT_LOCAL_NAME, SOAPConstants.SOAP11_PREFIX); + } + + /** {@inheritDoc} */ + public Header buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new HeaderImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/HeaderImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/HeaderImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/HeaderImpl.java 17 Aug 2012 15:09:08 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import org.opensaml.ws.soap.common.AbstractExtensibleSOAPObject; +import org.opensaml.ws.soap.soap11.Header; + +/** + * Concrete implementation of {@link org.opensaml.ws.soap.soap11.Header}. + */ +public class HeaderImpl extends AbstractExtensibleSOAPObject implements Header { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + protected HeaderImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/HeaderMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/HeaderMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/HeaderMarshaller.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.soap11.Header; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread-safe marshaller for {@link org.opensaml.ws.soap.soap11.Header}s. + */ +public class HeaderMarshaller extends AbstractXMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Header header = (Header) xmlObject; + + Attr attribute; + for (Entry entry : header.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || header.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + // nothing to do, not element content + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/HeaderUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/HeaderUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/HeaderUnmarshaller.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap11.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.soap11.Header; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.ws.soap.soap11.Header}s. + */ +public class HeaderUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Header header = (Header) parentXMLObject; + header.getUnknownXMLObjects().add(childXMLObject); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Header header = (Header) xmlObject; + QName attribQName = XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute + .getPrefix()); + if (attribute.isId()) { + header.getUnknownAttributes().registerID(attribQName); + } + header.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + // do nothing, no child content + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap11/impl/package.html 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,5 @@ + + +Provided implementations of the SOAP 1.1 XMLObject interfaces. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap12/EncodingStyleBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap12/EncodingStyleBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap12/EncodingStyleBearing.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap12; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.util.SOAPConstants; + +/** + * Interface for element having a @soap12:encodingStyle attribute. + */ +public interface EncodingStyleBearing { + + /** The soap12:@encodingStyle attribute local name. */ + public static final String SOAP12_ENCODING_STYLE_ATTR_LOCAL_NAME = "encodingStyle"; + + /** The soap12:@encodingStyle qualified attribute name. */ + public static final QName SOAP12_ENCODING_STYLE_ATTR_NAME = + new QName(SOAPConstants.SOAP12_NS, SOAP12_ENCODING_STYLE_ATTR_LOCAL_NAME, SOAPConstants.SOAP12_PREFIX); + + /** + * Get the attribute value. + * + * @return return the attribute value + */ + public String getSOAP12EncodingStyle(); + + /** + * Set the attribute value. + * + * @param newEncodingStyle the new attribute value + */ + public void setSOAP12EncodingStyle(String newEncodingStyle); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap12/MustUnderstandBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap12/MustUnderstandBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap12/MustUnderstandBearing.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap12; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.util.SOAPConstants; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * Interface for element having a @soap12:mustUnderstand attribute. + */ +public interface MustUnderstandBearing { + + /** The soap12:@mustUnderstand attribute local name. */ + public static final String SOAP12_MUST_UNDERSTAND_ATTR_LOCAL_NAME = "mustUnderstand"; + + /** The soap12:@mustUnderstand qualified attribute name. */ + public static final QName SOAP12_MUST_UNDERSTAND_ATTR_NAME = + new QName(SOAPConstants.SOAP12_NS, SOAP12_MUST_UNDERSTAND_ATTR_LOCAL_NAME, SOAPConstants.SOAP12_PREFIX); + + /** + * Get the attribute value. + * + * @return return the attribute value + */ + public Boolean isSOAP12MustUnderstand(); + + /** + * Get the attribute value. + * + * @return return the attribute value + */ + public XSBooleanValue isSOAP12MustUnderstandXSBoolean(); + + /** + * Set the attribute value. + * + * @param newMustUnderstand the new attribute value + */ + public void setSOAP12MustUnderstand(Boolean newMustUnderstand); + + /** + * Set the attribute value. + * + * @param newMustUnderstand the new attribute value + */ + public void setSOAP12MustUnderstand(XSBooleanValue newMustUnderstand); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap12/RelayBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap12/RelayBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap12/RelayBearing.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap12; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.util.SOAPConstants; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * Interface for element having a @soap12:relay attribute. + */ +public interface RelayBearing { + + /** The soap12:@relay attribute local name. */ + public static final String SOAP12_RELAY_ATTR_LOCAL_NAME = "relay"; + + /** The soap12:@relay qualified attribute name. */ + public static final QName SOAP12_RELAY_ATTR_NAME = + new QName(SOAPConstants.SOAP12_NS, SOAP12_RELAY_ATTR_LOCAL_NAME, SOAPConstants.SOAP12_PREFIX); + + /** + * Get the attribute value. + * + * @return return the attribute vlue + */ + public Boolean isSOAP12Relay(); + + /** + * Get the attribute value. + * + * @return return the attribute vlue + */ + public XSBooleanValue isSOAP12RelayXSBoolean(); + + /** + * Set the attribute value. + * + * @param newRelay the new attribute value + */ + public void setSOAP12Relay(Boolean newRelay); + + /** + * Set the attribute value. + * + * @param newRelay the new attribute value + */ + public void setSOAP12Relay(XSBooleanValue newRelay); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/soap12/RoleBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/soap12/RoleBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/soap12/RoleBearing.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.soap12; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.util.SOAPConstants; + +/** + * Interface for element having a @soap12:role attribute. + */ +public interface RoleBearing { + + /** The soap12:@role attribute local name. */ + public static final String SOAP12_ROLE_ATTR_LOCAL_NAME = "role"; + + /** The soap12:@role qualified attribute name. */ + public static final QName SOAP12_ROLE_ATTR_NAME = + new QName(SOAPConstants.SOAP12_NS, SOAP12_ROLE_ATTR_LOCAL_NAME, SOAPConstants.SOAP12_PREFIX); + + /** + * Get the attribute value. + * + * @return return the attribute vlue + */ + public String getSOAP12Role(); + + /** + * Set the attribute value. + * + * @param newRole the new attribute value + */ + public void setSOAP12Role(String newRole); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/util/SOAPConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/util/SOAPConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/util/SOAPConstants.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.util; + +/** SOAP Related Constants. */ +public class SOAPConstants { + + /** SOAP 1.1 namespace. */ + public static final String SOAP11_NS = "http://schemas.xmlsoap.org/soap/envelope/"; + + /** SOAP 1.1 prefix. */ + public static final String SOAP11_PREFIX = "soap11"; + + /** SOAP 1.2 namespace. */ + public static final String SOAP12_NS = "http://www.w3.org/2003/05/soap-envelope"; + + /** SOAP 1.2 prefix. */ + public static final String SOAP12_PREFIX = "soap12"; +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/soap/util/SOAPHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/util/SOAPHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/util/SOAPHelper.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,660 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.soap.util; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.soap.soap11.ActorBearing; +import org.opensaml.ws.soap.soap11.Detail; +import org.opensaml.ws.soap.soap11.EncodingStyleBearing; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.soap.soap11.Fault; +import org.opensaml.ws.soap.soap11.FaultActor; +import org.opensaml.ws.soap.soap11.FaultCode; +import org.opensaml.ws.soap.soap11.FaultString; +import org.opensaml.ws.soap.soap11.Header; +import org.opensaml.ws.soap.soap11.MustUnderstandBearing; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.XMLObjectBuilderFactory; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.LazyList; +import org.opensaml.xml.util.XMLHelper; + +/** + * Helper methods for working with SOAP. + */ +public final class SOAPHelper { + + /** + * Private constructor. + */ + private SOAPHelper() { + } + + /** + * Adds a soap11:mustUnderstand attribute to the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * @param mustUnderstand whether mustUnderstand is true or false + */ + public static void addSOAP11MustUnderstandAttribute(XMLObject soapObject, boolean mustUnderstand) { + if (soapObject instanceof MustUnderstandBearing) { + ((MustUnderstandBearing) soapObject).setSOAP11MustUnderstand(new XSBooleanValue(mustUnderstand, true)); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + ((AttributeExtensibleXMLObject) soapObject).getUnknownAttributes().put( + MustUnderstandBearing.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + new XSBooleanValue(mustUnderstand, true).toString()); + } else { + throw new IllegalArgumentException("Specified object was neither MustUnderBearing nor AttributeExtensible"); + } + } + + /** + * Get the soap11:mustUnderstand attribute from a given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * + * @return value of the mustUnderstand attribute, or false if not present + */ + public static boolean getSOAP11MustUnderstandAttribute(XMLObject soapObject) { + if (soapObject instanceof MustUnderstandBearing) { + XSBooleanValue value = ((MustUnderstandBearing) soapObject).isSOAP11MustUnderstandXSBoolean(); + if (value != null) { + return value.getValue(); + } + } + if (soapObject instanceof AttributeExtensibleXMLObject) { + String value = DatatypeHelper.safeTrimOrNullString(((AttributeExtensibleXMLObject) soapObject) + .getUnknownAttributes().get(MustUnderstandBearing.SOAP11_MUST_UNDERSTAND_ATTR_NAME)); + return DatatypeHelper.safeEquals("1", value); + } + return false; + } + + /** + * Adds a soap11:actor attribute to the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * @param actorURI the URI of the actor + */ + public static void addSOAP11ActorAttribute(XMLObject soapObject, String actorURI) { + if (soapObject instanceof ActorBearing) { + ((ActorBearing) soapObject).setSOAP11Actor(actorURI); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + ((AttributeExtensibleXMLObject) soapObject).getUnknownAttributes().put(ActorBearing.SOAP11_ACTOR_ATTR_NAME, + actorURI); + } else { + throw new IllegalArgumentException("Specified object was neither ActorBearing nor AttributeExtensible"); + } + } + + /** + * Gets the soap11:actor attribute from a given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * + * @return the value of the actor attribute, or null if not present + */ + public static String getSOAP11ActorAttribute(XMLObject soapObject) { + String value = null; + if (soapObject instanceof ActorBearing) { + value = DatatypeHelper.safeTrimOrNullString(((ActorBearing) soapObject).getSOAP11Actor()); + if (value != null) { + return value; + } + } + if (soapObject instanceof AttributeExtensibleXMLObject) { + value = DatatypeHelper.safeTrimOrNullString(((AttributeExtensibleXMLObject) soapObject) + .getUnknownAttributes().get(ActorBearing.SOAP11_ACTOR_ATTR_NAME)); + return value; + } + return null; + } + + /** + * Adds a single encoding style to the given SOAP object. If an existing soap11:encodingStyle attribute + * is present, the given style will be added to the existing list. + * + * @param soapObject the SOAP object to add the attribute to + * @param encodingStyle the encoding style to add + */ + public static void addSOAP11EncodingStyle(XMLObject soapObject, String encodingStyle) { + if (soapObject instanceof EncodingStyleBearing) { + EncodingStyleBearing esb = (EncodingStyleBearing) soapObject; + List list = esb.getSOAP11EncodingStyles(); + if (list == null) { + list = new LazyList(); + esb.setSOAP11EncodingStyles(list); + } + list.add(encodingStyle); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + AttributeMap am = ((AttributeExtensibleXMLObject) soapObject).getUnknownAttributes(); + String list = am.get(EncodingStyleBearing.SOAP11_ENCODING_STYLE_ATTR_NAME); + if (list == null) { + list = encodingStyle; + } else { + list = list + " " + encodingStyle; + } + am.put(EncodingStyleBearing.SOAP11_ENCODING_STYLE_ATTR_NAME, list); + } else { + throw new IllegalArgumentException( + "Specified object was neither EncodingStyleBearing nor AttributeExtensible"); + } + } + + /** + * Adds a soap11:encodingStyle attribute to the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * @param encodingStyles the list of encoding styles to add + */ + public static void addSOAP11EncodingStyles(XMLObject soapObject, List encodingStyles) { + if (soapObject instanceof EncodingStyleBearing) { + ((EncodingStyleBearing) soapObject).setSOAP11EncodingStyles(encodingStyles); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + ((AttributeExtensibleXMLObject) soapObject).getUnknownAttributes().put( + EncodingStyleBearing.SOAP11_ENCODING_STYLE_ATTR_NAME, + DatatypeHelper.listToStringValue(encodingStyles, " ")); + } else { + throw new IllegalArgumentException( + "Specified object was neither EncodingStyleBearing nor AttributeExtensible"); + } + } + + /** + * Gets the list value of the soap11:encodingStyle attribute from the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * + * @return the list of encoding styles, or null if not present + */ + public static List getSOAP11EncodingStyles(XMLObject soapObject) { + if (soapObject instanceof EncodingStyleBearing) { + List value = ((EncodingStyleBearing) soapObject).getSOAP11EncodingStyles(); + if (value != null) { + return value; + } + } + if (soapObject instanceof AttributeExtensibleXMLObject) { + String value = DatatypeHelper.safeTrimOrNullString(((AttributeExtensibleXMLObject) soapObject) + .getUnknownAttributes().get(EncodingStyleBearing.SOAP11_ENCODING_STYLE_ATTR_NAME)); + if (value != null) { + DatatypeHelper.stringToList(value, XMLHelper.LIST_DELIMITERS); + } + } + return null; + } + + /** + * Adds the soap12:encodingStyle attribute to the given soap object. + * + * @param soapObject object to which the encoding style attribute should be added + * @param style the encoding style + */ + public static void addSOAP12EncodingStyleAttribute(XMLObject soapObject, String style) { + if (soapObject instanceof org.opensaml.ws.soap.soap12.EncodingStyleBearing) { + ((org.opensaml.ws.soap.soap12.EncodingStyleBearing) soapObject).setSOAP12EncodingStyle(style); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + ((AttributeExtensibleXMLObject) soapObject).getUnknownAttributes().put( + org.opensaml.ws.soap.soap12.EncodingStyleBearing.SOAP12_ENCODING_STYLE_ATTR_NAME, style); + } else { + throw new IllegalArgumentException( + "Specified object was neither EncodingStyleBearing nor AttribtueExtensible"); + } + } + + /** + * Gets the soap12:encodingStyle. + * + * @param soapObject the SOAP object which may contain the encoding style + * + * @return the encoding style or null if it is not set on the object + */ + public static String getSOAP12EncodingStyleAttribute(XMLObject soapObject) { + String style = null; + if (soapObject instanceof org.opensaml.ws.soap.soap12.EncodingStyleBearing) { + style = ((org.opensaml.ws.soap.soap12.EncodingStyleBearing) soapObject).getSOAP12EncodingStyle(); + } + + if (style == null && soapObject instanceof AttributeExtensibleXMLObject) { + style = DatatypeHelper.safeTrimOrNullString(((AttributeExtensibleXMLObject) soapObject) + .getUnknownAttributes().get( + org.opensaml.ws.soap.soap12.EncodingStyleBearing.SOAP12_ENCODING_STYLE_ATTR_NAME)); + } + + return style; + } + + /** + * Adds a soap12:mustUnderstand attribute to the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * @param mustUnderstand whether mustUnderstand is true or false + */ + public static void addSOAP12MustUnderstandAttribute(XMLObject soapObject, boolean mustUnderstand) { + if (soapObject instanceof org.opensaml.ws.soap.soap12.MustUnderstandBearing) { + ((org.opensaml.ws.soap.soap12.MustUnderstandBearing) soapObject) + .setSOAP12MustUnderstand(new XSBooleanValue(mustUnderstand, false)); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + ((AttributeExtensibleXMLObject) soapObject).getUnknownAttributes().put( + org.opensaml.ws.soap.soap12.MustUnderstandBearing.SOAP12_MUST_UNDERSTAND_ATTR_NAME, + new XSBooleanValue(mustUnderstand, false).toString()); + } else { + throw new IllegalArgumentException("Specified object was neither MustUnderstandBearing nor AttributeExtensible"); + } + } + + /** + * Get the soap12:mustUnderstand attribute from a given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * + * @return value of the mustUnderstand attribute, or false if not present + */ + public static boolean getSOAP12MustUnderstandAttribute(XMLObject soapObject) { + if (soapObject instanceof org.opensaml.ws.soap.soap12.MustUnderstandBearing) { + XSBooleanValue value = ((org.opensaml.ws.soap.soap12.MustUnderstandBearing) soapObject) + .isSOAP12MustUnderstandXSBoolean(); + if (value != null) { + return value.getValue(); + } + } + if (soapObject instanceof AttributeExtensibleXMLObject) { + String value = DatatypeHelper.safeTrimOrNullString(((AttributeExtensibleXMLObject) soapObject) + .getUnknownAttributes().get( + org.opensaml.ws.soap.soap12.MustUnderstandBearing.SOAP12_MUST_UNDERSTAND_ATTR_NAME)); + return DatatypeHelper.safeEquals("1", value) || DatatypeHelper.safeEquals("true", value); + } + return false; + } + + /** + * Adds a soap12:relay attribute to the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * @param relay whether relay is true or false + */ + public static void addSOAP12RelayAttribute(XMLObject soapObject, boolean relay) { + if (soapObject instanceof org.opensaml.ws.soap.soap12.RelayBearing) { + ((org.opensaml.ws.soap.soap12.RelayBearing) soapObject).setSOAP12Relay(new XSBooleanValue(relay, false)); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + ((AttributeExtensibleXMLObject) soapObject).getUnknownAttributes().put( + org.opensaml.ws.soap.soap12.RelayBearing.SOAP12_RELAY_ATTR_NAME, + new XSBooleanValue(relay, false).toString()); + } else { + throw new IllegalArgumentException("Specified object was neither RelyBearing nor AttributeExtensible"); + } + } + + /** + * Get the soap12:relay attribute from a given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * + * @return value of the relay attribute, or false if not present + */ + public static boolean getSOAP12RelayAttribute(XMLObject soapObject) { + if (soapObject instanceof org.opensaml.ws.soap.soap12.RelayBearing) { + XSBooleanValue value = ((org.opensaml.ws.soap.soap12.RelayBearing) soapObject).isSOAP12RelayXSBoolean(); + if (value != null) { + return value.getValue(); + } + } + if (soapObject instanceof AttributeExtensibleXMLObject) { + String value = DatatypeHelper.safeTrimOrNullString(((AttributeExtensibleXMLObject) soapObject) + .getUnknownAttributes().get(org.opensaml.ws.soap.soap12.RelayBearing.SOAP12_RELAY_ATTR_LOCAL_NAME)); + return DatatypeHelper.safeEquals("1", value) || DatatypeHelper.safeEquals("true", value); + } + return false; + } + + /** + * Adds the soap12:role attribute to the given soap object. + * + * @param soapObject object to which the rol attribute should be added + * @param role the role + */ + public static void addSOAP12RoleAttribute(XMLObject soapObject, String role) { + if (soapObject instanceof org.opensaml.ws.soap.soap12.RoleBearing) { + ((org.opensaml.ws.soap.soap12.RoleBearing) soapObject).setSOAP12Role(role); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + ((AttributeExtensibleXMLObject) soapObject).getUnknownAttributes().put( + org.opensaml.ws.soap.soap12.RoleBearing.SOAP12_ROLE_ATTR_NAME, role); + } else { + throw new IllegalArgumentException( + "Specified object was neither RoleBearing nor AttribtueExtensible"); + } + } + + /** + * Gets the soap12:role. + * + * @param soapObject the SOAP object which may contain the role + * + * @return the role or null if it is not set on the object + */ + public static String getSOAP12RoleAttribute(XMLObject soapObject) { + String role = null; + if (soapObject instanceof org.opensaml.ws.soap.soap12.RoleBearing) { + role = ((org.opensaml.ws.soap.soap12.RoleBearing) soapObject).getSOAP12Role(); + } + + if (role == null && soapObject instanceof AttributeExtensibleXMLObject) { + role = DatatypeHelper.safeTrimOrNullString(((AttributeExtensibleXMLObject) soapObject) + .getUnknownAttributes().get( + org.opensaml.ws.soap.soap12.RoleBearing.SOAP12_ROLE_ATTR_LOCAL_NAME)); + } + + return role; + } + + /** + * Adds a soap11:actor attribute to the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * @param actorURI the URI of the actor + * + * @deprecated use instead {@link #addSOAP11ActorAttribute(XMLObject, String)}. + */ + public static void addActorAttribute(XMLObject soapObject, String actorURI) { + addSOAP11ActorAttribute(soapObject, actorURI); + } + + /** + * Adds a single encoding style to the given SOAP object. If an existing soap11:encodingStyle attribute + * is present, the given style will be added to the existing list. + * + * @param soapObject the SOAP object to add the attribute to + * @param encodingStyle the encoding style to add + * + * @deprecated use instead {@link #addSOAP11EncodingStyle(XMLObject, String)}. + */ + public static void addEncodingStyle(XMLObject soapObject, String encodingStyle) { + addSOAP11EncodingStyle(soapObject, encodingStyle); + } + + /** + * Adds a soap11:encodingStyle attribute to the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * @param encodingStyles the list of encoding styles to add + * + * @deprecated use instead {@link #addSOAP11EncodingStyles(XMLObject, List)}. + */ + public static void addEncodingStyles(XMLObject soapObject, List encodingStyles) { + addSOAP11EncodingStyles(soapObject, encodingStyles); + } + + /** + * Adds a soap11:mustUnderstand attribute to the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * @param mustUnderstand whether mustUnderstand is true or false + * + * @deprecated use instead {@link #addSOAP11MustUnderstandAttribute(XMLObject, boolean)}. + */ + public static void addMustUnderstandAttribute(XMLObject soapObject, boolean mustUnderstand) { + addSOAP11MustUnderstandAttribute(soapObject, mustUnderstand); + } + + /** + * Add a header block to the SOAP envelope contained within the specified message context's + * {@link MessageContext#getOutboundMessage()}. + * + * @param messageContext the message context being processed + * @param headerBlock the header block to add + */ + public static void addHeaderBlock(MessageContext messageContext, XMLObject headerBlock) { + XMLObject outboundEnvelope = messageContext.getOutboundMessage(); + if (outboundEnvelope == null) { + throw new IllegalArgumentException("Message context does not contain a SOAP envelope"); + } + + // SOAP 1.1 Envelope + if (outboundEnvelope instanceof Envelope) { + addSOAP11HeaderBlock((Envelope) outboundEnvelope, headerBlock); + } + + //TODO SOAP 1.2 support when object providers are implemented + + } + + /** + * Add a header to the SOAP 1.1 Envelope. + * + * @param envelope the SOAP 1.1 envelope to process + * @param headerBlock the header to add + */ + public static void addSOAP11HeaderBlock(Envelope envelope, XMLObject headerBlock) { + Header envelopeHeader = envelope.getHeader(); + if (envelopeHeader == null) { + envelopeHeader = (Header) Configuration.getBuilderFactory().getBuilder(Header.DEFAULT_ELEMENT_NAME) + .buildObject(Header.DEFAULT_ELEMENT_NAME); + envelope.setHeader(envelopeHeader); + } + + envelopeHeader.getUnknownXMLObjects().add(headerBlock); + } + + /** + * Get a header block from the SOAP envelope contained within the specified message context's + * {@link MessageContext#getInboundMessage()}. + * + * @param msgContext the message context being processed + * @param headerName the name of the header block to return + * @param targetNodes the explicitly specified SOAP node actors (1.1) or roles (1.2) for which the header is desired + * @param isFinalDestination true specifies that headers targeted for message final destination should be returned, + * false means they should not be returned + * @return the list of matching header blocks + */ + public static List getInboundHeaderBlock(MessageContext msgContext, QName headerName, + Set targetNodes, boolean isFinalDestination) { + XMLObject inboundEnvelope = msgContext.getInboundMessage(); + if (inboundEnvelope == null) { + throw new IllegalArgumentException("Message context does not contain an inbound SOAP envelope"); + } + + // SOAP 1.1 Envelope + if (inboundEnvelope instanceof Envelope) { + return getSOAP11HeaderBlock((Envelope) inboundEnvelope, headerName, targetNodes, isFinalDestination); + } + + //TODO SOAP 1.2 support when object providers are implemented + return Collections.emptyList(); + } + + /** + * Get a header block from the SOAP envelope contained within the specified message context's + * {@link MessageContext#getOutboundMessage()}. + * + * @param msgContext the message context being processed + * @param headerName the name of the header block to return + * @param targetNodes the explicitly specified SOAP node actors (1.1) or roles (1.2) for which the header is desired + * @param isFinalDestination true specifies that headers targeted for message final destination should be returned, + * false specifies they should not be returned + * @return the list of matching header blocks + */ + public static List getOutboundHeaderBlock(MessageContext msgContext, QName headerName, + Set targetNodes, boolean isFinalDestination) { + XMLObject outboundEnvelope = msgContext.getOutboundMessage(); + if (outboundEnvelope == null) { + throw new IllegalArgumentException("Message context does not contain an outbound SOAP envelope"); + } + + // SOAP 1.1 Envelope + if (outboundEnvelope instanceof Envelope) { + return getSOAP11HeaderBlock((Envelope) outboundEnvelope, headerName, targetNodes, isFinalDestination); + } + + //TODO SOAP 1.2 support when object providers are implemented + return Collections.emptyList(); + } + + /** + * Get a header block from the SOAP 1.1 envelope. + * + * @param envelope the SOAP 1.1 envelope to process + * @param headerName the name of the header block to return + * @param targetNodes the explicitly specified SOAP node actors for which the header is desired + * @param isFinalDestination true specifies that headers targeted for message final destination should be returned, + * false specifies they should not be returned + * @return the list of matching header blocks + */ + public static List getSOAP11HeaderBlock(Envelope envelope, QName headerName, Set targetNodes, + boolean isFinalDestination) { + Header envelopeHeader = envelope.getHeader(); + if (envelopeHeader == null) { + return Collections.emptyList(); + } + ArrayList headers = new ArrayList(); + for (XMLObject header : envelopeHeader.getUnknownXMLObjects(headerName)) { + if (isSOAP11HeaderTargetedToNode(header, targetNodes, isFinalDestination)) { + headers.add(header); + } + } + + return headers; + } + + /** + * Evaluate whether the specified header block is targeted to a SOAP 1.1 node given the specified + * parameters. + * + * @param header the header to evaluate + * @param nodeActors the explicitly specified node actors for which the header is desired + * @param isFinalDestination true specifies that headers targeted for message final destination should be returned, + * false specifies they should not be returned + * @return the list of matching header blocks + */ + public static boolean isSOAP11HeaderTargetedToNode(XMLObject header, Set nodeActors, + boolean isFinalDestination) { + String headerActor = getSOAP11ActorAttribute(header); + if (headerActor == null) { + if (isFinalDestination) { + return true; + } + } else if (ActorBearing.SOAP11_ACTOR_NEXT.equals(headerActor)) { + return true; + } else if (nodeActors != null && nodeActors.contains(headerActor)) { + return true; + } + return false; + } + + /** + * Determine whether the inbound message represented by the message context + * contains a SOAP Envelope. + * + * @param messageContext the current message context + * @return true if the inbound message contains a SOAP Envelope, false otherwise + */ + public static boolean isInboundSOAPMessage(MessageContext messageContext) { + XMLObject inboundMessage = messageContext.getInboundMessage(); + if (inboundMessage == null) { + return false; + } + // SOAP 1.1 Envelope + if (inboundMessage instanceof Envelope) { + return true; + } + //TODO SOAP 1.2 support when object providers are implemented + return false; + } + + /** + * Build a SOAP 1.1. Fault element. + * + * @param faultCode the 'faultcode' QName (required) + * @param faultString the 'faultstring' value (required) + * @param faultActor the 'faultactor' value (may be null) + * @param detailChildren the 'detail' child elements + * @param detailAttributes the 'detail' element attributes + * @return the new Fault element object + */ + public static Fault buildSOAP11Fault(QName faultCode, String faultString, String faultActor, + List detailChildren, Map detailAttributes) { + if (faultCode == null) { + throw new IllegalArgumentException("Argument for 'faultcode' may not be null"); + } + if (faultString == null) { + throw new IllegalArgumentException("Argument for 'faultstring' may not be null"); + } + + XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); + + Fault faultObj = (Fault) builderFactory.getBuilder(Fault.DEFAULT_ELEMENT_NAME) + .buildObject(Fault.DEFAULT_ELEMENT_NAME); + FaultCode faultCodeObj = (FaultCode) builderFactory.getBuilder(FaultCode.DEFAULT_ELEMENT_NAME) + .buildObject(FaultCode.DEFAULT_ELEMENT_NAME); + FaultString faultStringObj = (FaultString) builderFactory.getBuilder(FaultString.DEFAULT_ELEMENT_NAME) + .buildObject(FaultString.DEFAULT_ELEMENT_NAME); + + faultCodeObj.setValue(faultCode); + faultObj.setCode(faultCodeObj); + + faultStringObj.setValue(faultString); + faultObj.setMessage(faultStringObj); + + if (faultActor != null) { + FaultActor faultActorObj = (FaultActor) builderFactory.getBuilder(FaultActor.DEFAULT_ELEMENT_NAME) + .buildObject(FaultActor.DEFAULT_ELEMENT_NAME); + faultActorObj.setValue(faultActor); + faultObj.setActor(faultActorObj); + } + + Detail detailObj = null; + if (detailChildren != null && !detailChildren.isEmpty()) { + detailObj = (Detail) builderFactory.getBuilder(Detail.DEFAULT_ELEMENT_NAME) + .buildObject(Detail.DEFAULT_ELEMENT_NAME); + for (XMLObject xo : detailChildren) { + if (xo != null) { + detailObj.getUnknownXMLObjects().add(xo); + } + } + } + if (detailAttributes != null && !detailAttributes.isEmpty()) { + if (detailObj == null) { + detailObj = (Detail) builderFactory.getBuilder(Detail.DEFAULT_ELEMENT_NAME) + .buildObject(Detail.DEFAULT_ELEMENT_NAME); + } + for (Entry entry : detailAttributes.entrySet()) { + if (entry.getKey() != null && entry.getValue() != null) { + detailObj.getUnknownAttributes().put(entry.getKey(), entry.getValue()); + } + } + } + if (detailObj != null && + (!detailObj.getUnknownXMLObjects().isEmpty() || !detailObj.getUnknownAttributes().isEmpty())) { + faultObj.setDetail(detailObj); + } + + return faultObj; + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/soap/util/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/soap/util/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/soap/util/package.html 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,5 @@ + + +General utility classes. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/transport/BaseTransport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/BaseTransport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/BaseTransport.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,125 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport; + +import java.util.HashMap; +import java.util.Map; + +import org.opensaml.xml.security.credential.Credential; + +/** + * Base abstract class for a {@link Transport} that provides local storage for all transport properties. + */ +public abstract class BaseTransport implements Transport { + + /** Local credential. */ + private Credential localCredential; + + /** Peer credential. */ + private Credential peerCredential; + + /** Transport attributes. */ + private Map attributes; + + /** Character encoding. */ + private String characterEncoding; + + /** Authenticated flag. */ + private boolean authenticated; + + /** Confidential flag. */ + private boolean confidential; + + /** Integrity-protected flag. */ + private boolean integrityProtected; + + /** Constructor. */ + public BaseTransport() { + attributes = new HashMap(); + } + + /** {@inheritDoc} */ + public Object getAttribute(String name) { + return attributes.get(name); + } + + /** {@inheritDoc} */ + public String getCharacterEncoding() { + return characterEncoding; + } + + /** {@inheritDoc} */ + public Credential getLocalCredential() { + return localCredential; + } + + /** {@inheritDoc} */ + public Credential getPeerCredential() { + return peerCredential; + } + + /** {@inheritDoc} */ + public boolean isAuthenticated() { + return authenticated; + } + + /** {@inheritDoc} */ + public boolean isConfidential() { + return confidential; + } + + /** {@inheritDoc} */ + public boolean isIntegrityProtected() { + return integrityProtected; + } + + /** {@inheritDoc} */ + public void setAuthenticated(boolean isAuthenticated) { + authenticated = isAuthenticated; + } + + /** {@inheritDoc} */ + public void setConfidential(boolean isConfidential) { + confidential = isConfidential; + } + + /** {@inheritDoc} */ + public void setIntegrityProtected(boolean isIntegrityProtected) { + integrityProtected = isIntegrityProtected; + } + + /** + * Set an attribute value. + * + * @param name attribute name + * @param value attribute value + */ + protected void setAttribute(String name, Object value) { + attributes.put(name, value); + } + + /** + * Set the character encoding. + * + * @param encoding the character encoding + */ + protected void setCharacterEncoding(String encoding) { + characterEncoding = encoding; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/transport/InTransport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/InTransport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/InTransport.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport; + +import java.io.InputStream; + +/** + * Represents an inbound transport, that is the transport used to receive information. + */ +public interface InTransport extends Transport { + + /** + * Gets the incoming stream from the peer. + * + * @return incoming stream from the peer + */ + public InputStream getIncomingStream(); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/transport/InputStreamInTransportAdapter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/InputStreamInTransportAdapter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/InputStreamInTransportAdapter.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport; + +import java.io.InputStream; + +/** + * Adapter that allows a raw {@link InputStream} to be used as an {@link InTransport}. + */ +public class InputStreamInTransportAdapter extends BaseTransport implements InTransport { + + /** The wrapped InputStream. */ + private InputStream inputStream; + + /** + * Constructor. + * + * @param stream the input stream to adapt + */ + public InputStreamInTransportAdapter(InputStream stream) { + super(); + inputStream = stream; + } + + /** {@inheritDoc} */ + public InputStream getIncomingStream() { + return inputStream; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/transport/OutTransport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/OutTransport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/OutTransport.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport; + +import java.io.OutputStream; + +/** + * Represents an outbound transport, that is the transport used to send information. + */ +public interface OutTransport extends Transport { + + /** + * Sets a transport-specific attribute. + * + * @param name attribute name + * @param value attribute value + */ + public void setAttribute(String name, Object value); + + /** + * Sets the character encoding of the transport. + * + * @param encoding character encoding of the transport + */ + public void setCharacterEncoding(String encoding); + + /** + * Gets the outgoing data stream to the peer. + * + * @return outgoing data stream to the peer + */ + public OutputStream getOutgoingStream(); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/transport/OutputStreamOutTransportAdapter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/OutputStreamOutTransportAdapter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/OutputStreamOutTransportAdapter.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport; + +import java.io.OutputStream; + +/** + * Adapter that allows a raw {@link OutputStream} to be used as an {@link OutTransport}. + */ +public class OutputStreamOutTransportAdapter extends BaseTransport implements OutTransport { + + /** The wrapped output stream. */ + private OutputStream outputStream; + + /** + * Constructor. + * + * @param stream the output stream to adapt + */ + public OutputStreamOutTransportAdapter(OutputStream stream) { + outputStream = stream; + } + + /** {@inheritDoc} */ + public OutputStream getOutgoingStream() { + return outputStream; + } + + /** {@inheritDoc} */ + public void setAttribute(String name, Object value) { + super.setAttribute(name, value); + } + + /** {@inheritDoc} */ + public void setCharacterEncoding(String encoding) { + super.setCharacterEncoding(encoding); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/transport/Transport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/Transport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/Transport.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,99 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport; + +import org.opensaml.xml.security.credential.Credential; + +/** + * Base interface for inbound and outbound transports. + */ +public interface Transport { + + /** + * Gets a transport-specific attribute. + * + * @param name name of the attribute + * + * @return attribute value + */ + public Object getAttribute(String name); + + /** + * Gets the character encoding of the transport. + * + * @return character encoding of the transport + */ + public String getCharacterEncoding(); + + /** + * Gets the local credential used to authenticate to the peer. + * + * @return local credential used to authenticate to the peer + */ + public Credential getLocalCredential(); + + /** + * Gets the credential offered by the peer to authenticate itself. + * + * @return credential offered by the peer to authenticate itself + */ + public Credential getPeerCredential(); + + /** + * Gets whether the peer is authenticated. + * + * @return whether the peer is authenticated + */ + public boolean isAuthenticated(); + + /** + * Sets whether the peer is authenticated. + * + * @param isAuthenticated whether the peer is authenticated + */ + public void setAuthenticated(boolean isAuthenticated); + + /** + * Gets whether the transport represents a confidential connection (e.g. an SSL connection). + * + * @return whether the transport represents a confidential connection + */ + public boolean isConfidential(); + + /** + * Sets whether the transport represents a confidential connection. + * + * @param isConfidential whether the transport represents a confidential connection + */ + public void setConfidential(boolean isConfidential); + + /** + * Gets whether the transport represents a connection that protects the integrity of transported content. + * + * @return whether the transport represents a connection that protects the integrity of transported content + */ + public boolean isIntegrityProtected(); + + /** + * Sets whether the transport represents a connection that protects the integrity of transported content. + * + * @param isIntegrityProtected whether the transport represents a connection that protects the integrity of + * transported content + */ + public void setIntegrityProtected(boolean isIntegrityProtected); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/transport/TransportException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/TransportException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/TransportException.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport; + +import org.opensaml.ws.WSException; + +/** + * Base exception for transport-related errors. + */ +public class TransportException extends WSException { + + /** Serial version UID. */ + private static final long serialVersionUID = -3982638571562100128L; + + /** + * Constructor. + */ + public TransportException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public TransportException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public TransportException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public TransportException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/transport/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/package.html 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,5 @@ + + +Interfaces to the various transports (HTTP, SMTP, TCP, etc.) that may be used to receive/send messages. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/transport/http/HTTPInTransport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/http/HTTPInTransport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/http/HTTPInTransport.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport.http; + +import org.opensaml.ws.transport.InTransport; + +/** + * HTTP-based inbound transport. + * + * The stream returned by {@link InTransport#getIncomingStream()} represents the body of the HTTP message. + */ +public interface HTTPInTransport extends InTransport, HTTPTransport { + + /** + * Gets the IP address of the peer. + * + * @return IP address of the peer + */ + public String getPeerAddress(); + + /** + * Gets the domain name of the peer. + * + * @return domain name of the peer + */ + public String getPeerDomainName(); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/transport/http/HTTPOutTransport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/http/HTTPOutTransport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/http/HTTPOutTransport.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport.http; + +import org.opensaml.ws.transport.OutTransport; + +/** + * HTTP-based outbound transport. + */ +public interface HTTPOutTransport extends OutTransport, HTTPTransport { + + /** + * Sets the HTTP version to use for outgoing messages. + * + * @param version HTTP version to use for outgoing messages + */ + public void setVersion(HTTP_VERSION version); + + /** + * Sets the given header with the given value. + * + * @param name header name + * @param value header value + */ + public void setHeader(String name, String value); + + /** + * Sets the given parameter with the given value. + * + * @param name parameter name + * @param value parameter value + */ + public void addParameter(String name, String value); + + /** + * Sets the status code for this transport. + * + * @param code status code for this transport + */ + public void setStatusCode(int code); + + /** + * Sends an HTTP 3XX redirect message back to the client. + * + * @param location location to redirect the client to + */ + public void sendRedirect(String location); +} Index: 3rdParty_sources/openws/org/opensaml/ws/transport/http/HTTPTransport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/http/HTTPTransport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/http/HTTPTransport.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport.http; + +import java.util.List; + +import org.opensaml.ws.transport.Transport; + +/** + * An HTTP-based transport. + */ +public interface HTTPTransport extends Transport { + + /** HTTP version identifier. */ + public static enum HTTP_VERSION { + /** HTTP version 1.0. */ + HTTP1_0, + + /** HTTP version 1.1. */ + HTTP1_1, + }; + + /** + * Gets the first value of the header with the given name. + * + * @param name header name + * + * @return first value of the header with the given name, or null + */ + public String getHeaderValue(String name); + + /** + * Gets the HTTP method (POST, GET, etc) used. + * + * @return HTTP method used + */ + public String getHTTPMethod(); + + /** + * Gets the status code of the request. + * + * @return status code of the request + */ + public int getStatusCode(); + + /** + * Gets the first value of the named parameter. If the request is GET, this is a decoded URL parameter. + * If the request is POST-based, it is a parameter from the POST body. + * + * @param name parameter name + * + * @return parameter value + */ + public String getParameterValue(String name); + + /** + * Gets the values of the named parameter. If the request is GET, this is a decoded URL parameter. + * If the request is POST-based, it is a parameter from the POST body. + * + * @param name parameter name + * + * @return parameter values + */ + public List getParameterValues(String name); + + /** + * Gets the HTTP version used to receive the message. + * + * @return HTTP version used to receive the message + */ + public HTTP_VERSION getVersion(); +} Index: 3rdParty_sources/openws/org/opensaml/ws/transport/http/HTTPTransportUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/http/HTTPTransportUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/http/HTTPTransportUtils.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,119 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport.http; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; + +/** + * Utilities for working with HTTP transports. + */ +public class HTTPTransportUtils { + + /** Constructor. */ + protected HTTPTransportUtils() { + } + + /** + * Adds Cache-Control and Pragma headers meant to disable caching. + * + * @param transport transport to add headers to + */ + public static void addNoCacheHeaders(HTTPOutTransport transport) { + transport.setHeader("Cache-control", "no-cache, no-store"); + transport.setHeader("Pragma", "no-cache"); + } + + /** + * Sets the character encoding of the transport to UTF-8. + * + * @param transport transport to set character encoding type + */ + public static void setUTF8Encoding(HTTPOutTransport transport) { + transport.setCharacterEncoding("UTF-8"); + } + + /** + * Sets the MIME content type of the transport. + * + * @param transport the transport to set content type on + * @param contentType the content type to set + */ + public static void setContentType(HTTPOutTransport transport, String contentType) { + transport.setHeader("Content-Type", contentType); + } + + /** + * URL Decode the given string. + * + * @param value the string to decode + * @return the decoded string + */ + public static String urlDecode(String value) { + try { + return URLDecoder.decode(value, "UTF-8"); + } catch (UnsupportedEncodingException e) { + // UTF-8 encoding is required to be supported by all JVMs + return null; + } + } + + /** + * URL Encode the given string. + * + * @param value the string to encode + * @return the encoded string + */ + public static String urlEncode(String value) { + try { + return URLEncoder.encode(value, "UTF-8"); + } catch (UnsupportedEncodingException e) { + // UTF-8 encoding is required to be supported by all JVMs + return null; + } + } + + /** + * Get the first raw (i.e. non URL-decoded) query string component with the specified parameter name. + * + * The component will be returned as a string in the form 'paramName=paramValue' (minus the quotes). + * + * @param queryString the raw HTTP URL query string + * @param paramName the name of the parameter to find + * @return the found component, or null if not found + */ + public static String getRawQueryStringParameter(String queryString, String paramName) { + if (queryString == null) { + return null; + } + + String paramPrefix = paramName + "="; + int start = queryString.indexOf(paramPrefix); + if (start == -1) { + return null; + } + + int end = queryString.indexOf('&', start); + if (end == -1) { + return queryString.substring(start); + } else { + return queryString.substring(start, end); + } + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/transport/http/HttpServletRequestAdapter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/http/HttpServletRequestAdapter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/http/HttpServletRequestAdapter.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,202 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport.http; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.opensaml.ws.security.ServletRequestX509CredentialAdapter; +import org.opensaml.xml.security.credential.Credential; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Adapts an {@link HttpServletRequest} to an {@link HTTPInTransport}. + */ +public class HttpServletRequestAdapter implements HTTPInTransport { + + /** Adapted servlet request. */ + private HttpServletRequest httpServletRequest; + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HttpServletRequestAdapter.class); + + /** Whether the peer endpoint has been authenticated. */ + private boolean peerAuthenticated; + + /** Storage for peer credential adapted from HTTP servlet request. */ + private Credential peerCredential; + + /** + * Constructor. + * + * @param request servlet request to adap + */ + public HttpServletRequestAdapter(HttpServletRequest request) { + httpServletRequest = request; + } + + /** {@inheritDoc} */ + public Object getAttribute(String name) { + return httpServletRequest.getAttribute(name); + } + + /** {@inheritDoc} */ + public String getCharacterEncoding() { + return httpServletRequest.getCharacterEncoding(); + } + + /** {@inheritDoc} */ + public String getHeaderValue(String name) { + // This appears to be necessary for at least some HttpServletRequest impls + if (name.equalsIgnoreCase("Content-Type")) { + return httpServletRequest.getContentType(); + } else if (name.equalsIgnoreCase("Content-Length")) { + return Integer.toString(httpServletRequest.getContentLength()); + } + return httpServletRequest.getHeader(name); + } + + /** {@inheritDoc} */ + public String getHTTPMethod() { + return httpServletRequest.getMethod(); + } + + /** {@inheritDoc} */ + public InputStream getIncomingStream() { + try { + return httpServletRequest.getInputStream(); + } catch (IOException e) { + log.error("Unable to recover input stream from adapted HttpServletRequest", e); + return null; + } + } + + /** {@inheritDoc} */ + public Credential getLocalCredential() { + // TODO Auto-generated method stub + return null; + } + + /** {@inheritDoc} */ + public String getParameterValue(String name) { + return httpServletRequest.getParameter(name); + + } + + /** {@inheritDoc} */ + public List getParameterValues(String name) { + ArrayList valuesList = new ArrayList(); + String[] values = httpServletRequest.getParameterValues(name); + if (values != null) { + for (String value : values) { + valuesList.add(value); + } + } + + return valuesList; + } + + /** {@inheritDoc} */ + public String getPeerAddress() { + return httpServletRequest.getRemoteAddr(); + } + + /** {@inheritDoc} */ + public Credential getPeerCredential() { + if (peerCredential == null) { + try { + peerCredential = new ServletRequestX509CredentialAdapter(httpServletRequest); + } catch (IllegalArgumentException e) { + log.info("Wrapped HTTP servlet request did not contain a client certificate"); + } + } + return peerCredential; + } + + /** {@inheritDoc} */ + public String getPeerDomainName() { + return httpServletRequest.getRemoteHost(); + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation. It always returns -1; + */ + public int getStatusCode() { + return -1; + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation. It always returns null; + */ + public HTTP_VERSION getVersion() { + // unsupported options + return null; + } + + /** + * Gets the adapted request. + * + * @return adapted request + */ + public HttpServletRequest getWrappedRequest() { + return httpServletRequest; + } + + /** {@inheritDoc} */ + public boolean isAuthenticated() { + return peerAuthenticated; + } + + /** {@inheritDoc} */ + public boolean isConfidential() { + return httpServletRequest.isSecure(); + } + + /** {@inheritDoc} */ + public void setAuthenticated(boolean isAuthenticated) { + peerAuthenticated = isAuthenticated; + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation. + */ + public void setConfidential(boolean isConfidential) { + + } + + /** {@inheritDoc} */ + public boolean isIntegrityProtected() { + return httpServletRequest.isSecure(); + } + + /** {@inheritDoc} */ + public void setIntegrityProtected(boolean isIntegrityProtected) { + + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/transport/http/HttpServletResponseAdapter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/http/HttpServletResponseAdapter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/http/HttpServletResponseAdapter.java 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,250 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.transport.http; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.List; + +import javax.servlet.http.HttpServletResponse; + +import org.opensaml.xml.security.credential.Credential; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Adapts an {@link HttpServletResponse} to an {@link HTTPOutTransport}. + */ +public class HttpServletResponseAdapter implements HTTPOutTransport { + + /** Adapted servlet response. */ + private HttpServletResponse httpServletResponse; + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HttpServletResponseAdapter.class); + + /** Whether the peer endpoint has been authenticated. */ + private boolean peerAuthenticated; + + /** Whether the HTTP connection is over SSL/TLS. */ + private boolean secure; + + /** + * Constructor. + * + * @param response servlet response to adapt + * @param isSecure whether the outbound connection is protected by SSL/TLS + */ + public HttpServletResponseAdapter(HttpServletResponse response, boolean isSecure) { + httpServletResponse = response; + secure = isSecure; + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation and always returns null. + */ + public Object getAttribute(String name) { + return null; + } + + /** {@inheritDoc} */ + public String getCharacterEncoding() { + return httpServletResponse.getCharacterEncoding(); + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation. + * + */ + public String getHeaderValue(String name) { + return null; + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation. + */ + public String getHTTPMethod() { + return null; + } + + /** {@inheritDoc} */ + public Credential getLocalCredential() { + // TODO Auto-generated method stub + return null; + } + + /** {@inheritDoc} */ + public OutputStream getOutgoingStream() { + try { + return httpServletResponse.getOutputStream(); + } catch (IOException e) { + log.error("Unable to recover input stream from adapted HttpServletResponse", e); + return null; + } + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation. + */ + public String getParameterValue(String name) { + return null; + } + + /** {@inheritDoc} */ + public List getParameterValues(String name) { + return null; + } + + /** {@inheritDoc} */ + public Credential getPeerCredential() { + return null; + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation. + */ + public int getStatusCode() { + return -1; + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation. + */ + public HTTP_VERSION getVersion() { + return null; + } + + /** + * Gets the adapted response. + * + * @return adapted response + */ + public HttpServletResponse getWrappedResponse() { + return httpServletResponse; + } + + /** {@inheritDoc} */ + public boolean isAuthenticated() { + return peerAuthenticated; + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation and always returns false. + */ + public boolean isConfidential() { + return secure; + } + + /** {@inheritDoc} */ + public void sendRedirect(String location) { + try { + httpServletResponse.sendRedirect(location); + } catch (IOException e) { + log.error("Unable to send redirect message", e); + } + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation. + */ + public void setAttribute(String name, Object value) { + } + + /** + * {@inheritDoc} + */ + public void setAuthenticated(boolean isAuthenticated) { + peerAuthenticated = isAuthenticated; + } + + /** {@inheritDoc} */ + public void setCharacterEncoding(String encoding) { + httpServletResponse.setCharacterEncoding(encoding); + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation. + */ + public void setConfidential(boolean isConfidential) { + } + + /** {@inheritDoc} */ + public void setHeader(String name, String value) { + if (name == null) { + return; + } + + // HttpServletRequest requires certain headers be set by special methods + if (name.equalsIgnoreCase("Content-Type")) { + httpServletResponse.setContentType(value); + } else if (name.equalsIgnoreCase("Content-Length")) { + httpServletResponse.setContentLength(Integer.parseInt(value)); + } + + httpServletResponse.setHeader(name, value); + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation. + */ + public void addParameter(String name, String value) { + } + + /** {@inheritDoc} */ + public void setStatusCode(int code) { + httpServletResponse.setStatus(code); + } + + /** + * {@inheritDoc} + * + * This method is not supported for this transport implementation. + */ + public void setVersion(HTTP_VERSION version) { + } + + /** {@inheritDoc} */ + public boolean isIntegrityProtected() { + return secure; + } + + /** {@inheritDoc} */ + public void setIntegrityProtected(boolean isIntegrityProtected) { + + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/transport/http/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/transport/http/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/transport/http/package.html 17 Aug 2012 15:09:12 -0000 1.1 @@ -0,0 +1,5 @@ + + +HTTP transport classes included bindings for Servlets. + + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/Action.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/Action.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/Action.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +/** + * The <wsa:Action> element. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface Action extends AttributedURI { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Action"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/Address.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/Address.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/Address.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +/** + * The <wsa:Address> element. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface Address extends AttributedURI { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Address"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + + /** Anonymous address URI. */ + public static final String ANONYMOUS = WSAddressingConstants.WSA_NS + "/anonymous"; + + /** None address URI. */ + public static final String NONE = WSAddressingConstants.WSA_NS + "/none"; +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/AttributedQName.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/AttributedQName.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/AttributedQName.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.schema.XSQName; + +/** + * Interface for type <wsa:AttributedQName>. + * + * @see "WS-Addressing 1.0 - SOAP Binding" + * + */ +public interface AttributedQName extends XSQName, AttributeExtensibleXMLObject, WSAddressingObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AttributedQNameType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSAddressingConstants.WSA_NS, TYPE_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/AttributedURI.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/AttributedURI.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/AttributedURI.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.schema.XSURI; + +/** + * Interface for element of type <wsa:AttributedURIType>. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface AttributedURI extends XSURI, AttributeExtensibleXMLObject, WSAddressingObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AttributedURIType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSAddressingConstants.WSA_NS, TYPE_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/AttributedUnsignedLong.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/AttributedUnsignedLong.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/AttributedUnsignedLong.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; + +/** + * Interface for type <wsa:AttributedUnsignedLongType>. + * + * @see "WS-Addressing 1.0 - SOAP Binding" + * + */ +public interface AttributedUnsignedLong extends AttributeExtensibleXMLObject, WSAddressingObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AttributedUnsignedLongType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSAddressingConstants.WSA_NS, TYPE_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + + /** + * Gets the element's value. + * + * @return the element's value + */ + public Long getValue(); + + /** + * Sets the element's value. + * + * @param newValue the new element value + */ + public void setValue(Long newValue); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/EndpointReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/EndpointReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/EndpointReference.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +/** + * The <wsa:EndpointReference> element. + * + * @see Address + * @see ReferenceParameters + * @see Metadata + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface EndpointReference extends EndpointReferenceType { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "EndpointReference"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/EndpointReferenceType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/EndpointReferenceType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/EndpointReferenceType.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,82 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * Interface for element of type {@link EndpointReferenceType}. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface EndpointReferenceType extends AttributeExtensibleXMLObject, ElementExtensibleXMLObject, WSAddressingObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "EndpointReferenceType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSAddressingConstants.WSA_NS, TYPE_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + + /** + * Returns the <wsa:Address> child element. + * + * @return the {@link Address} child element or null + */ + public Address getAddress(); + + /** + * Sets the <wsa:Address> child element. + * + * @param address the {@link Address} child element to set. + */ + public void setAddress(Address address); + + /** + * Returns the optional <wsa:Metadata> child element. + * + * @return the {@link Metadata} child element or null. + */ + public Metadata getMetadata(); + + /** + * Sets the <wsa:Metadata> child element. + * + * @param metadata the {@link Metadata} child element to set. + */ + public void setMetadata(Metadata metadata); + + /** + * Returns the optional <wsa:ReferenceParameters> child element. + * + * @return the {@link ReferenceParameters} child element or null. + */ + public ReferenceParameters getReferenceParameters(); + + /** + * Sets the <wsa:ReferenceParameters> child element. + * + * @param referenceParameters the {@link ReferenceParameters} child element to set. + */ + public void setReferenceParameters(ReferenceParameters referenceParameters); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/FaultTo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/FaultTo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/FaultTo.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +/** + * The <wsa:FaultTo> element. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface FaultTo extends EndpointReferenceType { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "FaultTo"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/From.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/From.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/From.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +/** + * The <wsa:From> element. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface From extends EndpointReferenceType { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "From"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/IsReferenceParameterBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/IsReferenceParameterBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/IsReferenceParameterBearing.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * Interface for element having a @wsa:IsReferenceParameter attribute. + * + */ +public interface IsReferenceParameterBearing { + + /** the IsReferenceParameter attribute local name. */ + public static final String WSA_IS_REFERENCE_PARAMETER_ATTR_LOCAL_NAME = "IsReferenceParameter"; + + /** the wsa:IsReferenceParameter qualified attribute name. */ + public static final QName WSA_IS_REFERENCE_PARAMETER_ATTR_NAME = + new QName(WSAddressingConstants.WSA_NS, WSA_IS_REFERENCE_PARAMETER_ATTR_LOCAL_NAME, + WSAddressingConstants.WSA_PREFIX); + + /** + * Returns the @wsa:IsReferenceParameter attribute value. + * + * @return The @wsa:IsReferenceParameter attribute value or null. + */ + public Boolean isWSAIsReferenceParameter(); + + /** + * Returns the @wsa:IsReferenceParameter attribute value. + * + * @return The @wsa:IsReferenceParameter attribute value or null. + */ + public XSBooleanValue isWSAIsReferenceParameterXSBoolean(); + + /** + * Sets the @wsa:IsReferenceParameter attribute value. + * + * @param newIsReferenceParameter The @wsa:IsReferenceParameter attribute value + */ + public void setWSAIsReferenceParameter(Boolean newIsReferenceParameter); + + /** + * Sets the @wsa:IsReferenceParameter attribute value. + * + * @param newIsReferenceParameter The @wsa:IsReferenceParameter attribute value + */ + public void setWSAIsReferenceParameter(XSBooleanValue newIsReferenceParameter); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/MessageID.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/MessageID.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/MessageID.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +/** + * The <wsa:MessageID> element. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface MessageID extends AttributedURI { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "MessageID"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/Metadata.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/Metadata.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/Metadata.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The optional <wsa:Metadata> element. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface Metadata extends AttributeExtensibleXMLObject, ElementExtensibleXMLObject, WSAddressingObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Metadata"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "MetadataType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSAddressingConstants.WSA_NS, TYPE_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ProblemAction.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ProblemAction.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ProblemAction.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; + +/** + * Interface for element <wsa:ProblemAction>. + * + * @see "WS-Addressing 1.0 - SOAP Binding" + * + */ +public interface ProblemAction extends AttributeExtensibleXMLObject, WSAddressingObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "ProblemAction"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ProblemActionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSAddressingConstants.WSA_NS, TYPE_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + + /** + * Get the Action child element. + * + * @return the Action child element + */ + public Action getAction(); + + /** + * Set the Action child element. + * + * @param newAction the new Action child element + */ + public void setAction(Action newAction); + + /** + * Get the SoapAction child element. + * + * @return the SoapAction child element + */ + public SoapAction getSoapAction(); + + /** + * Set the SoapAction child element. + * + * @param newSoapAction the new SoapAction child element + */ + public void setSoapAction(SoapAction newSoapAction); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ProblemHeaderQName.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ProblemHeaderQName.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ProblemHeaderQName.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +/** + * Interface for element <wsa:ProblemHeaderQName>. + * + * @see "WS-Addressing 1.0 - SOAP Binding" + * + */ +public interface ProblemHeaderQName extends AttributedQName { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "ProblemHeaderQName"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ProblemIRI.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ProblemIRI.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ProblemIRI.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +/** + * The <wsa:ProblemIRI> element. + * + * @see "WS-Addressing 1.0 - SOAP Binding" + * + */ +public interface ProblemIRI extends AttributedURI { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "ProblemIRI"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ReferenceParameters.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ReferenceParameters.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ReferenceParameters.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The optional <wsa:ReferenceParameters> element. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface ReferenceParameters extends AttributeExtensibleXMLObject, ElementExtensibleXMLObject, WSAddressingObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "ReferenceParameters"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ReferenceParametersType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSAddressingConstants.WSA_NS, TYPE_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/RelatesTo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/RelatesTo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/RelatesTo.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.schema.XSURI; + +/** + * Interface for element <wsa:RelatesTo>. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface RelatesTo extends XSURI, AttributeExtensibleXMLObject, WSAddressingObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "RelatesTo"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RelatesToType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSAddressingConstants.WSA_NS, TYPE_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + + /** The RelationshipType attribute name. */ + public static final String RELATIONSHIP_TYPE_ATTRIB_NAME = "RelationshipType"; + + /** RelationshipType attribute - Reply URI. */ + public static final String RELATIONSHIP_TYPE_REPLY = WSAddressingConstants.WSA_NS + "/reply"; + + /** + * Returns the RelationshipType attribute URI value. + * + * @return the RelationshipType attribute value or null. + */ + public String getRelationshipType(); + + /** + * Sets the RelationshipType attribute URI value. + * + * @param newRelationshipType the RelationshipType attribute value. + */ + public void setRelationshipType(String newRelationshipType); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ReplyTo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ReplyTo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/ReplyTo.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +/** + * The <wsa:ReplyTo> element. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface ReplyTo extends EndpointReferenceType { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "ReplyTo"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/RetryAfter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/RetryAfter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/RetryAfter.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +/** + * Interface for element <wsa:RetryAfter>. + * + * @see "WS-Addressing 1.0 - SOAP Binding" + * + */ +public interface RetryAfter extends AttributedUnsignedLong { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "RetryAfter"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/SoapAction.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/SoapAction.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/SoapAction.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * Interface for element of type <wsa:SoapAction>. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface SoapAction extends XSURI, WSAddressingObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "SoapAction"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/To.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/To.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/To.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +/** + * The <wsa:To> element. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public interface To extends AttributedURI { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "To"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSAddressingConstants.WSA_NS, ELEMENT_LOCAL_NAME, WSAddressingConstants.WSA_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/WSAddressingConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/WSAddressingConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/WSAddressingConstants.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,85 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import javax.xml.namespace.QName; + +/** + * WS-Addressing 1.0 constants. + * + * @see "WS-Addressing 1.0 - Core" + * + */ +public class WSAddressingConstants { + + /** WS-Addressing 1.0 namespace. */ + public static final String WSA_NS= "http://www.w3.org/2005/08/addressing"; + + /** WS-Addressing prefix. */ + public static final String WSA_PREFIX= "wsa"; + + // SOAP fault codes + + /** WS-Addressing SOAP fault code: "wsa:InvalidAddressingHeader". */ + public static final QName SOAP_FAULT_INVALID_ADDRESSING_HEADER = + new QName(WSA_NS, "InvalidAddressingHeader", WSA_PREFIX); + + /** WS-Addressing SOAP fault code: "wsa:InvalidAddress". */ + public static final QName SOAP_FAULT_INVALID_ADDRESS = + new QName(WSA_NS, "InvalidAddress", WSA_PREFIX); + + /** WS-Addressing SOAP fault code: "wsa:InvalidEPR". */ + public static final QName SOAP_FAULT_INVALID_EPR = + new QName(WSA_NS, "InvalidEPR", WSA_PREFIX); + + /** WS-Addressing SOAP fault code: "wsa:InvalidCardinality". */ + public static final QName SOAP_FAULT_INVALID_CARDINALITY = + new QName(WSA_NS, "InvalidCardinality", WSA_PREFIX); + + /** WS-Addressing SOAP fault code: "wsa:MissingAddressInEPR". */ + public static final QName SOAP_FAULT_MISSING_ADDRESS_IN_EPR = + new QName(WSA_NS, "MissingAddressInEPR", WSA_PREFIX); + + /** WS-Addressing SOAP fault code: "wsa:DuplicateMessageID". */ + public static final QName SOAP_FAULT_DUPLICATE_MESSAGE_ID = + new QName(WSA_NS, "DuplicateMessageID", WSA_PREFIX); + + /** WS-Addressing SOAP fault code: "wsa:ActionMismatch". */ + public static final QName SOAP_FAULT_ACTION_MISMATCH = + new QName(WSA_NS, "ActionMismatch", WSA_PREFIX); + + /** WS-Addressing SOAP fault code: "wsa:MessageAddressingHeaderRequired". */ + public static final QName SOAP_FAULT_MESSAGE_ADDRESSING_HEADER_REQUIRED = + new QName(WSA_NS, "MessageAddressingHeaderRequired", WSA_PREFIX); + + /** WS-Addressing SOAP fault code: "wsa:DestinationUnreachable". */ + public static final QName SOAP_FAULT_DESTINATION_UNREACHABLE = + new QName(WSA_NS, "DestinationUnreachable", WSA_PREFIX); + + /** WS-Addressing SOAP fault code: "wsa:ActionNotSupported". */ + public static final QName SOAP_FAULT_ACTION_NOT_SUPPORTED = + new QName(WSA_NS, "ActionNotSupported", WSA_PREFIX); + + /** WS-Addressing SOAP fault code: "wsa:EndpointUnavailable". */ + public static final QName SOAP_FAULT_ENDPOINT_UNAVAILABLE = + new QName(WSA_NS, "EndpointUnavailable", WSA_PREFIX); + + /** Prevent instantiation. */ + private WSAddressingConstants() { } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/WSAddressingObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/WSAddressingObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/WSAddressingObject.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import org.opensaml.xml.XMLObject; + +/** + * Abstract WS-Addressing object interface. + * + */ +public interface WSAddressingObject extends XMLObject { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/WSAddressingObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/WSAddressingObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/WSAddressingObjectBuilder.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing; + +import org.opensaml.xml.XMLObjectBuilder; + +/** + * WSAddressingObjectBuilder. + * + * @param the type of object being built + * + */ +public interface WSAddressingObjectBuilder + extends XMLObjectBuilder { + + /** + * Builds a WS-Addressing object. + * + * @return the built object + */ + public WSAddressingObjectType buildObject(); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/package.html 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,10 @@ + + +

+XMLObject interfaces for WS-Addressing 1.0 elements. +

+

+The W3C Web Services Addressing 1.0 - Core specification defines a set of abstract properties and an XML Infoset [XML Information Set] representation thereof to reference Web services and to facilitate end-to-end addressing of endpoints in messages. +

+ + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AbstractWSAddressingObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AbstractWSAddressingObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AbstractWSAddressingObject.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import java.util.List; + +import org.opensaml.ws.wsaddressing.WSAddressingObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.validation.AbstractValidatingXMLObject; + +/** + * AbstractWSAddressingObject. + * + */ +public abstract class AbstractWSAddressingObject extends AbstractValidatingXMLObject implements WSAddressingObject { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public AbstractWSAddressingObject(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AbstractWSAddressingObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AbstractWSAddressingObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AbstractWSAddressingObjectBuilder.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + + +import org.opensaml.ws.wsaddressing.WSAddressingObject; +import org.opensaml.ws.wsaddressing.WSAddressingObjectBuilder; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * AbstractWSAddressObjectBuilder. + * + * @param the type of WS-Addressing object to be built + */ +public abstract class AbstractWSAddressingObjectBuilder + extends AbstractXMLObjectBuilder implements + WSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public abstract WSAddressingObjectType buildObject(); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AbstractWSAddressingObjectMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AbstractWSAddressingObjectMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AbstractWSAddressingObjectMarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * An abstract marshaller implementation for XMLObjects from {@link org.opensaml.ws.wsaddressing}. + */ +public abstract class AbstractWSAddressingObjectMarshaller extends AbstractXMLObjectMarshaller { + + /** + * Constructor. + */ + protected AbstractWSAddressingObjectMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AbstractWSAddressingObjectUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AbstractWSAddressingObjectUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AbstractWSAddressingObjectUnmarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; + +/** + * An abstract unmarshaller implementation for XMLObjects from {@link org.opensaml.ws.wsaddressing}. + */ +public abstract class AbstractWSAddressingObjectUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** + * Logger. + */ + private final Logger log = LoggerFactory.getLogger(AbstractWSAddressingObjectUnmarshaller.class); + + /** Constructor. */ + protected AbstractWSAddressingObjectUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + log.warn("{} ignoring unknown child element {}", parentXMLObject.getElementQName().getLocalPart(), + childXMLObject.getElementQName().getLocalPart()); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + log.warn("{} ignoring unknown attribute {}", xmlObject.getElementQName().getLocalPart(), attribute + .getLocalName()); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + log.warn("{} ignoring unknown element content: {}", xmlObject.getElementQName().getLocalPart(), elementContent); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ActionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ActionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ActionBuilder.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.Action; + +/** + * ActionBuilder. + * + */ +public class ActionBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public Action buildObject() { + return buildObject(Action.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Action buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ActionImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ActionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ActionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ActionImpl.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.Action; + +/** + * ActionImpl is the concrete implementation of {@link Action}. + * + */ +public class ActionImpl extends AttributedURIImpl implements Action { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ActionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ActionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ActionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ActionMarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.Action; + +/** + * Marshaller for the <wsa:Action> element. + * + * @see Action + * + */ +public class ActionMarshaller extends AttributedURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ActionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ActionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ActionUnmarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.Action; + +/** + * Unmarshaller for the <wsa:Action> element. + * + * @see Action + * + */ +public class ActionUnmarshaller extends AttributedURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressBuilder.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.Address; + +/** + * AddressBuilder. + * + */ +public class AddressBuilder extends AbstractWSAddressingObjectBuilder
{ + + /** {@inheritDoc} */ + public Address buildObject() { + return buildObject(Address.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Address buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AddressImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressImpl.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.Address; + +/** + * AddressImpl is the concrete implementation of {@link Address}. + * + */ +public class AddressImpl extends AttributedURIImpl implements Address { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public AddressImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressMarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.Address; + +/** + * Marshaller for the <wsa:Address> element. + * + * @see Address + * + */ +public class AddressMarshaller extends AttributedURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressUnmarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.Address; + +/** + * Unmarshaller for the <wsa:Address> element. + * + * @see Address + * + */ +public class AddressUnmarshaller extends AttributedURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedQNameImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedQNameImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedQNameImpl.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.AttributedQName; +import org.opensaml.xml.schema.impl.XSQNameImpl; +import org.opensaml.xml.util.AttributeMap; + +/** + * Implementation of {@link AttributedQName}. + */ +public class AttributedQNameImpl extends XSQNameImpl implements AttributedQName { + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public AttributedQNameImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedQNameMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedQNameMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedQNameMarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.AttributedQName; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.schema.impl.XSQNameMarshaller; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for instances of {@link AttributedQName}. + */ +public class AttributedQNameMarshaller extends XSQNameMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributedQName attributedQName = (AttributedQName) xmlObject; + XMLHelper.marshallAttributeMap(attributedQName.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedQNameUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedQNameUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedQNameUnmarshaller.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.AttributedQName; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.impl.XSQNameUnmarshaller; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for instances of {@link AttributedQName}. + */ +public class AttributedQNameUnmarshaller extends XSQNameUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + AttributedQName attributedQName = (AttributedQName) xmlObject; + XMLHelper.unmarshallToAttributeMap(attributedQName.getUnknownAttributes(), attribute); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedURIImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedURIImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedURIImpl.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.AttributedURI; +import org.opensaml.xml.schema.impl.XSURIImpl; +import org.opensaml.xml.util.AttributeMap; + +/** + * AbstractAttributedURIType is the abstract implementation of {@link AttributedURI}. + * + */ +public class AttributedURIImpl extends XSURIImpl implements AttributedURI { + + /** xs:anyAttribute for this element. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public AttributedURIImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedURIMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedURIMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedURIMarshaller.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + + +import org.opensaml.ws.wsaddressing.AttributedURI; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Abstract marshaller for the element of type {@link AttributedURI}. + * + */ +public class AttributedURIMarshaller extends AbstractWSAddressingObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributedURI attributedURI = (AttributedURI) xmlObject; + XMLHelper.appendTextContent(domElement, attributedURI.getValue()); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributedURI attributedURI = (AttributedURI) xmlObject; + XMLHelper.marshallAttributeMap(attributedURI.getUnknownAttributes(), domElement); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedURIUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedURIUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedURIUnmarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.AttributedURI; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Abstract unmarshaller for the element of type {@link AttributedURI}. + * + */ +public class AttributedURIUnmarshaller extends AbstractWSAddressingObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + if (elementContent != null) { + AttributedURI attributedURI = (AttributedURI) xmlObject; + attributedURI.setValue(elementContent); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + AttributedURI attributedURI = (AttributedURI) xmlObject; + XMLHelper.unmarshallToAttributeMap(attributedURI.getUnknownAttributes(), attribute); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedUnsignedLongImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedUnsignedLongImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedUnsignedLongImpl.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.AttributedUnsignedLong; +import org.opensaml.xml.util.AttributeMap; + +/** + * Implementation of {@link AttributedUnsignedLong}. + */ +public class AttributedUnsignedLongImpl extends AbstractWSAddressingObject implements AttributedUnsignedLong { + + /** Element's long value. */ + private Long value; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public AttributedUnsignedLongImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public Long getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setValue(Long newValue) { + value = prepareForAssignment(value, newValue); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedUnsignedLongMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedUnsignedLongMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedUnsignedLongMarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.AttributedUnsignedLong; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for instances of {@link AttributedUnsignedLong}. + */ +public class AttributedUnsignedLongMarshaller extends AbstractWSAddressingObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributedUnsignedLong aul = (AttributedUnsignedLong) xmlObject; + XMLHelper.marshallAttributeMap(aul.getUnknownAttributes(), domElement); + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributedUnsignedLong aul = (AttributedUnsignedLong) xmlObject; + if (aul.getValue() != null) { + XMLHelper.appendTextContent(domElement, aul.getValue().toString()); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedUnsignedLongUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedUnsignedLongUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AttributedUnsignedLongUnmarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.AttributedUnsignedLong; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for instances of {@link AttributedUnsignedLong}. + */ +public class AttributedUnsignedLongUnmarshaller extends AbstractWSAddressingObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + AttributedUnsignedLong aul = (AttributedUnsignedLong) xmlObject; + XMLHelper.unmarshallToAttributeMap(aul.getUnknownAttributes(), attribute); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + AttributedUnsignedLong aul = (AttributedUnsignedLong) xmlObject; + if (elementContent != null) { + aul.setValue(Long.valueOf(elementContent.trim())); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceBuilder.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.EndpointReference; + +/** + * EndpointReferenceBuilder. + * + */ +public class EndpointReferenceBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public EndpointReference buildObject() { + return buildObject(EndpointReference.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public EndpointReference buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EndpointReferenceImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceImpl.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.EndpointReference; + +/** + * Concrete implementation of element {@link EndpointReference}. + * + */ +public class EndpointReferenceImpl extends EndpointReferenceTypeImpl implements EndpointReference { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public EndpointReferenceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceMarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.EndpointReference; + +/** + * Marshaller for the <wsa:EndpointReference> element. + * + * @see EndpointReference + * + */ +public class EndpointReferenceMarshaller extends EndpointReferenceTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceTypeImpl.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,134 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wsaddressing.Address; +import org.opensaml.ws.wsaddressing.EndpointReferenceType; +import org.opensaml.ws.wsaddressing.Metadata; +import org.opensaml.ws.wsaddressing.ReferenceParameters; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * Abstract implementation of the element of type {@link EndpointReferenceType }. + * + */ +public class EndpointReferenceTypeImpl extends AbstractWSAddressingObject implements EndpointReferenceType { + + /** {@link Address} child element. */ + private Address address; + + /** Optional {@link Metadata} child element. */ + private Metadata metadata; + + /** Optional {@link ReferenceParameters} child element. */ + private ReferenceParameters referenceParameters; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public EndpointReferenceTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public Address getAddress() { + return address; + } + + /** {@inheritDoc} */ + public void setAddress(Address newAddress) { + address = prepareForAssignment(address, newAddress); + } + + /** {@inheritDoc} */ + public Metadata getMetadata() { + return metadata; + } + + /** {@inheritDoc} */ + public void setMetadata(Metadata newMetadata) { + metadata = prepareForAssignment(metadata, newMetadata); + } + + /** {@inheritDoc} */ + public ReferenceParameters getReferenceParameters() { + return referenceParameters; + } + + /** {@inheritDoc} */ + public void setReferenceParameters(ReferenceParameters newReferenceParameters) { + referenceParameters = prepareForAssignment(referenceParameters, newReferenceParameters); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (address != null) { + children.add(address); + } + if (referenceParameters != null) { + children.add(referenceParameters); + } + if (metadata != null) { + children.add(metadata); + } + + // xs:any element + if (!getUnknownXMLObjects().isEmpty()) { + children.addAll(getUnknownXMLObjects()); + } + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceTypeMarshaller.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.EndpointReferenceType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Abstract marshaller for the element of type {@link EndpointReferenceType}. + * + */ +public class EndpointReferenceTypeMarshaller extends AbstractWSAddressingObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + EndpointReferenceType eprType = (EndpointReferenceType) xmlObject; + XMLHelper.marshallAttributeMap(eprType.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceTypeUnmarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.Address; +import org.opensaml.ws.wsaddressing.EndpointReferenceType; +import org.opensaml.ws.wsaddressing.Metadata; +import org.opensaml.ws.wsaddressing.ReferenceParameters; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Abstract unmarshaller for the element of type {@link EndpointReferenceType}. + * + */ +public class EndpointReferenceTypeUnmarshaller extends AbstractWSAddressingObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + EndpointReferenceType epr = (EndpointReferenceType) parentXMLObject; + if (childXMLObject instanceof Address) { + epr.setAddress((Address) childXMLObject); + } else if (childXMLObject instanceof Metadata) { + epr.setMetadata((Metadata) childXMLObject); + } else if (childXMLObject instanceof ReferenceParameters) { + epr.setReferenceParameters((ReferenceParameters) childXMLObject); + } else { + epr.getUnknownXMLObjects().add(childXMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + EndpointReferenceType epr = (EndpointReferenceType) xmlObject; + XMLHelper.unmarshallToAttributeMap(epr.getUnknownAttributes(), attribute); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/EndpointReferenceUnmarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.EndpointReference; + +/** + * Unmarshaller for the <wsa:EndpointReference> element. + * + * @see EndpointReference + * + */ +public class EndpointReferenceUnmarshaller extends EndpointReferenceTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FaultToBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FaultToBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FaultToBuilder.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.FaultTo; + +/** + * Builder for the {@link FaultTo} element. + * + */ +public class FaultToBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public FaultTo buildObject() { + return buildObject(FaultTo.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public FaultTo buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new FaultToImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FaultToImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FaultToImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FaultToImpl.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.FaultTo; + +/** + * Concrete implementation of element {@link FaultTo}. + * + */ +public class FaultToImpl extends EndpointReferenceTypeImpl implements FaultTo { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public FaultToImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FaultToMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FaultToMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FaultToMarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.FaultTo; + +/** + * Marshaller for the {@link FaultTo} element. + * + */ +public class FaultToMarshaller extends EndpointReferenceTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FaultToUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FaultToUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FaultToUnmarshaller.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.FaultTo; + +/** + * Unmarshaller for the {@link FaultTo} element. + * + */ +public class FaultToUnmarshaller extends EndpointReferenceTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FromBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FromBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FromBuilder.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.From; + +/** + * Builder for the {@link From} element. + * + */ +public class FromBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public From buildObject() { + return buildObject(From.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public From buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new FromImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FromImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FromImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FromImpl.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.From; + +/** + * Concrete implementation of element {@link From}. + * + */ +public class FromImpl extends EndpointReferenceTypeImpl implements From { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public FromImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FromMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FromMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FromMarshaller.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.From; + +/** + * Marshaller for the {@link From} element. + * + */ +public class FromMarshaller extends EndpointReferenceTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FromUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FromUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/FromUnmarshaller.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.From; + +/** + * Unmarshaller for the {@link From} element. + * + */ +public class FromUnmarshaller extends EndpointReferenceTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDBuilder.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.MessageID; + +/** + * MessageIDBuilder. + * + */ +public class MessageIDBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public MessageID buildObject() { + return buildObject(MessageID.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public MessageID buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new MessageIDImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDImpl.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.MessageID; + +/** + * Concrete implementation for the {@link MessageID} element. + */ +public class MessageIDImpl extends AttributedURIImpl implements MessageID { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public MessageIDImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDMarshaller.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.MessageID; + +/** + * Marshaller for the <wsa:MessageID> element. + * + * @see MessageID + * + */ +public class MessageIDMarshaller extends AttributedURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDUnmarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.MessageID; + +/** + * Unmarshaller for the <wsa:MessageID> element. + * + * @see MessageID + * + */ +public class MessageIDUnmarshaller extends AttributedURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MetadataBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MetadataBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MetadataBuilder.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.Metadata; + +/** + * MetadataBuilder. + * + */ +public class MetadataBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public Metadata buildObject() { + return buildObject(Metadata.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Metadata buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new MetadataImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MetadataImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MetadataImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MetadataImpl.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,82 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wsaddressing.Metadata; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * MetadataImpl. + * + */ +public class MetadataImpl extends AbstractWSAddressingObject implements Metadata { + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public MetadataImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (!getUnknownXMLObjects().isEmpty()) { + children.addAll(getUnknownXMLObjects()); + } + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MetadataMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MetadataMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MetadataMarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + + +import org.opensaml.ws.wsaddressing.Metadata; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * MetadataMarshaller. + * + */ +public class MetadataMarshaller extends AbstractWSAddressingObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Metadata metadata = (Metadata) xmlObject; + XMLHelper.marshallAttributeMap(metadata.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MetadataUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MetadataUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MetadataUnmarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.Metadata; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * MetadataUnmarshaller. + * + */ +public class MetadataUnmarshaller extends AbstractWSAddressingObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Metadata metadata = (Metadata) xmlObject; + XMLHelper.unmarshallToAttributeMap(metadata.getUnknownAttributes(), attribute); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Metadata metadata = (Metadata) parentXMLObject; + metadata.getUnknownXMLObjects().add(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemActionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemActionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemActionBuilder.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ProblemAction; + +/** + * ProblemActionBuilder. + * + */ +public class ProblemActionBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public ProblemAction buildObject() { + return buildObject(ProblemAction.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ProblemAction buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ProblemActionImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemActionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemActionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemActionImpl.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,94 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wsaddressing.Action; +import org.opensaml.ws.wsaddressing.ProblemAction; +import org.opensaml.ws.wsaddressing.SoapAction; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; + +/** + * Implementation of {@link ProblemAction}. + */ +public class ProblemActionImpl extends AbstractWSAddressingObject implements ProblemAction { + + /** Action child element. */ + private Action action; + + /** SoapAction child element. */ + private SoapAction soapAction; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ProblemActionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public Action getAction() { + return action; + } + + /** {@inheritDoc} */ + public SoapAction getSoapAction() { + return soapAction; + } + + /** {@inheritDoc} */ + public void setAction(Action newAction) { + action = prepareForAssignment(action, newAction); + } + + /** {@inheritDoc} */ + public void setSoapAction(SoapAction newSoapAction) { + soapAction = prepareForAssignment(soapAction, newSoapAction); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (action != null) { + children.add(action); + } + if (soapAction != null) { + children.add(soapAction); + } + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemActionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemActionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemActionMarshaller.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ProblemAction; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for instances of {@link ProblemAction}. + */ +public class ProblemActionMarshaller extends AbstractWSAddressingObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + ProblemAction pa = (ProblemAction) xmlObject; + XMLHelper.marshallAttributeMap(pa.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemActionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemActionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemActionUnmarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.Action; +import org.opensaml.ws.wsaddressing.ProblemAction; +import org.opensaml.ws.wsaddressing.SoapAction; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for instances of {@link ProblemActionUnmarshaller}. + */ +public class ProblemActionUnmarshaller extends AbstractWSAddressingObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + ProblemAction pa = (ProblemAction) xmlObject; + XMLHelper.unmarshallToAttributeMap(pa.getUnknownAttributes(), attribute); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ProblemAction pa = (ProblemAction) parentXMLObject; + + if (childXMLObject instanceof Action) { + pa.setAction((Action) childXMLObject); + } else if (childXMLObject instanceof SoapAction) { + pa.setSoapAction((SoapAction) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemHeaderQNameBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemHeaderQNameBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemHeaderQNameBuilder.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ProblemHeaderQName; + +/** + * ProblemHeaderQNameBuilder. + * + */ +public class ProblemHeaderQNameBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public ProblemHeaderQName buildObject() { + return buildObject(ProblemHeaderQName.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ProblemHeaderQName buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ProblemHeaderQNameImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemHeaderQNameImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemHeaderQNameImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemHeaderQNameImpl.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ProblemHeaderQName; + +/** + * Concrete implementation for the {@link ProblemHeaderQName} element. + */ +public class ProblemHeaderQNameImpl extends AttributedQNameImpl implements ProblemHeaderQName { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ProblemHeaderQNameImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemHeaderQNameMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemHeaderQNameMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemHeaderQNameMarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ProblemHeaderQName; + +/** + * Marshaller for the <wsa:ProblemHeaderQName> element. + * + * @see ProblemHeaderQName + * + */ +public class ProblemHeaderQNameMarshaller extends AttributedQNameMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemHeaderQNameUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemHeaderQNameUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemHeaderQNameUnmarshaller.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.MessageID; + +/** + * Unmarshaller for the <wsa:ProblemHeaderQName> element. + * + * @see MessageID + * + */ +public class ProblemHeaderQNameUnmarshaller extends AttributedQNameUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemIRIBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemIRIBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemIRIBuilder.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ProblemIRI; + +/** + * ProblemIRIBuilder. + * + */ +public class ProblemIRIBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public ProblemIRI buildObject() { + return buildObject(ProblemIRI.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ProblemIRI buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ProblemIRIImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemIRIImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemIRIImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemIRIImpl.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ProblemIRI; + +/** + * ProblemIRIImpl is the concrete implementation of {@link ProblemIRI}. + * + */ +public class ProblemIRIImpl extends AttributedURIImpl implements ProblemIRI { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ProblemIRIImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemIRIMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemIRIMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemIRIMarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ProblemIRI; + +/** + * Marshaller for the <wsa:ProblemIRI> element. + * + * @see ProblemIRI + * + */ +public class ProblemIRIMarshaller extends AttributedURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemIRIUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemIRIUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ProblemIRIUnmarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ProblemIRI; + +/** + * Unmarshaller for the <wsa:ProblemIRI> element. + * + * @see ProblemIRI + * + */ +public class ProblemIRIUnmarshaller extends AttributedURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReferenceParametersBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReferenceParametersBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReferenceParametersBuilder.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ReferenceParameters; + +/** + * ReferenceParametersBuilder. + * + */ +public class ReferenceParametersBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public ReferenceParameters buildObject() { + return buildObject(ReferenceParameters.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ReferenceParameters buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ReferenceParametersImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReferenceParametersImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReferenceParametersImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReferenceParametersImpl.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,82 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wsaddressing.ReferenceParameters; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * ReferenceParametersImpl. + * + */ +public class ReferenceParametersImpl extends AbstractWSAddressingObject implements ReferenceParameters { + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ReferenceParametersImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (!getUnknownXMLObjects().isEmpty()) { + children.addAll(getUnknownXMLObjects()); + } + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReferenceParametersMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReferenceParametersMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReferenceParametersMarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + + +import org.opensaml.ws.wsaddressing.ReferenceParameters; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * ReferenceParametersMarshaller. + * + */ +public class ReferenceParametersMarshaller extends AbstractWSAddressingObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + ReferenceParameters rp = (ReferenceParameters) xmlObject; + XMLHelper.marshallAttributeMap(rp.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReferenceParametersUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReferenceParametersUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReferenceParametersUnmarshaller.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ReferenceParameters; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * ReferenceParametersUnmarshaller. + * + */ +public class ReferenceParametersUnmarshaller extends AbstractWSAddressingObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + ReferenceParameters rp = (ReferenceParameters) xmlObject; + XMLHelper.unmarshallToAttributeMap(rp.getUnknownAttributes(), attribute); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ReferenceParameters rp = (ReferenceParameters) parentXMLObject; + rp.getUnknownXMLObjects().add(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RelatesToBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RelatesToBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RelatesToBuilder.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.RelatesTo; + +/** + * RelatesToBuilder. + * + */ +public class RelatesToBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public RelatesTo buildObject() { + return buildObject(RelatesTo.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RelatesTo buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RelatesToImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RelatesToImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RelatesToImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RelatesToImpl.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.RelatesTo; +import org.opensaml.xml.schema.impl.XSURIImpl; +import org.opensaml.xml.util.AttributeMap; + +/** + * Implementation of {@link RelatesTo}. + */ +public class RelatesToImpl extends XSURIImpl implements RelatesTo { + + /** RelationshipType attribute value. */ + private String relationshipType; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RelatesToImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + // Default attribute value per the schema. + setRelationshipType(RELATIONSHIP_TYPE_REPLY); + } + + /** {@inheritDoc} */ + public String getRelationshipType() { + return relationshipType; + } + + /** {@inheritDoc} */ + public void setRelationshipType(String newRelationshipType) { + relationshipType = prepareForAssignment(relationshipType, newRelationshipType); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RelatesToMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RelatesToMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RelatesToMarshaller.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.RelatesTo; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.schema.impl.XSURIMarshaller; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for instances of {@link RelatesTo}. + */ +public class RelatesToMarshaller extends XSURIMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + RelatesTo relatesTo = (RelatesTo) xmlObject; + + String relationshipType = DatatypeHelper.safeTrimOrNullString(relatesTo.getRelationshipType()); + if (relationshipType != null) { + domElement.setAttributeNS(null, RelatesTo.RELATIONSHIP_TYPE_ATTRIB_NAME, relationshipType); + } + + XMLHelper.marshallAttributeMap(relatesTo.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RelatesToUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RelatesToUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RelatesToUnmarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.RelatesTo; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for instances of {@link RelatesTo}. + */ +public class RelatesToUnmarshaller extends XSURIUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + RelatesTo relatesTo = (RelatesTo) xmlObject; + + if (RelatesTo.RELATIONSHIP_TYPE_ATTRIB_NAME.equals(attribute.getLocalName())) { + relatesTo.setRelationshipType(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + XMLHelper.unmarshallToAttributeMap(relatesTo.getUnknownAttributes(), attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReplyToBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReplyToBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReplyToBuilder.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ReplyTo; + +/** + * Builder for the {@link ReplyTo} element. + * + */ +public class ReplyToBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public ReplyTo buildObject() { + return buildObject(ReplyTo.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ReplyTo buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ReplyToImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReplyToImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReplyToImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReplyToImpl.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ReplyTo; + +/** + * Concrete implementation of element {@link ReplyTo}. + * + */ +public class ReplyToImpl extends EndpointReferenceTypeImpl implements ReplyTo { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ReplyToImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReplyToMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReplyToMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReplyToMarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ReplyTo; + +/** + * Marshaller for the {@link ReplyTo} element. + * + */ +public class ReplyToMarshaller extends EndpointReferenceTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReplyToUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReplyToUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ReplyToUnmarshaller.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.ReplyTo; + +/** + * Unmarshaller for the {@link ReplyTo} element. + * + */ +public class ReplyToUnmarshaller extends EndpointReferenceTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RetryAfterBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RetryAfterBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RetryAfterBuilder.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.RetryAfter; + +/** + * RetryAfterBuilder. + * + */ +public class RetryAfterBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public RetryAfter buildObject() { + return buildObject(RetryAfter.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RetryAfter buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RetryAfterImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RetryAfterImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RetryAfterImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RetryAfterImpl.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.RetryAfter; + +/** + * Implementation of {@link RetryAfter}. + */ +public class RetryAfterImpl extends AttributedUnsignedLongImpl implements RetryAfter { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RetryAfterImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RetryAfterMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RetryAfterMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RetryAfterMarshaller.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.RetryAfter; + +/** + * Marshaller for instances of {@link RetryAfter}. + */ +public class RetryAfterMarshaller extends AttributedUnsignedLongMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RetryAfterUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RetryAfterUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/RetryAfterUnmarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.RetryAfter; + +/** + * Unmarshaller for instances of {@link RetryAfter}. + */ +public class RetryAfterUnmarshaller extends AttributedUnsignedLongUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/SoapActionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/SoapActionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/SoapActionBuilder.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.SoapAction; + +/** + * SoapActionBuilder. + * + */ +public class SoapActionBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public SoapAction buildObject() { + return buildObject(SoapAction.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public SoapAction buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SoapActionImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/SoapActionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/SoapActionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/SoapActionImpl.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.SoapAction; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * Implementation of {@link SoapAction}. + */ +public class SoapActionImpl extends XSURIImpl implements SoapAction { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public SoapActionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/SoapActionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/SoapActionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/SoapActionMarshaller.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.SoapAction; +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for instances of {@link SoapAction}. + */ +public class SoapActionMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/SoapActionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/SoapActionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/SoapActionUnmarshaller.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.SoapAction; +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for instances of {@link SoapAction}. + */ +public class SoapActionUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ToBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ToBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ToBuilder.java 17 Aug 2012 15:08:53 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.To; + +/** + * Builder for the {@link To} element. + * + */ +public class ToBuilder extends AbstractWSAddressingObjectBuilder { + + /** {@inheritDoc} */ + public To buildObject() { + return buildObject(To.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public To buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ToImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ToImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ToImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ToImpl.java 17 Aug 2012 15:08:51 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.To; + +/** + * Concrete implementation for the {@link To} element. + */ +public class ToImpl extends AttributedURIImpl implements To { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ToImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ToMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ToMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ToMarshaller.java 17 Aug 2012 15:08:52 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.To; + +/** + * Marshaller for the <wsa:To> element. + * + * @see To + * + */ +public class ToMarshaller extends AttributedURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ToUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ToUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/ToUnmarshaller.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.impl; + +import org.opensaml.ws.wsaddressing.To; + +/** + * Unmarshaller for the <wsa:To> element. + * + * @see To + * + */ +public class ToUnmarshaller extends AttributedURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/util/WSAddressingHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsaddressing/util/WSAddressingHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsaddressing/util/WSAddressingHelper.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsaddressing.util; + +import org.opensaml.ws.wsaddressing.IsReferenceParameterBearing; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Helper methods for working with WS-Addressing. + */ +public final class WSAddressingHelper { + + /** + * Private constructor. + */ + private WSAddressingHelper() { + } + + /** + * Adds a wsa:IsReferenceParameter attribute to the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * @param isReferenceParameter whether IsReferenceParameter is true or false + */ + public static void addWSAIsReferenceParameter(XMLObject soapObject, boolean isReferenceParameter) { + if (soapObject instanceof IsReferenceParameterBearing) { + ((IsReferenceParameterBearing)soapObject).setWSAIsReferenceParameter( + new XSBooleanValue(isReferenceParameter, false)); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + ((AttributeExtensibleXMLObject)soapObject).getUnknownAttributes() + .put(IsReferenceParameterBearing.WSA_IS_REFERENCE_PARAMETER_ATTR_NAME, + new XSBooleanValue(isReferenceParameter, false).toString()); + } else { + throw new IllegalArgumentException("Specified object was neither IsReferenceParameterBearing nor AttributeExtensible"); + } + } + + /** + * Get the wsa:IsReferenceParameter attribute from a given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * + * @return value of the IsReferenceParameter attribute, or false if not present + */ + public static boolean getWSAIsReferenceParameter(XMLObject soapObject) { + if (soapObject instanceof IsReferenceParameterBearing) { + XSBooleanValue value = ((IsReferenceParameterBearing)soapObject).isWSAIsReferenceParameterXSBoolean(); + if (value != null) { + return value.getValue(); + } + } + if (soapObject instanceof AttributeExtensibleXMLObject) { + String valueStr = DatatypeHelper.safeTrimOrNullString(((AttributeExtensibleXMLObject)soapObject) + .getUnknownAttributes().get(IsReferenceParameterBearing.WSA_IS_REFERENCE_PARAMETER_ATTR_NAME)); + return DatatypeHelper.safeEquals("1", valueStr) || DatatypeHelper.safeEquals("true", valueStr); + } + return false; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/Address.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/Address.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/Address.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed; + +import javax.xml.namespace.QName; + +/** + * This interface defines how the object representing a WS Address Address element behaves. + */ +public interface Address extends WSFedObject { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Address"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(WSFedConstants.WSADDRESS_NS, DEFAULT_ELEMENT_LOCAL_NAME, + WSFedConstants.WSADDRESS_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AddressType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(WSFedConstants.WSADDRESS_NS, TYPE_LOCAL_NAME, + WSFedConstants.WSADDRESS_PREFIX); + + /** + * Gets the end point reference address. + * + * @return the end point address + */ + public String getValue(); + + /** + * Sets the end point reference address. + * + * @param value the end point address + */ + public void setValue(String value); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/AppliesTo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/AppliesTo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/AppliesTo.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed; + +import javax.xml.namespace.QName; + +/** + * This interface defines how the object representing a WS Applies To AppliesTo element behaves. + */ +public interface AppliesTo extends WSFedObject { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AppliesTo"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(WSFedConstants.WSPOLICY_NS, DEFAULT_ELEMENT_LOCAL_NAME, + WSFedConstants.WSPOLICY_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AppliesToType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(WSFedConstants.WSPOLICY_NS, TYPE_LOCAL_NAME, + WSFedConstants.WSPOLICY_PREFIX); + + /** + * Gets the endpoint reference of the entity applicable entity. + * + * @return the endpoint reference of the entity applicable entity + */ + public EndPointReference getEndPointReference(); + + /** + * Sets the endpoint reference of the entity applicable entity. + * + * @param newEndPointReference the endpoint reference of the entity applicable entity + */ + public void setEndPointReference(EndPointReference newEndPointReference); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/EndPointReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/EndPointReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/EndPointReference.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed; + +import javax.xml.namespace.QName; + +/** + * This interface defines how the object representing a WS End Point Reference EndPointReference element + * behaves. + */ +public interface EndPointReference extends WSFedObject { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "EndPointReference"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(WSFedConstants.WSADDRESS_NS, DEFAULT_ELEMENT_LOCAL_NAME, + WSFedConstants.WSADDRESS_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "EndPointReferenceType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(WSFedConstants.WSADDRESS_NS, TYPE_LOCAL_NAME, + WSFedConstants.WSADDRESS_PREFIX); + + /** + * Return the object representing the Address (element). + * + * @return the end point address + */ + public Address getAddress(); + + /** + * Sets the end point address as an object. + * + * @param address the end point address + */ + public void setAddress(Address address); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/RequestSecurityTokenResponse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/RequestSecurityTokenResponse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/RequestSecurityTokenResponse.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed; + +import java.util.List; + +import javax.xml.namespace.QName; + +/** + * This interface defines how the object representing a WS RSTR RequestedSecurityTokenResponse element + * behaves. + */ +public interface RequestSecurityTokenResponse extends WSFedObject { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "RequestSecurityTokenResponse"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(WSFedConstants.WSFED11P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + WSFedConstants.WSFED1P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestSecurityTokenResponseType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(WSFedConstants.WSFED11P_NS, TYPE_LOCAL_NAME, + WSFedConstants.WSFED1P_PREFIX); + + /** + * Gets the entity to which the token applies. + * + * @return the entity to which the token applies + */ + public AppliesTo getAppliesTo(); + + /** + * Set the entity to which the token applies. + * + * @param appliesTo the entity to which the token applies + */ + public void setAppliesTo(AppliesTo appliesTo); + + /** + * Return the list of Security Token child elements. + * + * @return the list of RequestedSecurityToken child elements. + */ + public List getRequestedSecurityToken(); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/RequestedSecurityToken.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/RequestedSecurityToken.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/RequestedSecurityToken.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * This interface defines how the object representing a Requested Security Token RequestedSecurityToken + * element behaves. + */ +public interface RequestedSecurityToken extends WSFedObject { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "RequestedSecurityToken"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(WSFedConstants.WSFED11P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + WSFedConstants.WSFED1P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestedSecurityTokenType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(WSFedConstants.WSFED11P_NS, TYPE_LOCAL_NAME, + WSFedConstants.WSFED1P_PREFIX); + + /** + * Return the list security tokens. + * + * @return the list security tokens + */ + public List getSecurityTokens(); +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/WSFedConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/WSFedConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/WSFedConstants.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed; + +/** WS-Federation Constants. */ +public class WSFedConstants { + + /** WSFED 1.1 protocol XML namespace. */ + public static final String WSFED11P_NS = "http://schemas.xmlsoap.org/ws/2005/02/trust"; + + /** WSFED 1.X Protocol QName prefix. */ + public static final String WSFED1P_PREFIX = "wst"; + + /** WSFED 1.X Policy XML namespace. */ + public static final String WSPOLICY_NS = "http://schemas.xmlsoap.org/ws/2004/09/policy"; + + /** WSFED 1.X Policy QName prefix. */ + public static final String WSPOLICY_PREFIX = "wsp"; + + /** WSFED 1.X Address XML namespace. */ + public static final String WSADDRESS_NS = "http://schemas.xmlsoap.org/ws/2004/08/addressing"; + + /** WSFED 1.X Address QName prefix. */ + public static final String WSADDRESS_PREFIX = "wsa"; + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/WSFedObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/WSFedObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/WSFedObject.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed; + +import org.opensaml.xml.XMLObject; + +/** Marker interface for WS-Federation {@link XMLObject}s. */ +public interface WSFedObject extends XMLObject { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/WSFedObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/WSFedObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/WSFedObjectBuilder.java 17 Aug 2012 15:09:11 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed; + +import org.opensaml.xml.XMLObjectBuilder; + +/** + * Builder of {@link WSFedObject}s. + * + * @param type of WS-Federation object constructed by the builder. + */ +public interface WSFedObjectBuilder extends XMLObjectBuilder { + + /** + * Builds a WS-Federation object using its default element name. + * + * @return the constructed object + */ + public WSFedObjectType buildObject(); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AddressBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AddressBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AddressBuilder.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.ws.wsfed.Address; +import org.opensaml.ws.wsfed.WSFedConstants; +import org.opensaml.ws.wsfed.WSFedObjectBuilder; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** Builder of {@link AddressImpl} objects. */ +public class AddressBuilder extends AbstractXMLObjectBuilder
implements WSFedObjectBuilder
{ + + /** Constructor. */ + public AddressBuilder() { + + } + + /** {@inheritDoc} */ + public final Address buildObject() { + return buildObject(WSFedConstants.WSADDRESS_NS, Address.DEFAULT_ELEMENT_LOCAL_NAME, + WSFedConstants.WSADDRESS_PREFIX); + } + + /** {@inheritDoc} */ + public Address buildObject(final String namespaceURI, final String localName, String namespacePrefix) { + return new AddressImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AddressImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AddressImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AddressImpl.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.ws.wsfed.Address; +import org.opensaml.xml.AbstractXMLObject; +import org.opensaml.xml.XMLObject; + +/** Implementation of the {@link Address} object. */ +public class AddressImpl extends AbstractXMLObject implements Address { + + /** Address value. */ + private String value; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AddressImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setValue(String newValue) { + value = prepareForAssignment(value, newValue); + + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return new ArrayList(); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AddressMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AddressMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AddressMarshaller.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.ws.wsfed.Address; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** A thread-safe marshaller for {@link Address} objects. */ +public class AddressMarshaller extends AbstractXMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject fedObject, Element domElement) { + + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject fedObject, Element domElement) { + Address address = (Address) fedObject; + + if (address.getValue() != null) { + XMLHelper.appendTextContent(domElement, address.getValue()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AddressUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AddressUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AddressUnmarshaller.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.ws.wsfed.Address; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.w3c.dom.Attr; + +/** A thread-safe unmarshaller for {@link Address} objects. */ +public class AddressUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject fedObject, String elementContent) { + Address address = (Address) fedObject; + address.setValue(elementContent); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject fedObject, Attr attribute) { + + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject fedObject, XMLObject child) { + + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AppliesToBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AppliesToBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AppliesToBuilder.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.ws.wsfed.AppliesTo; +import org.opensaml.ws.wsfed.WSFedConstants; +import org.opensaml.ws.wsfed.WSFedObjectBuilder; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** Builder of {@link AppliesToImpl} objects. */ +public class AppliesToBuilder extends AbstractXMLObjectBuilder implements WSFedObjectBuilder { + + /** Constructor. */ + public AppliesToBuilder() { + + } + + /** {@inheritDoc} */ + public AppliesTo buildObject() { + return buildObject(WSFedConstants.WSPOLICY_NS, AppliesTo.DEFAULT_ELEMENT_LOCAL_NAME, + WSFedConstants.WSPOLICY_PREFIX); + } + + /** {@inheritDoc} */ + public AppliesTo buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AppliesToImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AppliesToImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AppliesToImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AppliesToImpl.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wsfed.AppliesTo; +import org.opensaml.ws.wsfed.EndPointReference; +import org.opensaml.xml.AbstractXMLObject; +import org.opensaml.xml.XMLObject; + +/** Implementation of the {@link AppliesTo} Object. */ +public class AppliesToImpl extends AbstractXMLObject implements AppliesTo { + + /** Endpoint reference. */ + private EndPointReference endPointReference; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AppliesToImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public EndPointReference getEndPointReference() { + return endPointReference; + } + + /** {@inheritDoc} */ + public void setEndPointReference(EndPointReference reference) { + endPointReference = prepareForAssignment(endPointReference, reference); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.add(endPointReference); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AppliesToMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AppliesToMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AppliesToMarshaller.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.w3c.dom.Element; + +/** A thread safe marshaller for {@link org.opensaml.ws.wsfed.AppliesTo} objects. */ +public class AppliesToMarshaller extends AbstractXMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject fedObject, Element domElement) { + + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject fedObject, Element domElement) { + + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AppliesToUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AppliesToUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/AppliesToUnmarshaller.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.ws.wsfed.AppliesTo; +import org.opensaml.ws.wsfed.EndPointReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.w3c.dom.Attr; + +/** A thread-safe unmarshaller for {@link AppliesTo} objects. */ +public class AppliesToUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentFedObject, XMLObject childFedObject) { + + AppliesTo appliesTo = (AppliesTo) parentFedObject; + + if (childFedObject instanceof EndPointReference) { + appliesTo.setEndPointReference((EndPointReference) childFedObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject fedObject, Attr attribute) { + + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject fedObject, String content) { + + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/EndPointReferenceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/EndPointReferenceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/EndPointReferenceBuilder.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.ws.wsfed.EndPointReference; +import org.opensaml.ws.wsfed.WSFedConstants; +import org.opensaml.ws.wsfed.WSFedObjectBuilder; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** Builder of {@link EndPointReferenceImpl} objects. */ +public class EndPointReferenceBuilder extends AbstractXMLObjectBuilder implements + WSFedObjectBuilder { + + /** Constructor. */ + public EndPointReferenceBuilder() { + + } + + /** {@inheritDoc} */ + public EndPointReference buildObject() { + return buildObject(WSFedConstants.WSADDRESS_NS, EndPointReference.DEFAULT_ELEMENT_LOCAL_NAME, + WSFedConstants.WSADDRESS_PREFIX); + } + + /** {@inheritDoc} */ + public EndPointReference buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EndPointReferenceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/EndPointReferenceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/EndPointReferenceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/EndPointReferenceImpl.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wsfed.Address; +import org.opensaml.ws.wsfed.EndPointReference; +import org.opensaml.xml.AbstractXMLObject; +import org.opensaml.xml.XMLObject; + +/** Implementation of the {@link EndPointReference} object. */ +public class EndPointReferenceImpl extends AbstractXMLObject implements EndPointReference { + + /** Address of the endpoint. */ + private Address address; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EndPointReferenceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + + } + + /** {@inheritDoc} */ + public Address getAddress() { + return address; + } + + /** {@inheritDoc} */ + public void setAddress(Address newAddress) { + address = prepareForAssignment(address, newAddress); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.add(address); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/EndPointReferenceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/EndPointReferenceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/EndPointReferenceMarshaller.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.w3c.dom.Element; + +/** A thread safe marshaller for {@link org.opensaml.ws.wsfed.EndPointReference} objects. */ +public class EndPointReferenceMarshaller extends AbstractXMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject fedObject, Element domElement) { + + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject fedObject, Element domElement) { + + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/EndPointReferenceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/EndPointReferenceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/EndPointReferenceUnmarshaller.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.ws.wsfed.Address; +import org.opensaml.ws.wsfed.EndPointReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.w3c.dom.Attr; + +/** A thread-safe unmarshaller for {@link EndPointReference} objects. */ +public class EndPointReferenceUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) { + EndPointReference endPointReference = (EndPointReference) parentSAMLObject; + + if (childSAMLObject instanceof Address) { + endPointReference.setAddress((Address) childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject fedObject, Attr attribute) { + + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject fedObject, String content) { + + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestSecurityTokenResponseBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestSecurityTokenResponseBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestSecurityTokenResponseBuilder.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.ws.wsfed.RequestSecurityTokenResponse; +import org.opensaml.ws.wsfed.WSFedConstants; +import org.opensaml.ws.wsfed.WSFedObjectBuilder; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** Builder of {@link RequestSecurityTokenResponseImpl} objects. */ +public class RequestSecurityTokenResponseBuilder extends AbstractXMLObjectBuilder + implements WSFedObjectBuilder { + + /** Constructor. */ + public RequestSecurityTokenResponseBuilder() { + + } + + /** {@inheritDoc} */ + public RequestSecurityTokenResponse buildObject() { + return buildObject(WSFedConstants.WSFED11P_NS, RequestSecurityTokenResponse.DEFAULT_ELEMENT_LOCAL_NAME, + WSFedConstants.WSFED1P_PREFIX); + } + + /** {@inheritDoc} */ + public RequestSecurityTokenResponse buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestSecurityTokenResponseImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestSecurityTokenResponseImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestSecurityTokenResponseImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestSecurityTokenResponseImpl.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wsfed.AppliesTo; +import org.opensaml.ws.wsfed.RequestSecurityTokenResponse; +import org.opensaml.ws.wsfed.RequestedSecurityToken; +import org.opensaml.xml.AbstractXMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Implementation of the {@link RequestSecurityTokenResponse} object. */ +public class RequestSecurityTokenResponseImpl extends AbstractXMLObject implements RequestSecurityTokenResponse { + + /** List of all the request security tokens. */ + private final XMLObjectChildrenList requestedSecurityTokens; + + /** Entity to whom the tokens apply. */ + private AppliesTo appliesTo; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + RequestSecurityTokenResponseImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + requestedSecurityTokens = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getRequestedSecurityToken() { + return requestedSecurityTokens; + } + + /** {@inheritDoc} */ + public AppliesTo getAppliesTo() { + return appliesTo; + } + + /** {@inheritDoc} */ + public void setAppliesTo(AppliesTo newappliesTo) { + this.appliesTo = prepareForAssignment(this.appliesTo, newappliesTo); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(1 + requestedSecurityTokens.size()); + + children.addAll(requestedSecurityTokens); + children.add(appliesTo); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestSecurityTokenResponseMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestSecurityTokenResponseMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestSecurityTokenResponseMarshaller.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.w3c.dom.Element; + +/** A thread safe marshaller for {@link org.opensaml.ws.wsfed.RequestSecurityTokenResponse} objects. */ +public class RequestSecurityTokenResponseMarshaller extends AbstractXMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject fedObject, Element domElement) { + + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject fedObject, Element domElement) { + + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestSecurityTokenResponseUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestSecurityTokenResponseUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestSecurityTokenResponseUnmarshaller.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.ws.wsfed.AppliesTo; +import org.opensaml.ws.wsfed.RequestSecurityTokenResponse; +import org.opensaml.ws.wsfed.RequestedSecurityToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.w3c.dom.Attr; + +/** A thread-safe unmarshaller for {@link RequestSecurityTokenResponse} objects. */ +public class RequestSecurityTokenResponseUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) { + RequestSecurityTokenResponse response = (RequestSecurityTokenResponse) parentSAMLObject; + + if (childSAMLObject instanceof RequestedSecurityToken) { + response.getRequestedSecurityToken().add((RequestedSecurityToken) childSAMLObject); + } else if (childSAMLObject instanceof AppliesTo) { + response.setAppliesTo((AppliesTo) childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject fedObject, Attr attribute) { + + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject fedObject, String content) { + + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestedSecurityTokenBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestedSecurityTokenBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestedSecurityTokenBuilder.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.ws.wsfed.RequestedSecurityToken; +import org.opensaml.ws.wsfed.WSFedConstants; +import org.opensaml.ws.wsfed.WSFedObjectBuilder; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** Builder of {@link RequestedSecurityTokenImpl} objects. */ +public class RequestedSecurityTokenBuilder extends AbstractXMLObjectBuilder implements + WSFedObjectBuilder { + + /** Constructor. */ + public RequestedSecurityTokenBuilder() { + + } + + /** {@inheritDoc} */ + public RequestedSecurityToken buildObject() { + return buildObject(WSFedConstants.WSFED11P_NS, RequestedSecurityToken.DEFAULT_ELEMENT_LOCAL_NAME, + WSFedConstants.WSFED1P_PREFIX); + } + + /** {@inheritDoc} */ + public RequestedSecurityToken buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestedSecurityTokenImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestedSecurityTokenImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestedSecurityTokenImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestedSecurityTokenImpl.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wsfed.RequestedSecurityToken; +import org.opensaml.xml.AbstractXMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Implementation of the {@link RequestedSecurityToken} object. */ +public class RequestedSecurityTokenImpl extends AbstractXMLObject implements RequestedSecurityToken { + + /** List of all the security tokens. */ + private final XMLObjectChildrenList tokens; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + public RequestedSecurityTokenImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + tokens = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getSecurityTokens() { + return tokens; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(1 + tokens.size()); + + children.addAll(tokens); + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestedSecurityTokenMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestedSecurityTokenMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestedSecurityTokenMarshaller.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.w3c.dom.Element; + +/** A thread safe marshaller for {@link org.opensaml.ws.wsfed.RequestedSecurityToken} objects. */ +public class RequestedSecurityTokenMarshaller extends AbstractXMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject fedObject, Element domElement) { + + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject fedObject, Element domElement) { + + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestedSecurityTokenUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestedSecurityTokenUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wsfed/impl/RequestedSecurityTokenUnmarshaller.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wsfed.impl; + +import org.opensaml.ws.wsfed.RequestedSecurityToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.w3c.dom.Attr; + +/** A thread-safe unmarshaller for {@link org.opensaml.ws.wsfed.RequestedSecurityToken} objects. */ +public class RequestedSecurityTokenUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) { + RequestedSecurityToken requestedSecurityToken = (RequestedSecurityToken) parentSAMLObject; + requestedSecurityToken.getSecurityTokens().add(childSAMLObject); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject fedObject, Attr attribute) { + + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject fedObject, String content) { + + } +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/All.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/All.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/All.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy; + +import javax.xml.namespace.QName; + +/** + * The wsp:All element. + * + * @see "WS-Policy (http://schemas.xmlsoap.org/ws/2004/09/policy)" + */ +public interface All extends OperatorContentType { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "All"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSPolicyConstants.WSP_NS, ELEMENT_LOCAL_NAME, WSPolicyConstants.WSP_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/AppliesTo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/AppliesTo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/AppliesTo.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The wsp:AppliesTo element. + * + * @see "WS-Policy (http://schemas.xmlsoap.org/ws/2004/09/policy)" + * + */ +public interface AppliesTo extends AttributeExtensibleXMLObject, ElementExtensibleXMLObject, WSPolicyObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME= "AppliesTo"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSPolicyConstants.WSP_NS, ELEMENT_LOCAL_NAME, WSPolicyConstants.WSP_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/ExactlyOne.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/ExactlyOne.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/ExactlyOne.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy; + +import javax.xml.namespace.QName; + +/** + * The wsp:ExactlyOne element. + * + * @see "WS-Policy (http://schemas.xmlsoap.org/ws/2004/09/policy)" + */ +public interface ExactlyOne extends OperatorContentType { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "ExactlyOne"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSPolicyConstants.WSP_NS, ELEMENT_LOCAL_NAME, WSPolicyConstants.WSP_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/OperatorContentType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/OperatorContentType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/OperatorContentType.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * The OperatorContentType complex type. + */ +public interface OperatorContentType extends WSPolicyObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "OperatorContentType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSPolicyConstants.WSP_NS, TYPE_LOCAL_NAME, WSPolicyConstants.WSP_PREFIX); + + /** + * Get the list of {@link Policy} elements. + * + * @return the list of {@link Policy} elements + */ + public List getPolicies(); + + /** + * Get the list of {@link All} elements. + * + * @return the list of {@link All} elements + */ + public List getAlls(); + + /** + * Get the list of {@link ExactlyOne} elements. + * + * @return the list of {@link ExactlyOne} elements + */ + public List getExactlyOnes(); + + /** + * Get the list of {@link PolicyReference} elements. + * + * @return the list of {@link PolicyReference} elements + */ + public List getPolicyReferences(); + + + /** + * Get the complete modifiable list of XMLObject children. + * + * @return the list of {@link XMLObject} instances + */ + public List getXMLObjects(); + + /** + * Get the modifiable sublist of XMLObject children which match the specified + * type or element name. + * + * @param typeOrName the element name or xsi:type + * + * @return the list of {@link XMLObject} instances + */ + public List getXMLObjects(QName typeOrName); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/OptionalBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/OptionalBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/OptionalBearing.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * Interface for element having a @wsp:Optional attribute. + */ +public interface OptionalBearing { + + /** The wsp:@Optional attribute local name. */ + public static final String WSP_OPTIONAL_ATTR_LOCAL_NAME = "Optional"; + + /** The wsp:@Optional qualified attribute name. */ + public static final QName WSP_OPTIONAL_ATTR_NAME = + new QName(WSPolicyConstants.WSP_NS, WSP_OPTIONAL_ATTR_LOCAL_NAME, WSPolicyConstants.WSP_PREFIX); + + /** + * Get the attribute value. + * + * @return return the attribute value + */ + public Boolean isWSP12Optional(); + + /** + * Get the attribute value. + * + * @return return the attribute value + */ + public XSBooleanValue isWSP12OptionalXSBoolean(); + + /** + * Set the attribute value. + * + * @param newOptional the new attribute value + */ + public void setWSP12Optional(Boolean newOptional); + + /** + * Set the attribute value. + * + * @param newOptional the new attribute value + */ + public void setWSP12Optional(XSBooleanValue newOptional); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/Policy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/Policy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/Policy.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.IdBearing; +import org.opensaml.xml.AttributeExtensibleXMLObject; + +/** + * The wsp:Policy element. + * + * @see "WS-Policy (http://schemas.xmlsoap.org/ws/2004/09/policy)" + * + */ +public interface Policy extends OperatorContentType, AttributeExtensibleXMLObject, IdBearing { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Policy"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSPolicyConstants.WSP_NS, ELEMENT_LOCAL_NAME, WSPolicyConstants.WSP_PREFIX); + + /** The wsp:Policy/@Name attribute local name. */ + public static final String NAME_ATTRIB_NAME = "Name"; + + /** + * Returns the wsp:Policy/@Name attribute value. + * + * @return the Name attribute value or null. + */ + public String getName(); + + /** + * Sets the wsp:Policy/@Name attribute value. + * + * @param name the Name attribute value to set. + */ + public void setName(String name); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/PolicyAttachment.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/PolicyAttachment.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/PolicyAttachment.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The wsp:PolicyAttachment element. + * + * @see "WS-Policy (http://schemas.xmlsoap.org/ws/2004/09/policy)" + */ +public interface PolicyAttachment extends WSPolicyObject, ElementExtensibleXMLObject, AttributeExtensibleXMLObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "PolicyAttachment"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSPolicyConstants.WSP_NS, ELEMENT_LOCAL_NAME, WSPolicyConstants.WSP_PREFIX); + + /** + * Get the AppliesTo child element. + * + * @return the child element + */ + public AppliesTo getAppliesTo(); + + /** + * Set the AppliesTo child element. + * + * @param newAppliesTo the new child element + */ + public void setAppliesTo(AppliesTo newAppliesTo); + + /** + * Get the list of Policy child elements. + * + * @return the list of child elements + */ + public List getPolicies(); + + /** + * Get the list of PolicyReference child elements. + * + * @return the list of child elements + */ + public List getPolicyReferences(); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/PolicyReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/PolicyReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/PolicyReference.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,93 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; + +/** + * The wsp:PolicyReference element. + * + * @see "WS-Policy (http://schemas.xmlsoap.org/ws/2004/09/policy)" + * + */ +public interface PolicyReference extends AttributeExtensibleXMLObject, WSPolicyObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "PolicyReference"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSPolicyConstants.WSP_NS, ELEMENT_LOCAL_NAME, WSPolicyConstants.WSP_PREFIX); + + /** The wsp:PolicyReference/@URI attribute local name. */ + public static final String URI_ATTRIB_NAME = "URI"; + + /** The wsp:PolicyReference/@Digest attribute local name. */ + public static final String DIGEST_ATTRIB_NAME = "Digest"; + + /** The wsp:PolicyReference/@Digest attribute local name. */ + public static final String DIGEST_ALGORITHM_ATTRIB_NAME = "DigestAlgorithm"; + + /** The default wsp:PolicyReference/@DigestAlgorithm attribute value. */ + public static final String DIGEST_ALGORITHM_SHA1EXC = WSPolicyConstants.WSP_NS + "/Sha1Exc"; + + /** + * Returns the wsp:PolicyReference/@URI attribute value. + * + * @return the URI attribute value. + */ + public String getURI(); + + /** + * Sets the wsp:PolicyReference/@URI attribute value. + * + * @param uri the URI attribute value to set. + */ + public void setURI(String uri); + + /** + * Returns the wsp:PolicyReference/@Digest attribute URI value. + * + * @return the Digest attribute URI value. + */ + public String getDigest(); + + /** + * Sets the wsp:PolicyReference/@Digest attribute URI value. + * + * @param digest the Digest attribute URI value to set. + */ + public void setDigest(String digest); + + /** + * Returns the wsp:PolicyReference/@DigestAlgoritm attribute Base64 binary value. + * + * @return the DigestAlgoritm attribute Base64 binary value. + */ + public String getDigestAlgorithm(); + + /** + * Sets the wsp:PolicyReference/@DigestAlgoritm attribute Base64 binary value. + * + * @param digestAlgorithm the DigestAlgoritm attribute Base64 binary value to set. + */ + public void setDigestAlgorithm(String digestAlgorithm); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/PolicyURIsBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/PolicyURIsBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/PolicyURIsBearing.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy; + +import java.util.List; + +import javax.xml.namespace.QName; + +/** + * Interface for element having a @wsp:PolicyURIs attribute. + */ +public interface PolicyURIsBearing { + + /** The wsp:@PolicyURIs attribute local name. */ + public static final String WSP_POLICY_URIS_ATTR_LOCAL_NAME = "PolicyURIs"; + + /** The wsp:@PolicyURIs qualified attribute name. */ + public static final QName WSP_POLICY_URIS_ATTR_NAME = + new QName(WSPolicyConstants.WSP_NS, WSP_POLICY_URIS_ATTR_LOCAL_NAME, WSPolicyConstants.WSP_PREFIX); + + /** + * Get the attribute value. + * + * @return return the list of attribute values + */ + public List getWSP12PolicyURIs(); + + /** + * Set the attribute value. + * + * @param newPolicyURIs the new list of attribute values + */ + public void setWSP12PolicyURIs(List newPolicyURIs); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/WSPolicyConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/WSPolicyConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/WSPolicyConstants.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy; + +/** + * WS-Policy 1.2 constants. + * + * @see "WS-Policy (http://schemas.xmlsoap.org/ws/2004/09/policy)" + * + */ +public final class WSPolicyConstants { + + /** WS-Policy namespace. */ + public static final String WSP_NS= "http://schemas.xmlsoap.org/ws/2004/09/policy"; + + /** WS-Policy namespace prefix. */ + public static final String WSP_PREFIX= "wsp"; + + /** Constructor. Private to prevent instantiation. */ + private WSPolicyConstants() { } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/WSPolicyObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/WSPolicyObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/WSPolicyObject.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy; + +import org.opensaml.xml.XMLObject; + +/** + * WSPolicyObject is the base interface for all WS-Policy elements. + * + */ +public interface WSPolicyObject extends XMLObject { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/WSPolicyObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/WSPolicyObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/WSPolicyObjectBuilder.java 17 Aug 2012 15:09:07 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy; + +import org.opensaml.xml.XMLObjectBuilder; + +/** + * WSPolicyObjectBuilder. + * + * @param the type of WS-Policy object being built + */ +public interface WSPolicyObjectBuilder + extends XMLObjectBuilder { + + /** + * Builds a WS-Policy object. + * + * @return the built object + */ + public WSPolicyObjectType buildObject(); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/package.html 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,10 @@ + + +

+XMLObject interfaces for WS-Policy 1.2 elements. +

+

+The Web Services Policy 1.2 - Framework defines a base set of constructs that can be used and extended by other Web services specifications to describe a broad range of service requirements and capabilities. +

+ + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AbstractWSPolicyObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AbstractWSPolicyObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AbstractWSPolicyObject.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.WSPolicyObject; +import org.opensaml.xml.validation.AbstractValidatingXMLObject; + +/** + * AbstractWSSecurityObject. + * + */ +public abstract class AbstractWSPolicyObject extends AbstractValidatingXMLObject implements WSPolicyObject { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public AbstractWSPolicyObject(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AbstractWSPolicyObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AbstractWSPolicyObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AbstractWSPolicyObjectBuilder.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + + +import org.opensaml.ws.wspolicy.WSPolicyObject; +import org.opensaml.ws.wspolicy.WSPolicyObjectBuilder; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * AbstactWSPolicyObjectBuilder. + * + * @param the type of object being built + */ +public abstract class AbstractWSPolicyObjectBuilder + extends AbstractXMLObjectBuilder implements WSPolicyObjectBuilder { + + /** {@inheritDoc} */ + public abstract T buildObject(); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AbstractWSPolicyObjectMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AbstractWSPolicyObjectMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AbstractWSPolicyObjectMarshaller.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * An abstract marshaller implementation for XMLObjects from {@link org.opensaml.ws.wssecurity}. + */ +public abstract class AbstractWSPolicyObjectMarshaller extends AbstractXMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AbstractWSPolicyObjectUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AbstractWSPolicyObjectUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AbstractWSPolicyObjectUnmarshaller.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; + +/** + * An abstract unmarshaller implementation for XMLObjects from {@link org.opensaml.ws.wspolicy}. + */ +public abstract class AbstractWSPolicyObjectUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** + * Logger. + */ + private final Logger log = LoggerFactory.getLogger(AbstractWSPolicyObjectUnmarshaller.class); + + /** Constructor. */ + protected AbstractWSPolicyObjectUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + log.warn("{} ignoring unknown child element {}", parentXMLObject.getElementQName().getLocalPart(), + childXMLObject.getElementQName().getLocalPart()); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + log.warn("{} ignoring unknown attribute {}", xmlObject.getElementQName().getLocalPart(), attribute + .getLocalName()); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + log.warn("{} ignoring unknown element content: {}", xmlObject.getElementQName().getLocalPart(), elementContent); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AllBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AllBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AllBuilder.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.All; + +/** + * Builder for the All element. + * + */ +public class AllBuilder extends AbstractWSPolicyObjectBuilder { + + /** {@inheritDoc} */ + public All buildObject() { + return buildObject(All.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public All buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AllImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AllImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AllImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AllImpl.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.All; + +/** + * AllImpl. + * + */ +public class AllImpl extends OperatorContentTypeImpl implements All { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + protected AllImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AllMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AllMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AllMarshaller.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + + + +/** + * Marshaller for the wsp:All element. + * + */ +public class AllMarshaller extends OperatorContentTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AllUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AllUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AllUnmarshaller.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + + +/** + * Unmarshaller for the wsp:All element. + * + */ +public class AllUnmarshaller extends OperatorContentTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AppliesToBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AppliesToBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AppliesToBuilder.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.AppliesTo; + +/** + * Builder for the AppliesTo element. + * + */ +public class AppliesToBuilder extends AbstractWSPolicyObjectBuilder { + + /** {@inheritDoc} */ + public AppliesTo buildObject() { + return buildObject(AppliesTo.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public AppliesTo buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AppliesToImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AppliesToImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AppliesToImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AppliesToImpl.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wspolicy.AppliesTo; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * AppliesToImpl. + * + */ +public class AppliesToImpl extends AbstractWSPolicyObject implements AppliesTo { + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + protected AppliesToImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + children.addAll(unknownChildren); + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AppliesToMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AppliesToMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AppliesToMarshaller.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.AppliesTo; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + + +/** + * Marshaller for the wsp:AppliesTo element. + * + */ +public class AppliesToMarshaller extends AbstractWSPolicyObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + AppliesTo at = (AppliesTo) xmlObject; + XMLHelper.marshallAttributeMap(at.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AppliesToUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AppliesToUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/AppliesToUnmarshaller.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.AppliesTo; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for the wsp:AppliesTo element. + * + */ +public class AppliesToUnmarshaller extends AbstractWSPolicyObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + AppliesTo at = (AppliesTo) xmlObject; + XMLHelper.unmarshallToAttributeMap(at.getUnknownAttributes(), attribute); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + AppliesTo at = (AppliesTo) parentXMLObject; + at.getUnknownXMLObjects().add(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/ExactlyOneBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/ExactlyOneBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/ExactlyOneBuilder.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.ExactlyOne; + +/** + * Builder for the ExactlyOne element. + * + */ +public class ExactlyOneBuilder extends AbstractWSPolicyObjectBuilder { + + /** {@inheritDoc} */ + public ExactlyOne buildObject() { + return buildObject(ExactlyOne.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ExactlyOne buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ExactlyOneImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/ExactlyOneImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/ExactlyOneImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/ExactlyOneImpl.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.ExactlyOne; + +/** + * ExactlyOneImpl. + * + */ +public class ExactlyOneImpl extends OperatorContentTypeImpl implements ExactlyOne { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + protected ExactlyOneImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/ExactlyOneMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/ExactlyOneMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/ExactlyOneMarshaller.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + + + +/** + * Marshaller for the wsp:ExactlyOne element. + * + */ +public class ExactlyOneMarshaller extends OperatorContentTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/ExactlyOneUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/ExactlyOneUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/ExactlyOneUnmarshaller.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + + +/** + * Unmarshaller for the wsp:ExactlyOne element. + * + */ +public class ExactlyOneUnmarshaller extends OperatorContentTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/OperatorContentTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/OperatorContentTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/OperatorContentTypeImpl.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,91 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wspolicy.All; +import org.opensaml.ws.wspolicy.ExactlyOne; +import org.opensaml.ws.wspolicy.OperatorContentType; +import org.opensaml.ws.wspolicy.Policy; +import org.opensaml.ws.wspolicy.PolicyReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * OperatorContentTypeImpl. + */ +public class OperatorContentTypeImpl extends AbstractWSPolicyObject implements OperatorContentType { + + /** All child elements. */ + private IndexedXMLObjectChildrenList xmlObjects; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public OperatorContentTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + xmlObjects = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAlls() { + return (List) xmlObjects.subList(All.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getExactlyOnes() { + return (List) xmlObjects.subList(ExactlyOne.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getPolicies() { + return (List) xmlObjects.subList(Policy.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getPolicyReferences() { + return (List) xmlObjects.subList(PolicyReference.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getXMLObjects() { + return xmlObjects; + } + + /** {@inheritDoc} */ + public List getXMLObjects(QName typeOrName) { + return (List) xmlObjects.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + children.addAll(xmlObjects); + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/OperatorContentTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/OperatorContentTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/OperatorContentTypeMarshaller.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +/** + * Marshaller for the wsp:OperatorContentType element. + */ +public class OperatorContentTypeMarshaller extends AbstractWSPolicyObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/OperatorContentTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/OperatorContentTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/OperatorContentTypeUnmarshaller.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.OperatorContentType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for the wsp:OperatorContentType element. + */ +public class OperatorContentTypeUnmarshaller extends AbstractWSPolicyObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + OperatorContentType oct = (OperatorContentType) parentXMLObject; + oct.getXMLObjects().add(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyAttachmentBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyAttachmentBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyAttachmentBuilder.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.PolicyAttachment; + +/** + * Builder for the PolicyAttachment element. + * + */ +public class PolicyAttachmentBuilder extends AbstractWSPolicyObjectBuilder { + + /** {@inheritDoc} */ + public PolicyAttachment buildObject() { + return buildObject(PolicyAttachment.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public PolicyAttachment buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new PolicyAttachmentImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyAttachmentImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyAttachmentImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyAttachmentImpl.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,111 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wspolicy.AppliesTo; +import org.opensaml.ws.wspolicy.Policy; +import org.opensaml.ws.wspolicy.PolicyAttachment; +import org.opensaml.ws.wspolicy.PolicyReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * PolicyAttachmentImpl. + */ +public class PolicyAttachmentImpl extends AbstractWSPolicyObject implements PolicyAttachment { + + /** AppliesTo Child element. */ + private AppliesTo appliesTo; + + /** Policy and PolicyReference children. */ + private IndexedXMLObjectChildrenList policiesAndReferences; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public PolicyAttachmentImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + policiesAndReferences = new IndexedXMLObjectChildrenList(this); + unknownChildren = new IndexedXMLObjectChildrenList(this); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public AppliesTo getAppliesTo() { + return appliesTo; + } + + /** {@inheritDoc} */ + public void setAppliesTo(AppliesTo newAppliesTo) { + appliesTo = prepareForAssignment(appliesTo, newAppliesTo); + } + + /** {@inheritDoc} */ + public List getPolicies() { + return (List) policiesAndReferences.subList(Policy.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getPolicyReferences() { + return (List) policiesAndReferences.subList(PolicyReference.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (appliesTo != null) { + children.add(appliesTo); + } + children.addAll(policiesAndReferences); + children.addAll(unknownChildren); + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyAttachmentMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyAttachmentMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyAttachmentMarshaller.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.PolicyAttachment; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for PolicyAttachment. + */ +public class PolicyAttachmentMarshaller extends AbstractWSPolicyObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + PolicyAttachment pa = (PolicyAttachment) xmlObject; + XMLHelper.marshallAttributeMap(pa.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyAttachmentUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyAttachmentUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyAttachmentUnmarshaller.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.AppliesTo; +import org.opensaml.ws.wspolicy.Policy; +import org.opensaml.ws.wspolicy.PolicyAttachment; +import org.opensaml.ws.wspolicy.PolicyReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for PolicyAttachment. + */ +public class PolicyAttachmentUnmarshaller extends AbstractWSPolicyObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + PolicyAttachment pa = (PolicyAttachment) xmlObject; + XMLHelper.unmarshallToAttributeMap(pa.getUnknownAttributes(), attribute); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + PolicyAttachment pa = (PolicyAttachment) parentXMLObject; + + if (childXMLObject instanceof AppliesTo) { + pa.setAppliesTo((AppliesTo) childXMLObject); + } else if (childXMLObject instanceof Policy) { + pa.getPolicies().add((Policy) childXMLObject); + } else if (childXMLObject instanceof PolicyReference) { + pa.getPolicyReferences().add((PolicyReference) childXMLObject); + } else { + pa.getUnknownXMLObjects().add(childXMLObject); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyBuilder.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.Policy; + +/** + * Builder for the Policy element. + * + */ +public class PolicyBuilder extends AbstractWSPolicyObjectBuilder { + + /** {@inheritDoc} */ + public Policy buildObject() { + return buildObject(Policy.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Policy buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new PolicyImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyImpl.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.Policy; +import org.opensaml.ws.wssecurity.IdBearing; +import org.opensaml.xml.util.AttributeMap; + +/** + * PolicyImpl. + * + */ +public class PolicyImpl extends OperatorContentTypeImpl implements Policy { + + /** The wsu:Id attribute value. */ + private String id; + + /** The Name attribute value. */ + private String name; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + protected PolicyImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + } + + + /** {@inheritDoc} */ + public String getName() { + return name; + } + + /** {@inheritDoc} */ + public void setName(String newName) { + name = prepareForAssignment(name, newName); + } + + /** {@inheritDoc} */ + public String getWSUId() { + return id; + } + + /** {@inheritDoc} */ + public void setWSUId(String newId) { + String oldId = id; + id = prepareForAssignment(id, newId); + registerOwnID(oldId, id); + manageQualifiedAttributeNamespace(IdBearing.WSU_ID_ATTR_NAME, id != null); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyMarshaller.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.Policy; +import org.opensaml.ws.wssecurity.IdBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + + +/** + * Marshaller for the wsp:Policy element. + * + */ +public class PolicyMarshaller extends OperatorContentTypeMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Policy policy = (Policy) xmlObject; + + if (policy.getName() != null) { + domElement.setAttributeNS(null, Policy.NAME_ATTRIB_NAME, policy.getName()); + } + + if (policy.getWSUId() != null) { + XMLHelper.marshallAttribute(IdBearing.WSU_ID_ATTR_NAME, policy.getWSUId(), domElement, true); + } + + XMLHelper.marshallAttributeMap(policy.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyReferenceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyReferenceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyReferenceBuilder.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.PolicyReference; + +/** + * Builder for the PolicyReference element. + * + */ +public class PolicyReferenceBuilder extends AbstractWSPolicyObjectBuilder { + + /** {@inheritDoc} */ + public PolicyReference buildObject() { + return buildObject(PolicyReference.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public PolicyReference buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new PolicyReferenceImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyReferenceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyReferenceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyReferenceImpl.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,96 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import java.util.List; + +import org.opensaml.ws.wspolicy.PolicyReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; + +/** + * PolicyReferenceImpl. + * + */ +public class PolicyReferenceImpl extends AbstractWSPolicyObject implements PolicyReference { + + /** URI attribute value. */ + private String uri; + + /** Digest attribute value. */ + private String digest; + + /** DigestAlgorithm attribute value. */ + private String digestAlgorithm; + + /** xs:anyAttribute attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public PolicyReferenceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public String getDigest() { + return digest; + } + + /** {@inheritDoc} */ + public String getDigestAlgorithm() { + return digestAlgorithm; + } + + /** {@inheritDoc} */ + public String getURI() { + return uri; + } + + /** {@inheritDoc} */ + public void setDigest(String newDigest) { + digest = prepareForAssignment(digest, newDigest); + } + + /** {@inheritDoc} */ + public void setDigestAlgorithm(String newDigestAlgorithm) { + digestAlgorithm = prepareForAssignment(digestAlgorithm, newDigestAlgorithm); + } + + /** {@inheritDoc} */ + public void setURI(String newURI) { + uri = prepareForAssignment(uri, newURI); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyReferenceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyReferenceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyReferenceMarshaller.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import org.opensaml.ws.wspolicy.PolicyReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for the wsp:PolicyReference element. + * + */ +public class PolicyReferenceMarshaller extends AbstractWSPolicyObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + PolicyReference pr = (PolicyReference) xmlObject; + + if (pr.getURI() != null) { + domElement.setAttributeNS(null, PolicyReference.URI_ATTRIB_NAME, pr.getURI()); + } + + if (pr.getDigest() != null) { + domElement.setAttributeNS(null, PolicyReference.DIGEST_ATTRIB_NAME, pr.getDigest()); + } + + if (pr.getDigestAlgorithm() != null) { + domElement.setAttributeNS(null, PolicyReference.DIGEST_ALGORITHM_ATTRIB_NAME, pr.getDigestAlgorithm()); + } + + XMLHelper.marshallAttributeMap(pr.getUnknownAttributes(), domElement); + + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyReferenceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyReferenceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyReferenceUnmarshaller.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wspolicy.PolicyReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for the wsp:PolicyReference element. + * + */ +public class PolicyReferenceUnmarshaller extends AbstractWSPolicyObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + PolicyReference pr = (PolicyReference) xmlObject; + + QName uriName = new QName(PolicyReference.URI_ATTRIB_NAME); + QName digestName = new QName(PolicyReference.DIGEST_ATTRIB_NAME); + QName digestAlgorithmName = new QName(PolicyReference.DIGEST_ALGORITHM_ATTRIB_NAME); + + QName attribQName = + XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute .getPrefix()); + + if (uriName.equals(attribQName)) { + pr.setURI(attribute.getValue()); + } else if (digestName.equals(attribQName)) { + pr.setDigest(attribute.getValue()); + } else if (digestAlgorithmName.equals(attribQName)) { + pr.setDigestAlgorithm(attribute.getValue()); + } else { + XMLHelper.unmarshallToAttributeMap(pr.getUnknownAttributes(), attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wspolicy/impl/PolicyUnmarshaller.java 17 Aug 2012 15:09:06 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wspolicy.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wspolicy.Policy; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + + + +/** + * Unmarshaller for the wsp:Policy element. + * + */ +public class PolicyUnmarshaller extends OperatorContentTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Policy policy = (Policy) xmlObject; + + QName nameQName = new QName(Policy.NAME_ATTRIB_NAME); + + QName attribQName = + XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute.getPrefix()); + + if (nameQName.equals(attribQName)) { + policy.setName(attribute.getValue()); + } else if (Policy.WSU_ID_ATTR_NAME.equals(attribQName)) { + policy.setWSUId(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else { + XMLHelper.unmarshallToAttributeMap(policy.getUnknownAttributes(), attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/AttributedDateTime.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/AttributedDateTime.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/AttributedDateTime.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,86 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.joda.time.format.DateTimeFormatter; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.schema.XSString; + +/** + * Interface for elements of complex type AttributedDateTime. + * + */ +public interface AttributedDateTime extends XSString, IdBearing, AttributeExtensibleXMLObject, WSSecurityObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AttributedDateTime"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSU_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSU_PREFIX); + + /** Default DateTime format. + * + * @deprecated replaced by use of a {@link DateTimeFormatter} + * configured via {@link #setDateTimeFormatter(DateTimeFormatter)}. + * + * */ + public static final String DEFAULT_DATETIME_FORMAT= "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; + + /** + * Returns the DateTime content or attribute value. + * + * @return the {@link DateTime} object. + */ + public DateTime getDateTime(); + + /** + * Sets the DateTime content or attribute value. + * + * @param dateTime + * the {@link DateTime} object to set. + */ + public void setDateTime(DateTime dateTime); + + /** + * Get the {@link DateTimeFormatter} to be used when stringifying + * the {@link DateTime} value. + * + *

Defaults to the formatter constructed by calling: + * org.joda.time.format.ISODateTimeFormat.dateTime().withChronology(org.joda.time.chrono.ISOChronology.getInstanceUTC() + *

+ * + * @return the currently configured formatter + */ + public DateTimeFormatter getDateTimeFormatter(); + + /** + * Set the {@link DateTimeFormatter} to be used when stringifying + * the {@link DateTime} value. + * + *

Defaults to the formatter constructed by calling: + * org.joda.time.format.ISODateTimeFormat.dateTime().withChronology(org.joda.time.chrono.ISOChronology.getInstanceUTC() + *

+ * + * @param newFormatter the new formatter + */ + public void setDateTimeFormatter(DateTimeFormatter newFormatter); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/AttributedString.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/AttributedString.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/AttributedString.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.schema.XSString; + +/** + * Interface for elements of complex type AttributedString. + */ +public interface AttributedString extends XSString, IdBearing, AttributeExtensibleXMLObject, WSSecurityObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AttributedString"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSSE_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/AttributedURI.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/AttributedURI.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/AttributedURI.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.schema.XSURI; + +/** + * Interface for elements of complex type AttributedURI. + */ +public interface AttributedURI extends XSURI, IdBearing, AttributeExtensibleXMLObject, WSSecurityObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AttributedURI"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSU_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSU_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/BinarySecurityToken.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/BinarySecurityToken.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/BinarySecurityToken.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +/** + * The <wsse:BinarySecurityToken> element. + */ +public interface BinarySecurityToken extends EncodedString { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "BinarySecurityToken"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "BinarySecurityTokenType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSSE_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** The ValueType attribute name. */ + public static final String VALUE_TYPE_ATTRIB_NAME = "ValueType"; + + /** + * Returns the ValueType attribute URI value. + * + * @return the ValueType attribute value or null. + */ + public String getValueType(); + + /** + * Sets the ValueType attribute URI value. + * + * @param newValueType the ValueType attribute value. + */ + public void setValueType(String newValueType); + + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Created.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/Created.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Created.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +/** + * The <wsu:Created> element. + * + */ +public interface Created extends AttributedDateTime { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Created"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSU_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSU_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Embedded.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/Embedded.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Embedded.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * the <wsse:Embedded> element. + * + */ +public interface Embedded extends AttributeExtensibleXMLObject, ElementExtensibleXMLObject, WSSecurityObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Embedded"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "EmbeddedType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSSE_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** The wsse:Embedded/@ValueType attribute local name. */ + public static final String VALUE_TYPE_ATTRIB_NAME= "ValueType"; + + /** + * Returns the ValueType attribute URI value. + * + * @return the ValueType attribute value or null. + */ + public String getValueType(); + + /** + * Sets the ValueType attribute URI value. + * + * @param newValueType the ValueType attribute value. + */ + public void setValueType(String newValueType); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/EncodedString.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/EncodedString.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/EncodedString.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +/** + * Interface for elements of complex type EncodedString. + */ +public interface EncodedString extends AttributedString { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "EncodedString"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSSE_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** The EncodingType attribute name. */ + public static final String ENCODING_TYPE_ATTRIB_NAME = "EncodingType"; + + /** The EncodingType attribute value #Base64Binary. */ + public static final String ENCODING_TYPE_BASE64_BINARY = WSSecurityConstants.WS_SECURITY_NS + "#Base64Binary"; + + /** + * Returns the EncodingType attribute value. + * + * @return the EncodingType attribute value. + */ + public String getEncodingType(); + + /** + * Sets the EncodingType attribute value. + * + * @param newEncodingType the EncodingType attribute value. + */ + public void setEncodingType(String newEncodingType); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/EncryptedHeader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/EncryptedHeader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/EncryptedHeader.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.soap.soap11.ActorBearing; +import org.opensaml.ws.soap.soap11.MustUnderstandBearing; +import org.opensaml.ws.soap.soap12.RelayBearing; +import org.opensaml.ws.soap.soap12.RoleBearing; +import org.opensaml.xml.encryption.EncryptedData; + +/** + * The <wsse:EncryptedHeader> element. + * + * @see EncryptedHeader + * @see "WS-Security, Chapter 9.3 EncryptedHeader" + * + */ +public interface EncryptedHeader extends IdBearing, MustUnderstandBearing, ActorBearing, + org.opensaml.ws.soap.soap12.MustUnderstandBearing, RoleBearing, RelayBearing, WSSecurityObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "EncryptedHeader"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE11_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE11_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "EncryptedHeaderType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSSE11_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSSE11_PREFIX); + + /** + * Gets the EncryptedData child element. + * + * @return the EncryptedData child element + */ + public EncryptedData getEncryptedData(); + + /** + * Sets the EncryptedData child element. + * + * @param newEncryptedData the new EncryptedData child element + */ + public void setEncryptedData(EncryptedData newEncryptedData); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Expires.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/Expires.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Expires.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +/** + * The <wsu:Expires> element. + * + */ +public interface Expires extends AttributedDateTime { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Expires"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSU_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSU_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/IdBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/IdBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/IdBearing.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +/** + * Interface for element having a @wsu:Id attribute. + * + */ +public interface IdBearing { + + /** the Id attribute local name. */ + public static final String WSU_ID_ATTR_LOCAL_NAME = "Id"; + + /** the wsu:Id qualified attribute name. */ + public static final QName WSU_ID_ATTR_NAME = + new QName(WSSecurityConstants.WSU_NS, WSU_ID_ATTR_LOCAL_NAME, WSSecurityConstants.WSU_PREFIX); + + /** + * Returns the @wsu:Id attribute value. + * + * @return The @wsu:Id attribute value or null. + */ + public String getWSUId(); + + /** + * Sets the @wsu:Id attribute value. + * + * @param newId The @wsu:Id attribute value + */ + public void setWSUId(String newId); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Iteration.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/Iteration.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Iteration.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSInteger; +import org.opensaml.xml.util.XMLConstants; + +/** + * The <wsse11:Iteration> element within a <wsse:UsernameToken> + * element. + * + * @see "WS-Security UsernameToken Profile 1.1, 4. Key Derivation." + * + */ +public interface Iteration extends XSInteger, WSSecurityObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Iteration"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE11_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE11_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "unsignedInt"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XMLConstants.XSD_NS, TYPE_LOCAL_NAME, XMLConstants.XSD_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/KeyIdentifier.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/KeyIdentifier.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/KeyIdentifier.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +/** + * The <wsse:KeyIdentifier> element. + * + * @see SecurityTokenReference + * @see "WS-Security, Chapter 7.3 Key Identifiers." + * + */ +public interface KeyIdentifier extends EncodedString { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "KeyIdentifier"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "KeyIdentifierType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSSE_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** The ValueType attribute name. */ + public static final String VALUE_TYPE_ATTRIB_NAME = "ValueType"; + + /** + * Returns the ValueType attribute URI value. + * + * @return the ValueType attribute value or null. + */ + public String getValueType(); + + /** + * Sets the ValueType attribute URI value. + * + * @param newValueType the ValueType attribute value. + */ + public void setValueType(String newValueType); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Nonce.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/Nonce.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Nonce.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +/** + * The <wsse:Nonce> element within a <wsse:UsernameToken> element. + * + * @see "WS-Security UsernameToken Profile 1.1, 4. Key Derivation." + * + */ +public interface Nonce extends EncodedString { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Nonce"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Password.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/Password.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Password.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +/** + * The Password element. + * + * @see "WS-Security UsernameToken Profile 1.1" + * + */ +public interface Password extends AttributedString { + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Password"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** The Type attribute local name. */ + public static final String TYPE_ATTRIB_NAME = "Type"; + + /** + * The wsse:Password/@Type attribute URI value #PasswordText (DEFAULT). + */ + public static final String TYPE_PASSWORD_TEXT = WSSecurityConstants.WSSE_NS + "#PasswordText"; + + /** + * The wsse:Password/@Type attribute URI value #PasswordDigest. + */ + public static final String TYPE_PASSWORD_DIGEST = WSSecurityConstants.WSSE_NS + "#PasswordDigest"; + + /** + * Returns the wsse:Password/@Type attribute URI value. + * + * @return the Type attribute URI value. + */ + public String getType(); + + /** + * Sets the wsse:Password/@Type attribute URI value. + * + * @param type the Type attribute URI value to set. + */ + public void setType(String type); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Reference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/Reference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Reference.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; + +/** + * The <wsse:Reference> empty element. + * + * @see "WS-Security 2004, Chapter 7.2" + * + */ +public interface Reference extends AttributeExtensibleXMLObject, WSSecurityObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Reference"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ReferenceType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSSE_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** The wsse:Reference/@URI attribute local name. */ + public static final String URI_ATTRIB_NAME= "URI"; + + /** The wsse:Reference/@ValueType attribute local name. */ + public static final String VALUE_TYPE_ATTRIB_NAME= "ValueType"; + + /** + * Returns the wsse:Reference/@URI attribute value. + * + * @return the URI attribute value. + */ + public String getURI(); + + /** + * Sets the wsse:Reference/@URI attribute value. + * + * @param newURI the URI to set. + */ + public void setURI(String newURI); + + /** + * Returns the ValueType attribute URI value. + * + * @return the ValueType attribute value or null. + */ + public String getValueType(); + + /** + * Sets the ValueType attribute URI value. + * + * @param newValueType the ValueType attribute value. + */ + public void setValueType(String newValueType); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Salt.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/Salt.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Salt.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSBase64Binary; + +/** + * The <wsse11:Salt> element within the <wsse:UsernameToken> + * element. + * + * @see "WS-Security UsernameToken Profile 1.1, 4. Key Derivation." + * + */ +public interface Salt extends XSBase64Binary, WSSecurityObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Salt"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE11_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE11_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Security.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/Security.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Security.java 17 Aug 2012 15:09:05 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The <wsse:Security> header block. + * + * @see "WS-Security 2004, Chapter 5 Security Header." + * + */ +public interface Security extends AttributeExtensibleXMLObject, ElementExtensibleXMLObject, WSSecurityObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Security"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "SecurityHeaderType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSSE_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/SecurityTokenReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/SecurityTokenReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/SecurityTokenReference.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The <wsse:SecurityTokenReference> element. + * + * @see "WS-Security 2004, Chapter 7. Token References." + * + * + */ +public interface SecurityTokenReference extends IdBearing, UsageBearing, AttributeExtensibleXMLObject, + ElementExtensibleXMLObject, WSSecurityObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "SecurityTokenReference"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "SecurityTokenReferenceType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSSE_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/SignatureConfirmation.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/SignatureConfirmation.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/SignatureConfirmation.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +/** + * The <wsse11:SignatureConfirmation> element. + */ +public interface SignatureConfirmation extends IdBearing, WSSecurityObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "SignatureConfirmation"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE11_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE11_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "SignatureConfirmationType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSSE11_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSSE11_PREFIX); + + /** The Value attribute name. */ + public static final String VALUE_ATTRIB_NAME = "Value"; + + /** + * Returns the Value attribute value. + * + * @return the Value attribute value or null. + */ + public String getValue(); + + /** + * Sets the Value attribute value. + * + * @param newValue the Value attribute value. + */ + public void setValue(String newValue); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Timestamp.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/Timestamp.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Timestamp.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The <wsu:Timestamp> element. + * + * @see Created + * @see Expires + * + */ +public interface Timestamp extends IdBearing, AttributeExtensibleXMLObject, + ElementExtensibleXMLObject, WSSecurityObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Timestamp"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSU_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSU_PREFIX); + + /** + * Returns the <wsu:Created< child element. + * + * @return the {@link Created} child element or null. + */ + public Created getCreated(); + + /** + * Sets the <wsu:Created> child element. + * + * @param created + * the {@link Created} child element to set. + */ + public void setCreated(Created created); + + /** + * Returns the <wsu:Expires> child element. + * + * @return the {@link Expires} child element or null. + */ + public Expires getExpires(); + + /** + * Sets the <wsu:Expires> child element. + * + * @param expires + * the {@link Expires} child element or null. + */ + public void setExpires(Expires expires); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/TokenTypeBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/TokenTypeBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/TokenTypeBearing.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +/** + * Interface for element having a @wsse11:TokenType; attribute. + * + * @see "WS-Security 2004, Chapter 7.1 SecurityTokenReference Element." + * + */ +public interface TokenTypeBearing { + + /** + * The @wsse11:TokenType attribute local name. + */ + public static final String WSSE11_TOKEN_TYPE_ATTR_LOCAL_NAME = "TokenType"; + + /** + * The @wsse11:TokenType qualified attribute name. + */ + public static final QName WSSE11_TOKEN_TYPE_ATTR_NAME = + new QName(WSSecurityConstants.WSSE11_NS, WSSE11_TOKEN_TYPE_ATTR_LOCAL_NAME, WSSecurityConstants.WSSE11_PREFIX); + + /** + * Returns the @wsse11:TokenType attribute value. + * + * @return the @wsse11:TokenType attribute value or null. + */ + public String getWSSE11TokenType(); + + /** + * Sets the @wsse11:TokenType attribute value. + * + * @param tokenType the @wsse11:TokenType attribute value to set. + */ + public void setWSSE11TokenType(String tokenType); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/TransformationParameters.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/TransformationParameters.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/TransformationParameters.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The <wsse:TransformationParameters> element. + * + */ +public interface TransformationParameters extends AttributeExtensibleXMLObject, ElementExtensibleXMLObject, WSSecurityObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "TransformationParameters"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "TransformationParametersType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSSE_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/UsageBearing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/UsageBearing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/UsageBearing.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import java.util.List; + +import javax.xml.namespace.QName; + +/** + * Interface for element having a @wsse:Usage attribute. + */ +public interface UsageBearing { + + /** The wsse:@Usage attribute local name. */ + public static final String WSSE_USAGE_ATTR_LOCAL_NAME = "Usage"; + + /** The wsse:@Usage qualified attribute name. */ + public static final QName WSSE_USAGE_ATTR_NAME = + new QName(WSSecurityConstants.WSSE_NS, WSSE_USAGE_ATTR_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** + * Returns the list of wsse:@Usage attributes value. + * + * @return the list of attribute values + */ + public List getWSSEUsages(); + + /** + * Sets the list of wsse:@Usage attributes value. + * + * @param usages the list of attribute values + */ + public void setWSSEUsages(List usages); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Username.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/Username.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/Username.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +/** + * The <wsse:Username> element within the <wsse:UsernameToken> + * element. + * + * @see "WS-Security UsernameToken Profile 1.1" + * + */ +public interface Username extends AttributedString { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Username"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/UsernameToken.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/UsernameToken.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/UsernameToken.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The <wsse:UsernameToken> element. + * + * @see "WS-Security UsernameToken Profile 1.1" + * + */ +public interface UsernameToken extends IdBearing, AttributeExtensibleXMLObject, + ElementExtensibleXMLObject, WSSecurityObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "UsernameToken"; + + /** Qualified element name. */ + public static final QName ELEMENT_NAME = + new QName(WSSecurityConstants.WSSE_NS, ELEMENT_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "UsernameTokenType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSSecurityConstants.WSSE_NS, TYPE_LOCAL_NAME, WSSecurityConstants.WSSE_PREFIX); + + /** + * Returns the <wsse:Username> child element. + * + * @return the {@link Username} child element. + */ + public Username getUsername(); + + /** + * Sets the <wsse:Username> child element. + * + * @param username + * the {@link Username} child element to set. + */ + public void setUsername(Username username); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/WSSecurityConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/WSSecurityConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/WSSecurityConstants.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,171 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import javax.xml.namespace.QName; + +/** + * Constants for the WS-Security 2004. + * + * @see "WS-Security 2004 Specification" + * + */ +public final class WSSecurityConstants { + + // Namespaces and prefixes. + + /** WS-Security SOAP Message Security 1.0 namespace. */ + public static final String WS_SECURITY_NS = + "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0"; + + /** WS-Security SOAP Message Security 1.1 namespace. */ + public static final String WS_SECURITY11_NS = + "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1"; + + /** WS-Security Utility 1.0 namespace. */ + public static final String WSU_NS = + "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"; + + /** WS-Security Utility 1.0 prefix. */ + public static final String WSU_PREFIX = "wsu"; + + /** WS-Security Security Extension 1.0 namespace. */ + public static final String WSSE_NS = + "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; + + /** WS-Security Security Extension 1.0 prefix. */ + public static final String WSSE_PREFIX = "wsse"; + + /** WS-Security Security Extension 1.1 namespace. */ + public static final String WSSE11_NS = + "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd"; + + /** WS-Security Security Extension 1.1 prefix. */ + public static final String WSSE11_PREFIX = "wsse11"; + + /** WS-Security SAML Token Profile 1.0 namespace. */ + public static final String WSSE_SAML_TOKEN_PROFILE_NS = + "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0"; + + /** WS-Security SAML Token Profile 1.1 namespace. */ + public static final String WSSE11_SAML_TOKEN_PROFILE_NS = + "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1"; + + /** WS-Security Username Token Profile 1.0 namespace. */ + public static final String WSSE_USERNAME_TOKEN_PROFILE_NS = + "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0"; + + /** WS-Security X509 Token Profile 1.0 namespace. */ + public static final String WSSE_X509_TOKEN_PROFILE_NS = + "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0"; + + /** WS-Security Kerberos Token Profile 1.1 namespace. */ + public static final String WSSE_KERBEROS_TOKEN_PROFILE_NS = + "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1"; + + // SOAP fault codes. + + /** WS-Security SOAP fault code: SOAP"wsse:UnsupportedSecurityToken". */ + public static final QName SOAP_FAULT_UNSUPPORTED_SECURITY_TOKEN = + new QName(WSSE_NS, "UnsupportedSecurityToken", WSSE_PREFIX); + + /** WS-Security SOAP fault code: "wsse:UnsupportedAlgorithm". */ + public static final QName SOAP_FAULT_UNSUPPORTED_ALGORITHM = + new QName(WSSE_NS, "UnsupportedAlgorithm", WSSE_PREFIX); + + /** WS-Security SOAP fault code: "wsse:InvalidSecurity". */ + public static final QName SOAP_FAULT_INVALID_SECURITY = + new QName(WSSE_NS, "InvalidSecurity", WSSE_PREFIX); + + /** WS-Security SOAP fault code: "wsse:InvalidSecurityToken". */ + public static final QName SOAP_FAULT_INVALID_SECURITY_TOKEN = + new QName(WSSE_NS, "InvalidSecurityToken", WSSE_PREFIX); + + /** WS-Security SOAP fault code: "wsse:FailedAuthentication". */ + public static final QName SOAP_FAULT_FAILED_AUTHENTICATION = + new QName(WSSE_NS, "FailedAuthentication", WSSE_PREFIX); + + /** WS-Security SOAP fault code: "wsse:FailedCheck". */ + public static final QName SOAP_FAULT_FAILED_CHECK = + new QName(WSSE_NS, "FailedCheck", WSSE_PREFIX); + + /** WS-Security SOAP fault code: "wsse:SecurityTokenUnavailable". */ + public static final QName SOAP_FAULT_SECURITY_TOKEN_UNAVAILABLE = + new QName(WSSE_NS, "SecurityTokenUnavailable", WSSE_PREFIX); + + /** WS-Security SOAP fault code: "wsu:MessageExpired". */ + public static final QName SOAP_FAULT_MESSAGE_EXPIRED = + new QName(WSU_NS, "MessageExpired", WSU_PREFIX); + + // Other constants + + /** WS-Security - Username Token Profile - UsernameToken. */ + public static final String USERNAME_TOKEN = + WSSE_USERNAME_TOKEN_PROFILE_NS + "#UsernameToken"; + + /** WS-Security - X.509 Token Profile - X509V3. */ + public static final String X509_V3 = + WSSE_X509_TOKEN_PROFILE_NS + "#X509v3"; + + /** WS-Security - X.509 Token Profile - X509V1. */ + public static final String X509_V1 = + WSSE_X509_TOKEN_PROFILE_NS + "#X509v1"; + + /** WS-Security - X.509 Token Profile - X509PKIPathv1. */ + public static final String X509_PKI_PATH_V1 = + WSSE_X509_TOKEN_PROFILE_NS + "#X509PKIPathv1"; + + /** WS-Security - X.509 Token Profile - PKCS7. */ + public static final String X509_PKCS7 = + WSSE_X509_TOKEN_PROFILE_NS + "#PKCS7"; + + /** WS-Security - X.509 Token Profile - X509SubjectKeyIdentifier. */ + public static final String X509_SUBJECT_KEY_IDENTIFIER = + WSSE_X509_TOKEN_PROFILE_NS + "#X509SubjectKeyIdentifier"; + + /** WS-Security - Kerberos Token Profile - Kerberosv5_AP_REQ. */ + public static final String KERBEROS_AP_REQ = + WSSE_KERBEROS_TOKEN_PROFILE_NS + "#Kerberosv5_AP_REQ"; + + /** WS-Security - Kerberos Token Profile - GSS_Kerberosv5_AP_REQ. */ + public static final String GSS_KERBEROS_AP_REQ = + WSSE_KERBEROS_TOKEN_PROFILE_NS + "#GSS_Kerberosv5_AP_REQ"; + + /** WS-Security - Kerberos Token Profile - Kerberosv5_AP_REQ1510. */ + public static final String KERBEROS_AP_REQ_1510 = + WSSE_KERBEROS_TOKEN_PROFILE_NS + "#Kerberosv5_AP_REQ1510"; + + /** WS-Security - Kerberos Token Profile - GSS_Kerberosv5_AP_REQ1510. */ + public static final String GSS_KERBEROS_AP_REQ_1510 = + WSSE_KERBEROS_TOKEN_PROFILE_NS + "#GSS_Kerberosv5_AP_REQ1510"; + + /** WS-Security - KeyIdentifier - ThumbPrintSHA1.*/ + public static final String THUMB_PRINT_SHA1 = + WS_SECURITY_NS + "#ThumbPrintSHA1"; + + /** WS-Security - KeyIdentifier - EncryptedKeySHA1.*/ + public static final String ENCRYPTED_KEY_SHA1 = + WS_SECURITY_NS + "#EncryptedKeySHA1"; + + /** + * Prevents instantiation. + */ + private WSSecurityConstants() { + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/WSSecurityObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/WSSecurityObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/WSSecurityObject.java 17 Aug 2012 15:09:04 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import org.opensaml.xml.XMLObject; + +/** + * WSSecurityObject is the base interface for all the WS-Security elements. + * + */ +public interface WSSecurityObject extends XMLObject { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/WSSecurityObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/WSSecurityObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/WSSecurityObjectBuilder.java 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity; + +import org.opensaml.xml.XMLObjectBuilder; + +/** + * WSSecurityObjectBuilder. + * + * @param the type of WS-Security object + */ +public interface WSSecurityObjectBuilder + extends XMLObjectBuilder { + + /** + * Builds a WS-Security object of the given type. + * + * @return the built object + */ + public WSSecurityObjectType buildObject(); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/package.html 17 Aug 2012 15:09:03 -0000 1.1 @@ -0,0 +1,19 @@ + + +

+XMLObject interfaces for WS-Security 2004 elements. +

+

+The OASIS Web Services Security: SOAP Message Security 1.1 (WS-Security 2004) specification describes enhancements to SOAP messaging to provide message integrity and confidentialy. This specification also provides a general-purpose mechanism for associating security tokens with message content. +

+

+The security token profiles currently supported are: +

+

+ + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AbstractWSSecurityObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AbstractWSSecurityObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AbstractWSSecurityObject.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import java.util.List; + +import org.opensaml.ws.wssecurity.WSSecurityObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.validation.AbstractValidatingXMLObject; + +/** + * AbstractWSSecurityObject + * + */ +public abstract class AbstractWSSecurityObject extends AbstractValidatingXMLObject implements WSSecurityObject { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public AbstractWSSecurityObject(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /* + * No-op method. No child by default. + * + * @see org.opensaml.xml.XMLObject#getOrderedChildren() + */ + public List getOrderedChildren() { + // no children + return null; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AbstractWSSecurityObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AbstractWSSecurityObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AbstractWSSecurityObjectBuilder.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +import org.opensaml.ws.wssecurity.WSSecurityObject; +import org.opensaml.ws.wssecurity.WSSecurityObjectBuilder; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * AbstractWSSecurityObjectBuilder + * + */ +public abstract class AbstractWSSecurityObjectBuilder + extends AbstractXMLObjectBuilder implements + WSSecurityObjectBuilder { + + /* + * (non-Javadoc) + * + * @see org.opensaml.ws.wssecurity.WSSecurityObjectBuilder#buildObject() + */ + public abstract WSSecurityObjectType buildObject(); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AbstractWSSecurityObjectMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AbstractWSSecurityObjectMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AbstractWSSecurityObjectMarshaller.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * An abstract marshaller implementation for XMLObjects from {@link org.opensaml.ws.wssecurity}. + */ +public abstract class AbstractWSSecurityObjectMarshaller extends AbstractXMLObjectMarshaller { + + /** + * Constructor. + *

+ */ + protected AbstractWSSecurityObjectMarshaller() { + super(); + } + + /* + * No-op method. Extending implementations should override this method if they have attributes to marshall into the + * Element. + * + * @see org.opensaml.xml.io.AbstractXMLObjectMarshaller#marshallAttributes(org.opensaml.xml.XMLObject, + * org.w3c.dom.Element) + */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + + } + + /* + * No-op method. Extending implementations should override this method if they have text content to marshall into + * the Element. + * + * @see org.opensaml.xml.io.AbstractXMLObjectMarshaller#marshallElementContent(org.opensaml.xml.XMLObject, + * org.w3c.dom.Element) + */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AbstractWSSecurityObjectUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AbstractWSSecurityObjectUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AbstractWSSecurityObjectUnmarshaller.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; + +/** + * An abstract unmarshaller implementation for XMLObjects from {@link org.opensaml.ws.wssecurity}. + */ +public abstract class AbstractWSSecurityObjectUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** + * Logger. + */ + private final Logger log = LoggerFactory.getLogger(AbstractWSSecurityObjectUnmarshaller.class); + + /** + * Constructor. + *

+ */ + protected AbstractWSSecurityObjectUnmarshaller() { + super(); + } + + /* + * No-op method. Extending implementations should override this method if they have child element to unmarshall. + * + * @see org.opensaml.xml.io.AbstractXMLObjectUnmarshaller#processChildElement(org.opensaml.xml.XMLObject, + * org.opensaml.xml.XMLObject) + */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + log.warn("{} ignoring unknown child element {}", parentXMLObject.getElementQName().getLocalPart(), + childXMLObject.getElementQName().getLocalPart()); + } + + /* + * No-op method. Extending implementations should override this method if they have attributes to unmarshall. + * + * @see org.opensaml.xml.io.AbstractXMLObjectUnmarshaller#processAttribute(org.opensaml.xml.XMLObject, + * org.w3c.dom.Attr) + */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + log.warn("{} ignoring unknown attribute {}", xmlObject.getElementQName().getLocalPart(), attribute + .getLocalName()); + } + + /* + * No-op method. Extending implementations should override this method if they have element content to unmarshall. + * + * @see org.opensaml.xml.io.AbstractXMLObjectUnmarshaller#processElementContent(org.opensaml.xml.XMLObject, + * java.lang.String) + */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + log.warn("{} ignoring unknown element content: {}", xmlObject.getElementQName().getLocalPart(), elementContent); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedDataTimeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedDataTimeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedDataTimeImpl.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.AttributedDateTime; + + +/** + * Implementation of {@link AttributedDateTime}. + * + * @deprecated replacement {@link AttributedDateTimeImpl}. + * + */ +public class AttributedDataTimeImpl extends AttributedDateTimeImpl { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public AttributedDataTimeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedDateTimeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedDateTimeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedDateTimeImpl.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,118 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; +import org.opensaml.ws.wssecurity.AttributedDateTime; +import org.opensaml.ws.wssecurity.IdBearing; +import org.opensaml.xml.util.AttributeMap; + +/** + * Implementation of {@link AttributedDateTime}. + * + */ +public class AttributedDateTimeImpl extends AbstractWSSecurityObject implements AttributedDateTime { + + /** DateTime formatter. */ + private DateTimeFormatter formatter; + + /** DateTime object. */ + private DateTime dateTimeValue; + + /** String dateTime representation. */ + private String stringValue; + + /** wsu:id attribute value. */ + private String id; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public AttributedDateTimeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + formatter = ISODateTimeFormat.dateTime().withChronology(ISOChronology.getInstanceUTC()); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public DateTime getDateTime() { + return dateTimeValue; + } + + /** {@inheritDoc} */ + public void setDateTime(DateTime newDateTime) { + dateTimeValue = newDateTime; + String formattedDateTime = formatter.print(dateTimeValue); + stringValue = prepareForAssignment(stringValue, formattedDateTime); + } + + /** {@inheritDoc} */ + public String getValue() { + return stringValue; + } + + /** {@inheritDoc} */ + public void setValue(String newValue) { + dateTimeValue = new DateTime(newValue).withChronology(ISOChronology.getInstanceUTC()); + stringValue = prepareForAssignment(stringValue, newValue); + } + + /** {@inheritDoc} */ + public String getWSUId() { + return id; + } + + /** {@inheritDoc} */ + public void setWSUId(String newId) { + String oldID = id; + id = prepareForAssignment(id, newId); + registerOwnID(oldID, id); + manageQualifiedAttributeNamespace(IdBearing.WSU_ID_ATTR_NAME, id != null); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public DateTimeFormatter getDateTimeFormatter() { + return formatter; + } + + /** {@inheritDoc} */ + public void setDateTimeFormatter(DateTimeFormatter newFormatter) { + if (newFormatter == null) { + throw new IllegalArgumentException("The specified DateTimeFormatter may not be null"); + } + formatter = newFormatter; + // Explicitly cause the cached string representation to be reformatted when the formatter is changed + setDateTime(getDateTime()); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedDateTimeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedDateTimeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedDateTimeMarshaller.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.AttributedDateTime; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * AttributedDateTimeMarshaller. + * + */ +public class AttributedDateTimeMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributedDateTime dateTime = (AttributedDateTime) xmlObject; + + if (!DatatypeHelper.isEmpty(dateTime.getWSUId())) { + XMLHelper.marshallAttribute(AttributedDateTime.WSU_ID_ATTR_NAME, dateTime.getWSUId(), domElement, true); + } + + XMLHelper.marshallAttributeMap(dateTime.getUnknownAttributes(), domElement); + + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributedDateTime dateTime = (AttributedDateTime) xmlObject; + XMLHelper.appendTextContent(domElement, dateTime.getValue()); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedDateTimeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedDateTimeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedDateTimeUnmarshaller.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.AttributedDateTime; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * AttributedDateTimeUnmarshaller. + * + */ +public class AttributedDateTimeUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + AttributedDateTime dateTime = (AttributedDateTime) xmlObject; + + QName attrName = + XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute.getPrefix()); + if (AttributedDateTime.WSU_ID_ATTR_NAME.equals(attrName)) { + dateTime.setWSUId(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else { + XMLHelper.unmarshallToAttributeMap(dateTime.getUnknownAttributes(), attribute); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + AttributedDateTime dateTime = (AttributedDateTime) xmlObject; + if (!DatatypeHelper.isEmpty(elementContent)) { + dateTime.setValue(elementContent); + } + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedStringImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedStringImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedStringImpl.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.AttributedString; +import org.opensaml.ws.wssecurity.IdBearing; +import org.opensaml.xml.util.AttributeMap; + +/** + * Implementation of {@link AttributedString}. + */ +public class AttributedStringImpl extends AbstractWSSecurityObject implements AttributedString { + + /** The string value. */ + private String value; + + /** The wsu:Id attribute value. */ + private String id; + + /** The wildcard attributes. */ + private AttributeMap attributes; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public AttributedStringImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public String getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setValue(String newValue) { + value = prepareForAssignment(value, newValue); + } + + /** {@inheritDoc} */ + public String getWSUId() { + return id; + } + + /** {@inheritDoc} */ + public void setWSUId(String newId) { + String oldId = id; + id = prepareForAssignment(id, newId); + registerOwnID(oldId, id); + manageQualifiedAttributeNamespace(IdBearing.WSU_ID_ATTR_NAME, id != null); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return attributes; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedStringMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedStringMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedStringMarshaller.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.AttributedString; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for instances of {@link AttributedString}. + */ +public class AttributedStringMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributedString attributedString = (AttributedString) xmlObject; + + if (!DatatypeHelper.isEmpty(attributedString.getWSUId())) { + XMLHelper.marshallAttribute(AttributedString.WSU_ID_ATTR_NAME, attributedString.getWSUId(), domElement, true); + } + + XMLHelper.marshallAttributeMap(attributedString.getUnknownAttributes(), domElement); + + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributedString attributedString = (AttributedString) xmlObject; + XMLHelper.appendTextContent(domElement, attributedString.getValue()); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedStringUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedStringUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedStringUnmarshaller.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.AttributedString; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for instances of {@link AttributedString}. + */ +public class AttributedStringUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + AttributedString attributedString = (AttributedString) xmlObject; + + QName attribQName = + XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute.getPrefix()); + if (AttributedString.WSU_ID_ATTR_NAME.equals(attribQName)) { + attributedString.setWSUId(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else { + XMLHelper.unmarshallToAttributeMap(attributedString.getUnknownAttributes(), attribute); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + AttributedString attributedString = (AttributedString) xmlObject; + attributedString.setValue(elementContent); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedURIImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedURIImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedURIImpl.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.AttributedURI; +import org.opensaml.ws.wssecurity.IdBearing; +import org.opensaml.xml.util.AttributeMap; + +/** + * Implementation of {@link AttributedURI}. + */ +public class AttributedURIImpl extends AbstractWSSecurityObject implements AttributedURI { + + /** The string value. */ + private String value; + + /** The wsu:Id attribute value. */ + private String id; + + /** The wildcard attributes. */ + private AttributeMap attributes; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public AttributedURIImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public String getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setValue(String newValue) { + value = prepareForAssignment(value, newValue); + } + + /** {@inheritDoc} */ + public String getWSUId() { + return id; + } + + /** {@inheritDoc} */ + public void setWSUId(String newId) { + String oldId = id; + id = prepareForAssignment(id, newId); + registerOwnID(oldId, id); + manageQualifiedAttributeNamespace(IdBearing.WSU_ID_ATTR_NAME, id != null); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return attributes; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedURIMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedURIMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedURIMarshaller.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.AttributedURI; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for instances of {@link AttributedURI}. + */ +public class AttributedURIMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributedURI attributedURI = (AttributedURI) xmlObject; + + if (!DatatypeHelper.isEmpty(attributedURI.getWSUId())) { + XMLHelper.marshallAttribute(AttributedURI.WSU_ID_ATTR_NAME, attributedURI.getWSUId(), domElement, true); + } + + XMLHelper.marshallAttributeMap(attributedURI.getUnknownAttributes(), domElement); + + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributedURI attributedURI = (AttributedURI) xmlObject; + XMLHelper.appendTextContent(domElement, attributedURI.getValue()); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedURIUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedURIUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/AttributedURIUnmarshaller.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.AttributedURI; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for instances of {@link AttributedURI}. + */ +public class AttributedURIUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + AttributedURI attributedURI = (AttributedURI) xmlObject; + + QName attribQName = + XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute.getPrefix()); + if (AttributedURI.WSU_ID_ATTR_NAME.equals(attribQName)) { + attributedURI.setWSUId(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else { + XMLHelper.unmarshallToAttributeMap(attributedURI.getUnknownAttributes(), attribute); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + AttributedURI attributedURI = (AttributedURI) xmlObject; + attributedURI.setValue(elementContent); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/BinarySecurityTokenBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/BinarySecurityTokenBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/BinarySecurityTokenBuilder.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.BinarySecurityToken; + +/** + * Builder for the <BinarySecurityToken> element. + */ +public class BinarySecurityTokenBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public BinarySecurityToken buildObject() { + return buildObject(BinarySecurityToken.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public BinarySecurityToken buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new BinarySecurityTokenImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/BinarySecurityTokenImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/BinarySecurityTokenImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/BinarySecurityTokenImpl.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.BinarySecurityToken; + +/** + * BinarySecurityTokenImpl. + */ +public class BinarySecurityTokenImpl extends EncodedStringImpl implements BinarySecurityToken { + + /** wsse:BinarySecurityToken/@ValueType attribute. */ + private String valueType; + + /** + * Constructor. Default EncodingType is BinarySecurityToken.ENCODINGTYPE_BASE64_BINARY + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public BinarySecurityTokenImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + // default encoding type + setEncodingType(BinarySecurityToken.ENCODING_TYPE_BASE64_BINARY); + } + + /** {@inheritDoc} */ + public String getValueType() { + return valueType; + } + + /** {@inheritDoc} */ + public void setValueType(String newValueType) { + valueType = prepareForAssignment(valueType, newValueType); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/BinarySecurityTokenMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/BinarySecurityTokenMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/BinarySecurityTokenMarshaller.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.BinarySecurityToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * BinarySecurityTokenMarshaller. + */ +public class BinarySecurityTokenMarshaller extends EncodedStringMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + BinarySecurityToken token = (BinarySecurityToken) xmlObject; + if (!DatatypeHelper.isEmpty(token.getValueType())) { + domElement.setAttributeNS(null, BinarySecurityToken.ENCODING_TYPE_ATTRIB_NAME, token.getValueType()); + } + super.marshallAttributes(xmlObject, domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/BinarySecurityTokenUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/BinarySecurityTokenUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/BinarySecurityTokenUnmarshaller.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.BinarySecurityToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * BinarySecurityTokenUnmarshaller. + */ +public class BinarySecurityTokenUnmarshaller extends EncodedStringUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + BinarySecurityToken token = (BinarySecurityToken) xmlObject; + if (BinarySecurityToken.VALUE_TYPE_ATTRIB_NAME.equals(attribute.getLocalName())) { + token.setValueType(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/CreatedBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/CreatedBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/CreatedBuilder.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Created; + +/** + * Builder for the <wsu:Created> element. + * + */ +public class CreatedBuilder extends AbstractWSSecurityObjectBuilder { + + /* + * (non-Javadoc) + * + * @see org.opensaml.ws.wssecurity.impl.AbstractWSSecurityObjectBuilder#buildObject() + */ + @Override + public Created buildObject() { + return buildObject(Created.ELEMENT_NAME); + } + + /* + * (non-Javadoc) + * + * @see org.opensaml.xml.AbstractXMLObjectBuilder#buildObject(java.lang.String, + * java.lang.String, java.lang.String) + */ + @Override + public Created buildObject(String namespaceURI, String localName, + String namespacePrefix) { + return new CreatedImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/CreatedImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/CreatedImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/CreatedImpl.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Created; + +/** + * CreatedImpl. + * + */ +public class CreatedImpl extends AttributedDateTimeImpl implements Created { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public CreatedImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/CreatedMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/CreatedMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/CreatedMarshaller.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +/** + * Marshaller for the <wsu:Created> element. + * + */ +public class CreatedMarshaller extends AttributedDateTimeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/CreatedUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/CreatedUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/CreatedUnmarshaller.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +/** + * CreatedUnmarshaller. + * + */ +public class CreatedUnmarshaller extends AttributedDateTimeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EmbeddedBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EmbeddedBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EmbeddedBuilder.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Embedded; + +/** + * EmbeddedBuilder. + * + */ +public class EmbeddedBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public Embedded buildObject() { + return buildObject(Embedded.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Embedded buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EmbeddedImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EmbeddedImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EmbeddedImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EmbeddedImpl.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,94 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.Embedded; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * EmbeddedImpl is the concrete implementation of {@link Embedded}. + * + */ +public class EmbeddedImpl extends AbstractWSSecurityObject implements Embedded { + + /** wsse:Embedded/@wsse:ValueType attribute. */ + private String valueType; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + protected EmbeddedImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getValueType() { + return valueType; + } + + /** {@inheritDoc} */ + public void setValueType(String newValueType) { + valueType = prepareForAssignment(valueType, newValueType); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (!getUnknownXMLObjects().isEmpty()) { + children.addAll(getUnknownXMLObjects()); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EmbeddedMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EmbeddedMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EmbeddedMarshaller.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Embedded; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * EmbeddedMarshaller. + * + */ +public class EmbeddedMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Embedded embedded = (Embedded) xmlObject; + if (!DatatypeHelper.isEmpty(embedded.getValueType())) { + domElement.setAttributeNS(null, Embedded.VALUE_TYPE_ATTRIB_NAME, embedded.getValueType()); + } + + XMLHelper.marshallAttributeMap(embedded.getUnknownAttributes(), domElement); + + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EmbeddedUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EmbeddedUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EmbeddedUnmarshaller.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Embedded; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * EmbeddedUnmarshaller. + * + */ +public class EmbeddedUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Embedded embedded = (Embedded) xmlObject; + String attrName = attribute.getLocalName(); + if (Embedded.VALUE_TYPE_ATTRIB_NAME.equals(attrName)) { + embedded.setValueType(attribute.getValue()); + } else { + XMLHelper.unmarshallToAttributeMap(embedded.getUnknownAttributes(), attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Embedded embedded = (Embedded) parentXMLObject; + embedded.getUnknownXMLObjects().add(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncodedStringImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncodedStringImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncodedStringImpl.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.EncodedString; + +/** + * Implementation of {@link EncodedString}. + */ +public class EncodedStringImpl extends AttributedStringImpl implements EncodedString { + + /** The encodingType attribute value. */ + private String encodingType; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public EncodedStringImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getEncodingType() { + return encodingType; + } + + /** {@inheritDoc} */ + public void setEncodingType(String newEncodingType) { + encodingType = prepareForAssignment(encodingType, newEncodingType); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncodedStringMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncodedStringMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncodedStringMarshaller.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.EncodedString; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for instances of {@link EncodedString}. + */ +public class EncodedStringMarshaller extends AttributedStringMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + EncodedString encodedString = (EncodedString) xmlObject; + if (!DatatypeHelper.isEmpty(encodedString.getEncodingType())){ + domElement.setAttributeNS(null, EncodedString.ENCODING_TYPE_ATTRIB_NAME, encodedString.getEncodingType()); + } + super.marshallAttributes(xmlObject, domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncodedStringUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncodedStringUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncodedStringUnmarshaller.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.EncodedString; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for instances of {@link EncodedString}. + */ +public class EncodedStringUnmarshaller extends AttributedStringUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + EncodedString encodedString= (EncodedString) xmlObject; + if (EncodedString.ENCODING_TYPE_ATTRIB_NAME.equals(attribute.getLocalName())) { + encodedString.setEncodingType(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncryptedHeaderBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncryptedHeaderBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncryptedHeaderBuilder.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.EncryptedHeader; + +/** + * EncryptedHeaderBuilder. + * + */ +public class EncryptedHeaderBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public EncryptedHeader buildObject() { + return buildObject(EncryptedHeader.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public EncryptedHeader buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EncryptedHeaderImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncryptedHeaderImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncryptedHeaderImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncryptedHeaderImpl.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,219 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.soap.soap11.ActorBearing; +import org.opensaml.ws.soap.soap11.MustUnderstandBearing; +import org.opensaml.ws.soap.soap12.RelayBearing; +import org.opensaml.ws.soap.soap12.RoleBearing; +import org.opensaml.ws.wssecurity.EncryptedHeader; +import org.opensaml.ws.wssecurity.IdBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.encryption.EncryptedData; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.LazyList; + +/** + * Implementation of {@link EncryptedHeader}. + */ +public class EncryptedHeaderImpl extends AbstractWSSecurityObject implements EncryptedHeader { + + /** EncryptedData child element. */ + private EncryptedData encryptedData; + + /** The @wsu:Id atribute. */ + private String wsuId; + + /** The @soap11:mustUnderstand atribute. */ + private XSBooleanValue soap11MustUnderstand; + + /** The @soap11:actor atribute. */ + private String soap11Actor; + + /** The @soap12:mustUnderstand atribute. */ + private XSBooleanValue soap12MustUnderstand; + + /** The @soap12:role atribute. */ + private String soap12Role; + + /** The @soap12:relay atribute. */ + private XSBooleanValue soap12Relay; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public EncryptedHeaderImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public EncryptedData getEncryptedData() { + return encryptedData; + } + + /** {@inheritDoc} */ + public void setEncryptedData(EncryptedData newEncryptedData) { + encryptedData = prepareForAssignment(encryptedData, newEncryptedData); + } + + /** {@inheritDoc} */ + public String getWSUId() { + return wsuId; + } + + /** {@inheritDoc} */ + public void setWSUId(String newId) { + String oldId = wsuId; + wsuId = prepareForAssignment(wsuId, newId); + registerOwnID(oldId, wsuId); + manageQualifiedAttributeNamespace(IdBearing.WSU_ID_ATTR_NAME, wsuId != null); + } + + /** {@inheritDoc} */ + public Boolean isSOAP11MustUnderstand() { + if (soap11MustUnderstand != null) { + return soap11MustUnderstand.getValue(); + } + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isSOAP11MustUnderstandXSBoolean() { + return soap11MustUnderstand; + } + + /** {@inheritDoc} */ + public void setSOAP11MustUnderstand(Boolean newMustUnderstand) { + if (newMustUnderstand != null) { + soap11MustUnderstand = prepareForAssignment(soap11MustUnderstand, + new XSBooleanValue(newMustUnderstand, true)); + } else { + soap11MustUnderstand = prepareForAssignment(soap11MustUnderstand, null); + } + manageQualifiedAttributeNamespace(MustUnderstandBearing.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + soap11MustUnderstand != null); + } + + /** {@inheritDoc} */ + public void setSOAP11MustUnderstand(XSBooleanValue newMustUnderstand) { + soap11MustUnderstand = prepareForAssignment(soap11MustUnderstand, newMustUnderstand); + manageQualifiedAttributeNamespace(MustUnderstandBearing.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + soap11MustUnderstand != null); + } + + /** {@inheritDoc} */ + public String getSOAP11Actor() { + return soap11Actor; + } + + /** {@inheritDoc} */ + public void setSOAP11Actor(String newActor) { + soap11Actor = prepareForAssignment(soap11Actor, newActor); + manageQualifiedAttributeNamespace(ActorBearing.SOAP11_ACTOR_ATTR_NAME, soap11Actor != null); + } + + /** {@inheritDoc} */ + public Boolean isSOAP12MustUnderstand() { + if (soap12MustUnderstand != null) { + return soap12MustUnderstand.getValue(); + } + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isSOAP12MustUnderstandXSBoolean() { + return soap12MustUnderstand; + } + + /** {@inheritDoc} */ + public void setSOAP12MustUnderstand(Boolean newMustUnderstand) { + if (newMustUnderstand != null) { + soap12MustUnderstand = prepareForAssignment(soap12MustUnderstand, + new XSBooleanValue(newMustUnderstand, false)); + } else { + soap12MustUnderstand = prepareForAssignment(soap12MustUnderstand, null); + } + manageQualifiedAttributeNamespace(org.opensaml.ws.soap.soap12.MustUnderstandBearing.SOAP12_MUST_UNDERSTAND_ATTR_NAME, + soap12MustUnderstand != null); + } + + /** {@inheritDoc} */ + public void setSOAP12MustUnderstand(XSBooleanValue newMustUnderstand) { + soap12MustUnderstand = prepareForAssignment(soap12MustUnderstand, newMustUnderstand); + manageQualifiedAttributeNamespace(org.opensaml.ws.soap.soap12.MustUnderstandBearing.SOAP12_MUST_UNDERSTAND_ATTR_NAME, + soap12MustUnderstand != null); + } + + /** {@inheritDoc} */ + public String getSOAP12Role() { + return soap12Role; + } + + /** {@inheritDoc} */ + public void setSOAP12Role(String newRole) { + soap12Role = prepareForAssignment(soap12Role, newRole); + manageQualifiedAttributeNamespace(RoleBearing.SOAP12_ROLE_ATTR_NAME, soap12Role != null); + } + + /** {@inheritDoc} */ + public Boolean isSOAP12Relay() { + if (soap12Relay != null) { + return soap12Relay.getValue(); + } + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isSOAP12RelayXSBoolean() { + return soap12Relay; + } + + /** {@inheritDoc} */ + public void setSOAP12Relay(Boolean newRelay) { + if (newRelay != null) { + soap12Relay = prepareForAssignment(soap12Relay, + new XSBooleanValue(newRelay, false)); + } else { + soap12Relay = prepareForAssignment(soap12Relay, null); + } + manageQualifiedAttributeNamespace(RelayBearing.SOAP12_RELAY_ATTR_NAME, soap12Relay != null); + } + + /** {@inheritDoc} */ + public void setSOAP12Relay(XSBooleanValue newRelay) { + soap12Relay = prepareForAssignment(soap12Relay, newRelay); + manageQualifiedAttributeNamespace(RelayBearing.SOAP12_RELAY_ATTR_NAME, soap12Relay != null); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + LazyList children = new LazyList(); + if (encryptedData != null) { + children.add(encryptedData); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncryptedHeaderMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncryptedHeaderMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncryptedHeaderMarshaller.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.EncryptedHeader; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for instances of {@link EncryptedHeaderMarshaller}. + */ +public class EncryptedHeaderMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + EncryptedHeader eh = (EncryptedHeader) xmlObject; + + if (eh.getWSUId() != null) { + XMLHelper.marshallAttribute(EncryptedHeader.WSU_ID_ATTR_NAME, + eh.getWSUId(), domElement, true); + } + if (eh.isSOAP11MustUnderstandXSBoolean() != null) { + XMLHelper.marshallAttribute(EncryptedHeader.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + eh.isSOAP11MustUnderstandXSBoolean().toString(), domElement, false); + } + if (eh.getSOAP11Actor() != null) { + XMLHelper.marshallAttribute(EncryptedHeader.SOAP11_ACTOR_ATTR_NAME, + eh.getSOAP11Actor(), domElement, false); + } + if (eh.isSOAP12MustUnderstandXSBoolean() != null) { + XMLHelper.marshallAttribute(EncryptedHeader.SOAP12_MUST_UNDERSTAND_ATTR_NAME, + eh.isSOAP12MustUnderstandXSBoolean().toString(), domElement, false); + } + if (eh.getSOAP12Role() != null) { + XMLHelper.marshallAttribute(EncryptedHeader.SOAP12_ROLE_ATTR_NAME, + eh.getSOAP12Role(), domElement, false); + } + if (eh.isSOAP12RelayXSBoolean() != null) { + XMLHelper.marshallAttribute(EncryptedHeader.SOAP12_RELAY_ATTR_NAME, + eh.isSOAP12RelayXSBoolean().toString(), domElement, false); + } + + super.marshallAttributes(xmlObject, domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncryptedHeaderUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncryptedHeaderUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/EncryptedHeaderUnmarshaller.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.EncryptedHeader; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.encryption.EncryptedData; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for instances of {@link EncryptedHeader}. + */ +public class EncryptedHeaderUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + EncryptedHeader eh = (EncryptedHeader) xmlObject; + QName attrName = XMLHelper.getNodeQName(attribute); + if (EncryptedHeader.WSU_ID_ATTR_NAME.equals(attrName)) { + eh.setWSUId(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else if (EncryptedHeader.SOAP11_MUST_UNDERSTAND_ATTR_NAME.equals(attrName)) { + eh.setSOAP11MustUnderstand(XSBooleanValue.valueOf(attribute.getValue())); + } else if (EncryptedHeader.SOAP11_ACTOR_ATTR_NAME.equals(attrName)) { + eh.setSOAP11Actor(attribute.getValue()); + } else if (EncryptedHeader.SOAP12_MUST_UNDERSTAND_ATTR_NAME.equals(attrName)) { + eh.setSOAP12MustUnderstand(XSBooleanValue.valueOf(attribute.getValue())); + } else if (EncryptedHeader.SOAP12_ROLE_ATTR_NAME.equals(attrName)) { + eh.setSOAP12Role(attribute.getValue()); + } else if (EncryptedHeader.SOAP12_RELAY_ATTR_NAME.equals(attrName)) { + eh.setSOAP12Relay(XSBooleanValue.valueOf(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + EncryptedHeader eh = (EncryptedHeader) parentXMLObject; + if (childXMLObject instanceof EncryptedData) { + eh.setEncryptedData((EncryptedData) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ExpiresBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ExpiresBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ExpiresBuilder.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Expires; + +/** + * ExpiresBuilder + * + */ +public class ExpiresBuilder extends AbstractWSSecurityObjectBuilder { + + /* + * (non-Javadoc) + * + * @see org.opensaml.ws.wssecurity.impl.AbstractWSSecurityObjectBuilder#buildObject() + */ + @Override + public Expires buildObject() { + return buildObject(Expires.ELEMENT_NAME); + } + + /* + * (non-Javadoc) + * + * @see org.opensaml.xml.AbstractXMLObjectBuilder#buildObject(java.lang.String, + * java.lang.String, java.lang.String) + */ + @Override + public Expires buildObject(String namespaceURI, String localName, + String namespacePrefix) { + return new ExpiresImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ExpiresImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ExpiresImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ExpiresImpl.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Expires; + +/** + * ExpiresImpl. + * + */ +public class ExpiresImpl extends AttributedDateTimeImpl implements Expires { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public ExpiresImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ExpiresMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ExpiresMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ExpiresMarshaller.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +/** + * ExpiresMarshaller. + * + */ +public class ExpiresMarshaller extends AttributedDateTimeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ExpiresUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ExpiresUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ExpiresUnmarshaller.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +/** + * ExpiresUnmarshaller. + * + */ +public class ExpiresUnmarshaller extends AttributedDateTimeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/IterationBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/IterationBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/IterationBuilder.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Iteration; + +/** + * IterationBuilder. + * + */ +public class IterationBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public Iteration buildObject() { + return buildObject(Iteration.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Iteration buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new IterationImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/IterationImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/IterationImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/IterationImpl.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Iteration; +import org.opensaml.xml.schema.impl.XSIntegerImpl; + +/** + * IterationImpl. + * + */ +public class IterationImpl extends XSIntegerImpl implements Iteration { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public IterationImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/IterationMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/IterationMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/IterationMarshaller.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +import org.opensaml.ws.wssecurity.Iteration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * IterationMarshaller. + * + */ +public class IterationMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + Iteration iteration = (Iteration) xmlObject; + + if (iteration.getValue() != null) { + XMLHelper.appendTextContent(domElement, iteration.getValue().toString()); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/IterationUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/IterationUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/IterationUnmarshaller.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +import org.opensaml.ws.wssecurity.Iteration; +import org.opensaml.xml.XMLObject; + +/** + * IterationUnmarshaller. + * + */ +public class IterationUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + Iteration iteration = (Iteration) xmlObject; + if (elementContent != null) { + iteration.setValue(Integer.valueOf(elementContent)); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/KeyIdentifierBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/KeyIdentifierBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/KeyIdentifierBuilder.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.KeyIdentifier; + +/** + * KeyIdentifierBuilder. + */ +public class KeyIdentifierBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public KeyIdentifier buildObject() { + return buildObject(KeyIdentifier.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public KeyIdentifier buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new KeyIdentifierImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/KeyIdentifierImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/KeyIdentifierImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/KeyIdentifierImpl.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +import org.opensaml.ws.wssecurity.KeyIdentifier; + +/** + * KeyIdentifierImpl. + */ +public class KeyIdentifierImpl extends EncodedStringImpl implements KeyIdentifier { + + /** wsse:KeyIdentifier/@ValueType attribute. */ + private String valueType; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public KeyIdentifierImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getValueType() { + return valueType; + } + + /** {@inheritDoc} */ + public void setValueType(String newValueType) { + valueType = prepareForAssignment(valueType, newValueType); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/KeyIdentifierMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/KeyIdentifierMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/KeyIdentifierMarshaller.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +import org.opensaml.ws.wssecurity.KeyIdentifier; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * KeyIdentifierMarshaller. + * + */ +public class KeyIdentifierMarshaller extends EncodedStringMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + KeyIdentifier keyIdentifier = (KeyIdentifier) xmlObject; + if (!DatatypeHelper.isEmpty(keyIdentifier.getValueType())) { + domElement.setAttributeNS(null, KeyIdentifier.VALUE_TYPE_ATTRIB_NAME, keyIdentifier.getValueType()); + } + super.marshallAttributes(xmlObject, domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/KeyIdentifierUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/KeyIdentifierUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/KeyIdentifierUnmarshaller.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +import org.opensaml.ws.wssecurity.KeyIdentifier; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * KeyIdentifierUnmarshaller. + */ +public class KeyIdentifierUnmarshaller extends EncodedStringUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + KeyIdentifier keyIdentifier = (KeyIdentifier) xmlObject; + if (KeyIdentifier.VALUE_TYPE_ATTRIB_NAME.equals(attribute.getLocalName())) { + keyIdentifier.setValueType(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/NonceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/NonceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/NonceBuilder.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Nonce; + +/** + * NonceBuilder. + * + */ +public class NonceBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public Nonce buildObject() { + return buildObject(Nonce.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Nonce buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new NonceImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/NonceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/NonceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/NonceImpl.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Nonce; + +/** + * NonceImpl. + * + */ +public class NonceImpl extends EncodedStringImpl implements Nonce { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public NonceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/NonceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/NonceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/NonceMarshaller.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,26 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +/** + * NonceMarshaller. + */ +public class NonceMarshaller extends EncodedStringMarshaller { + + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/NonceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/NonceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/NonceUnmarshaller.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +/** + * NonceUnmarshaller. + * + */ +public class NonceUnmarshaller extends EncodedStringUnmarshaller { + + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/PasswordBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/PasswordBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/PasswordBuilder.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Password; + +/** + * PasswordBuilder. + * + */ +public class PasswordBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public Password buildObject() { + return buildObject(Password.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Password buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new PasswordImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/PasswordImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/PasswordImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/PasswordImpl.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Password; + +/** + * PasswordImpl. + */ +public class PasswordImpl extends AttributedStringImpl implements Password { + + /** wsse:Password/@Type attribute. */ + private String type; + + /** + * Constructor. Default Type attribute: Password.TYPE_PASSWORD_TEXT + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public PasswordImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + // set default type + type = Password.TYPE_PASSWORD_TEXT; + } + + /** {@inheritDoc} */ + public String getType() { + return type; + } + + /** {@inheritDoc} */ + public void setType(String newType) { + type = prepareForAssignment(type, newType); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/PasswordMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/PasswordMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/PasswordMarshaller.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Password; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * PasswordMarshaller. + */ +public class PasswordMarshaller extends AttributedStringMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Password password = (Password) xmlObject; + if (!DatatypeHelper.isEmpty(password.getType())) { + domElement.setAttributeNS(null, Password.TYPE_ATTRIB_NAME, password.getType()); + } + super.marshallAttributes(xmlObject, domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/PasswordUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/PasswordUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/PasswordUnmarshaller.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +import org.opensaml.ws.wssecurity.Password; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * PasswordUnmarshaller. + * + */ +public class PasswordUnmarshaller extends AttributedStringUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Password password= (Password) xmlObject; + if (Password.TYPE_ATTRIB_NAME.equals(attribute.getLocalName())) { + password.setType(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ReferenceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ReferenceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ReferenceBuilder.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Reference; + +/** + * ReferenceBuilder. + * + */ +public class ReferenceBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public Reference buildObject() { + return buildObject(Reference.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Reference buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ReferenceImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ReferenceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ReferenceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ReferenceImpl.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,75 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Reference; +import org.opensaml.xml.util.AttributeMap; + +/** + * ReferenceImpl. + * + */ +public class ReferenceImpl extends AbstractWSSecurityObject implements Reference { + + /** wsse:Reference/@URI attribute. */ + private String uri; + + /** wsse:Reference/@ValueType attribute. */ + private String valueType; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public ReferenceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public String getURI() { + return uri; + } + + /** {@inheritDoc} */ + public void setURI(String newURI) { + uri = prepareForAssignment(uri, newURI); + } + + /** {@inheritDoc} */ + public String getValueType() { + return valueType; + } + + /** {@inheritDoc} */ + public void setValueType(String newValueType) { + valueType = prepareForAssignment(valueType, newValueType); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ReferenceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ReferenceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ReferenceMarshaller.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +import org.opensaml.ws.wssecurity.Reference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * ReferenceMarshaller. + * + */ +public class ReferenceMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Reference reference = (Reference) xmlObject; + + if (!DatatypeHelper.isEmpty(reference.getURI())) { + domElement.setAttributeNS(null, Reference.URI_ATTRIB_NAME, reference.getURI()); + } + + if (!DatatypeHelper.isEmpty(reference.getValueType())) { + domElement.setAttributeNS(null, Reference.VALUE_TYPE_ATTRIB_NAME, reference.getValueType()); + } + + XMLHelper.marshallAttributeMap(reference.getUnknownAttributes(), domElement); + + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ReferenceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ReferenceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/ReferenceUnmarshaller.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Reference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * ReferenceUnmarshaller. + * + */ +public class ReferenceUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Reference reference = (Reference) xmlObject; + String attrName = attribute.getLocalName(); + if (Reference.URI_ATTRIB_NAME.equals(attrName)) { + reference.setURI(attribute.getValue()); + } else if (Reference.VALUE_TYPE_ATTRIB_NAME.equals(attrName)) { + reference.setValueType(attribute.getValue()); + } else { + XMLHelper.unmarshallToAttributeMap(reference.getUnknownAttributes(), attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SaltBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SaltBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SaltBuilder.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Salt; + +/** + * SaltBuilder. + */ +public class SaltBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public Salt buildObject() { + return buildObject(Salt.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Salt buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SaltImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SaltImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SaltImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SaltImpl.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Salt; +import org.opensaml.xml.schema.impl.XSBase64BinaryImpl; + +/** + * SaltImpl. + * + */ +public class SaltImpl extends XSBase64BinaryImpl implements Salt { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + protected SaltImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SaltMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SaltMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SaltMarshaller.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Salt; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * SaltMarshaller. + * + */ +public class SaltMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + Salt salt = (Salt) xmlObject; + XMLHelper.appendTextContent(domElement, salt.getValue()); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SaltUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SaltUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SaltUnmarshaller.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Salt; +import org.opensaml.xml.XMLObject; + +/** + * SaltUnmarshaller. + * + */ +public class SaltUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + Salt salt = (Salt) xmlObject; + salt.setValue(elementContent); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityBuilder.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Security; + +/** + * SecurityBuilder. + * + */ +public class SecurityBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public Security buildObject() { + return buildObject(Security.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Security buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SecurityImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityImpl.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.Security; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * SecurityImpl implements the <wsse:Security> header. + * + */ +public class SecurityImpl extends AbstractWSSecurityObject implements Security { + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public SecurityImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (!getUnknownXMLObjects().isEmpty()) { + children.addAll(getUnknownXMLObjects()); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityMarshaller.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Security; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * SecurityMarshaller. + * + */ +public class SecurityMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Security security = (Security) xmlObject; + XMLHelper.marshallAttributeMap(security.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityTokenReferenceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityTokenReferenceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityTokenReferenceBuilder.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.SecurityTokenReference; + +/** + * SecurityTokenReferenceBuilder. + * + */ +public class SecurityTokenReferenceBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public SecurityTokenReference buildObject() { + return buildObject(SecurityTokenReference.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public SecurityTokenReference buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SecurityTokenReferenceImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityTokenReferenceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityTokenReferenceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityTokenReferenceImpl.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,116 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.IdBearing; +import org.opensaml.ws.wssecurity.SecurityTokenReference; +import org.opensaml.ws.wssecurity.UsageBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * SecurityTokenReferenceImpl. + * + */ +public class SecurityTokenReferenceImpl extends AbstractWSSecurityObject implements SecurityTokenReference { + + /** The <wsu:Id> attribute value. */ + private String id; + + /** List of <wsse:Usage> attribute values. */ + private List usages; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public SecurityTokenReferenceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + usages = new ArrayList(); + unknownAttributes = new AttributeMap(this); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + + /** {@inheritDoc} */ + public List getWSSEUsages() { + return usages; + } + + /** {@inheritDoc} */ + public void setWSSEUsages(List newUsages) { + usages = prepareForAssignment(usages, newUsages); + manageQualifiedAttributeNamespace(UsageBearing.WSSE_USAGE_ATTR_NAME, !usages.isEmpty()); + } + + /** {@inheritDoc} */ + public String getWSUId() { + return id; + } + + /** {@inheritDoc} */ + public void setWSUId(String newId) { + String oldId = id; + id = prepareForAssignment(id, newId); + registerOwnID(oldId, id); + manageQualifiedAttributeNamespace(IdBearing.WSU_ID_ATTR_NAME, id != null); + } + + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List children = new ArrayList(); + + if (!getUnknownXMLObjects().isEmpty()) { + children.addAll(getUnknownXMLObjects()); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityTokenReferenceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityTokenReferenceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityTokenReferenceMarshaller.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import java.util.List; + +import org.opensaml.ws.wssecurity.SecurityTokenReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * SecurityTokenReferenceMarshaller. + * + */ +public class SecurityTokenReferenceMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + SecurityTokenReference str = (SecurityTokenReference) xmlObject; + + if (!DatatypeHelper.isEmpty(str.getWSUId())) { + XMLHelper.marshallAttribute(SecurityTokenReference.WSU_ID_ATTR_NAME, str.getWSUId(), domElement, true); + } + + List usages = str.getWSSEUsages(); + if (usages != null && ! usages.isEmpty()) { + XMLHelper.marshallAttribute(SecurityTokenReference.WSSE_USAGE_ATTR_NAME, usages, domElement, false); + } + + XMLHelper.marshallAttributeMap(str.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityTokenReferenceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityTokenReferenceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityTokenReferenceUnmarshaller.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.SecurityTokenReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * SecurityTokenReferenceUnmarshaller. + */ +public class SecurityTokenReferenceUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + SecurityTokenReference str = (SecurityTokenReference) parentXMLObject; + + str.getUnknownXMLObjects().add(childXMLObject); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + SecurityTokenReference str = (SecurityTokenReference) xmlObject; + + QName attribQName = + XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute.getPrefix()); + if (SecurityTokenReference.WSU_ID_ATTR_NAME.equals(attribQName)) { + str.setWSUId(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else if (SecurityTokenReference.WSSE_USAGE_ATTR_NAME.equals(attribQName)) { + str.setWSSEUsages(XMLHelper.getAttributeValueAsList(attribute)); + } else { + XMLHelper.unmarshallToAttributeMap(str.getUnknownAttributes(), attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SecurityUnmarshaller.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Security; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * SecurityUnmarshaller. + * + */ +public class SecurityUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Security security = (Security) xmlObject; + XMLHelper.unmarshallToAttributeMap(security.getUnknownAttributes(), attribute); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Security security = (Security) parentXMLObject; + security.getUnknownXMLObjects().add(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SignatureConfirmationBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SignatureConfirmationBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SignatureConfirmationBuilder.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.SignatureConfirmation; + +/** + * SignatureConfirmationBuilder. + * + */ +public class SignatureConfirmationBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public SignatureConfirmation buildObject() { + return buildObject(SignatureConfirmation.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public SignatureConfirmation buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SignatureConfirmationImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SignatureConfirmationImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SignatureConfirmationImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SignatureConfirmationImpl.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.IdBearing; +import org.opensaml.ws.wssecurity.SignatureConfirmation; + +/** + * SignatureConfirmationImpl. + */ +public class SignatureConfirmationImpl extends AbstractWSSecurityObject implements SignatureConfirmation { + + /** wsu:Id attribute value. */ + private String id; + + /** the Value attribute value. */ + private String value; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public SignatureConfirmationImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setValue(String newValue) { + value = prepareForAssignment(value, newValue); + } + + /** {@inheritDoc} */ + public String getWSUId() { + return id; + } + + /** {@inheritDoc} */ + public void setWSUId(String newId) { + String oldId = id; + id = prepareForAssignment(id, newId); + registerOwnID(oldId, id); + manageQualifiedAttributeNamespace(IdBearing.WSU_ID_ATTR_NAME, id != null); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SignatureConfirmationMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SignatureConfirmationMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SignatureConfirmationMarshaller.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.SignatureConfirmation; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * SignatureConfirmationMarshaller. + */ +public class SignatureConfirmationMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + SignatureConfirmation sc = (SignatureConfirmation) xmlObject; + + if (!DatatypeHelper.isEmpty(sc.getWSUId())) { + XMLHelper.marshallAttribute(SignatureConfirmation.WSU_ID_ATTR_NAME, sc.getWSUId(), domElement, true); + } + if (!DatatypeHelper.isEmpty(sc.getValue())) { + domElement.setAttributeNS(null, SignatureConfirmation.VALUE_ATTRIB_NAME, sc.getValue()); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SignatureConfirmationUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SignatureConfirmationUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/SignatureConfirmationUnmarshaller.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.SignatureConfirmation; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * SignatureConfirmationUnmarshaller. + */ +public class SignatureConfirmationUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + SignatureConfirmation sc = (SignatureConfirmation) xmlObject; + + QName attrName = + XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute.getPrefix()); + if (SignatureConfirmation.WSU_ID_ATTR_NAME.equals(attrName)) { + sc.setWSUId(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else if (SignatureConfirmation.VALUE_ATTRIB_NAME.equals(attribute.getLocalName())) { + sc.setValue(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TimestampBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TimestampBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TimestampBuilder.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Timestamp; + +/** + * TimestampBuilder. + * + */ +public class TimestampBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public Timestamp buildObject() { + return buildObject(Timestamp.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Timestamp buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new TimestampImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TimestampImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TimestampImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TimestampImpl.java 17 Aug 2012 15:09:01 -0000 1.1 @@ -0,0 +1,132 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.Created; +import org.opensaml.ws.wssecurity.Expires; +import org.opensaml.ws.wssecurity.IdBearing; +import org.opensaml.ws.wssecurity.Timestamp; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.ws.wssecurity.Timestamp}. + * + */ +public class TimestampImpl extends AbstractWSSecurityObject implements Timestamp { + + /** wsu:Timestamp/@wsu:Id attribute. */ + private String id; + + /** wsu:Timestamp/wsu:Created element. */ + private Created created; + + /** wsu:Timestamp/wsu:Expires element. */ + private Expires expires; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public TimestampImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public Created getCreated() { + return created; + } + + /** {@inheritDoc} */ + public Expires getExpires() { + return expires; + } + + /** {@inheritDoc} */ + public void setCreated(Created newCreated) { + created = prepareForAssignment(created, newCreated); + } + + /** {@inheritDoc} */ + public void setExpires(Expires newExpires) { + expires = prepareForAssignment(expires, newExpires); + } + + /** {@inheritDoc} */ + public String getWSUId() { + return id; + } + + /** {@inheritDoc} */ + public void setWSUId(String newId) { + String oldId = id; + id = prepareForAssignment(id, newId); + registerOwnID(oldId, id); + manageQualifiedAttributeNamespace(IdBearing.WSU_ID_ATTR_NAME, id != null); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (created != null) { + children.add(created); + } + if (expires != null) { + children.add(expires); + } + if (!getUnknownXMLObjects().isEmpty()) { + children.addAll(getUnknownXMLObjects()); + } + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TimestampMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TimestampMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TimestampMarshaller.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Timestamp; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * TimestampMarshaller. + * + */ +public class TimestampMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Timestamp timestamp = (Timestamp) xmlObject; + + if (!DatatypeHelper.isEmpty(timestamp.getWSUId())) { + XMLHelper.marshallAttribute(Timestamp.WSU_ID_ATTR_NAME, timestamp.getWSUId(), domElement, true); + } + + XMLHelper.marshallAttributeMap(timestamp.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TimestampUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TimestampUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TimestampUnmarshaller.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.Created; +import org.opensaml.ws.wssecurity.Expires; +import org.opensaml.ws.wssecurity.Timestamp; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * TimestampUnmarshaller. + * + */ +public class TimestampUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Timestamp timestamp = (Timestamp) parentXMLObject; + + if (childXMLObject instanceof Created) { + timestamp.setCreated((Created) childXMLObject); + } else if (childXMLObject instanceof Expires) { + timestamp.setExpires((Expires) childXMLObject); + } else { + timestamp.getUnknownXMLObjects().add(childXMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Timestamp timestamp = (Timestamp) xmlObject; + + QName attrName = + XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute.getPrefix()); + if (Timestamp.WSU_ID_ATTR_NAME.equals(attrName)) { + timestamp.setWSUId(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else { + XMLHelper.unmarshallToAttributeMap(timestamp.getUnknownAttributes(), attribute); + } + + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TransformationParametersBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TransformationParametersBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TransformationParametersBuilder.java 17 Aug 2012 15:08:58 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.TransformationParameters; + +/** + * TransformationParametersBuilder. + */ +public class TransformationParametersBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public TransformationParameters buildObject() { + return buildObject(TransformationParameters.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public TransformationParameters buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new TransformationParametersImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TransformationParametersImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TransformationParametersImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TransformationParametersImpl.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.TransformationParameters; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * TransformationParametersImpl implements the <wsse:TransformationParameters> element. + * + */ +public class TransformationParametersImpl extends AbstractWSSecurityObject implements TransformationParameters { + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public TransformationParametersImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (!getUnknownXMLObjects().isEmpty()) { + children.addAll(getUnknownXMLObjects()); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TransformationParametersMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TransformationParametersMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TransformationParametersMarshaller.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.TransformationParameters; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * TransformationParametersMarshaller. + * + */ +public class TransformationParametersMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + TransformationParameters tp = (TransformationParameters) xmlObject; + XMLHelper.marshallAttributeMap(tp.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TransformationParametersUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TransformationParametersUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/TransformationParametersUnmarshaller.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.TransformationParameters; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * TransformationParametersUnmarshaller. + * + */ +public class TransformationParametersUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + TransformationParameters tp = (TransformationParameters) xmlObject; + XMLHelper.unmarshallToAttributeMap(tp.getUnknownAttributes(), attribute); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + TransformationParameters tp = (TransformationParameters) parentXMLObject; + tp.getUnknownXMLObjects().add(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameBuilder.java 17 Aug 2012 15:08:59 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Username; + +/** + * UsernameBuilder. + */ +public class UsernameBuilder extends AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public Username buildObject() { + return buildObject(Username.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Username buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new UsernameImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameImpl.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.Username; + +/** + * Implementation of {@link Username}. + */ +public class UsernameImpl extends AttributedStringImpl implements Username { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the elements + */ + public UsernameImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameMarshaller.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +/** + * UsernameMarshaller. + */ +public class UsernameMarshaller extends AttributedStringMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameTokenBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameTokenBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameTokenBuilder.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.UsernameToken; + +/** + * UsernameTokenBuilder. + */ +public class UsernameTokenBuilder extends + AbstractWSSecurityObjectBuilder { + + /** {@inheritDoc} */ + public UsernameToken buildObject() { + return buildObject(UsernameToken.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public UsernameToken buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new UsernameTokenImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameTokenImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameTokenImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameTokenImpl.java 17 Aug 2012 15:09:02 -0000 1.1 @@ -0,0 +1,114 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.IdBearing; +import org.opensaml.ws.wssecurity.Username; +import org.opensaml.ws.wssecurity.UsernameToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * Implementation of {@link UsernameToken}. + */ +public class UsernameTokenImpl extends AbstractWSSecurityObject implements UsernameToken { + + /** The <wsu:Id> attribute value. */ + private String id; + + /** The <wsse:Username> child element. */ + private Username username; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public UsernameTokenImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public Username getUsername() { + return username; + } + + /** {@inheritDoc} */ + public void setUsername(Username newUsername) { + username = prepareForAssignment(username, newUsername); + } + + /** {@inheritDoc} */ + public String getWSUId() { + return id; + } + + /** {@inheritDoc} */ + public void setWSUId(String newId) { + String oldId = id; + id = prepareForAssignment(id, newId); + registerOwnID(oldId, id); + manageQualifiedAttributeNamespace(IdBearing.WSU_ID_ATTR_NAME, id != null); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (username != null) { + children.add(username); + } + + if (!getUnknownXMLObjects().isEmpty()) { + children.addAll(getUnknownXMLObjects()); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameTokenMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameTokenMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameTokenMarshaller.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import org.opensaml.ws.wssecurity.UsernameToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * UsernameTokenMarshaller. + */ +public class UsernameTokenMarshaller extends AbstractWSSecurityObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + UsernameToken usernameToken = (UsernameToken) xmlObject; + + if (!DatatypeHelper.isEmpty(usernameToken.getWSUId())) { + XMLHelper.marshallAttribute(UsernameToken.WSU_ID_ATTR_NAME, usernameToken.getWSUId(), domElement, true); + } + + XMLHelper.marshallAttributeMap(usernameToken.getUnknownAttributes(), domElement); + + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameTokenUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameTokenUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameTokenUnmarshaller.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.Username; +import org.opensaml.ws.wssecurity.UsernameToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * UsernameUnmarshaller. + */ +public class UsernameTokenUnmarshaller extends AbstractWSSecurityObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + UsernameToken token = (UsernameToken) parentXMLObject; + if (childXMLObject instanceof Username) { + token.setUsername((Username) childXMLObject); + } else { + token.getUnknownXMLObjects().add(childXMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + UsernameToken token = (UsernameToken) xmlObject; + + QName attribQName = + XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute.getPrefix()); + if (UsernameToken.WSU_ID_ATTR_NAME.equals(attribQName)) { + token.setWSUId(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else { + XMLHelper.unmarshallToAttributeMap(token.getUnknownAttributes(), attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/impl/UsernameUnmarshaller.java 17 Aug 2012 15:09:00 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.impl; + +/** + * UsernameUnmarshaller. + */ +public class UsernameUnmarshaller extends AttributedStringUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wssecurity/util/WSSecurityHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wssecurity/util/WSSecurityHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wssecurity/util/WSSecurityHelper.java 17 Aug 2012 15:09:14 -0000 1.1 @@ -0,0 +1,194 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wssecurity.util; + +import java.util.List; + +import org.opensaml.ws.wssecurity.IdBearing; +import org.opensaml.ws.wssecurity.TokenTypeBearing; +import org.opensaml.ws.wssecurity.UsageBearing; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.LazyList; +import org.opensaml.xml.util.XMLHelper; + +/** + * Helper methods for working with WS-Security. + */ +public final class WSSecurityHelper { + + /** + * Private constructor. + */ + private WSSecurityHelper() { + } + + /** + * Adds a wsu:Id attribute to the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * @param id the Id value + */ + public static void addWSUId(XMLObject soapObject, String id) { + if (soapObject instanceof IdBearing) { + ((IdBearing)soapObject).setWSUId(id); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + ((AttributeExtensibleXMLObject)soapObject).getUnknownAttributes() + .put(IdBearing.WSU_ID_ATTR_NAME, id); + } else { + throw new IllegalArgumentException("Specified object was neither IdBearing nor AttributeExtensible"); + } + } + + /** + * Gets the wsu:Id attribute from a given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * + * @return the value of the Id attribute, or null if not present + */ + public static String getWSUId(XMLObject soapObject) { + String value = null; + if (soapObject instanceof IdBearing) { + value = DatatypeHelper.safeTrimOrNullString(((IdBearing)soapObject).getWSUId()); + if (value != null) { + return value; + } + } + if (soapObject instanceof AttributeExtensibleXMLObject) { + value = DatatypeHelper.safeTrimOrNullString(((AttributeExtensibleXMLObject)soapObject) + .getUnknownAttributes().get(IdBearing.WSU_ID_ATTR_NAME)); + return value; + } + return null; + } + + /** + * Adds a wsse11:TokenType attribute to the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * @param tokenType the tokenType value + */ + public static void addWSSE11TokenType(XMLObject soapObject, String tokenType) { + if (soapObject instanceof TokenTypeBearing) { + ((TokenTypeBearing)soapObject).setWSSE11TokenType(tokenType); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + ((AttributeExtensibleXMLObject)soapObject).getUnknownAttributes() + .put(TokenTypeBearing.WSSE11_TOKEN_TYPE_ATTR_NAME, tokenType); + } else { + throw new IllegalArgumentException("Specified object was neither TokenTypeBearing nor AttributeExtensible"); + } + } + + /** + * Gets the wsse11:TokenType attribute from a given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * + * @return the value of the tokenType attribute, or null if not present + */ + public static String getWSSE11TokenType(XMLObject soapObject) { + String value = null; + if (soapObject instanceof TokenTypeBearing) { + value = DatatypeHelper.safeTrimOrNullString(((TokenTypeBearing)soapObject).getWSSE11TokenType()); + if (value != null) { + return value; + } + } + if (soapObject instanceof AttributeExtensibleXMLObject) { + value = DatatypeHelper.safeTrimOrNullString(((AttributeExtensibleXMLObject)soapObject) + .getUnknownAttributes().get(TokenTypeBearing.WSSE11_TOKEN_TYPE_ATTR_NAME)); + return value; + } + return null; + } + + /** + * Adds a single wsse:Usage value to the given SOAP object. If an existing wsse:Usage + * attribute is present, the given usage will be added to the existing list. + * + * @param soapObject the SOAP object to add the attribute to + * @param usage the usage to add + */ + public static void addWSSEUsage(XMLObject soapObject, String usage) { + if (soapObject instanceof UsageBearing) { + UsageBearing usageBearing = (UsageBearing) soapObject; + List list = usageBearing.getWSSEUsages(); + if (list == null) { + list = new LazyList(); + usageBearing.setWSSEUsages(list); + } + list.add(usage); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + AttributeMap am = ((AttributeExtensibleXMLObject)soapObject).getUnknownAttributes(); + String list = am.get(UsageBearing.WSSE_USAGE_ATTR_NAME); + if (list == null) { + list = usage; + } else { + list = list + " " + usage; + } + am.put(UsageBearing.WSSE_USAGE_ATTR_NAME, list); + } else { + throw new IllegalArgumentException("Specified object was neither UsageBearing nor AttributeExtensible"); + } + } + + /** + * Adds a wsse:Usage attribute to the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * @param usages the list of usages to add + */ + public static void addWSSEUsages(XMLObject soapObject, List usages) { + if (soapObject instanceof UsageBearing) { + ((UsageBearing)soapObject).setWSSEUsages(usages); + } else if (soapObject instanceof AttributeExtensibleXMLObject) { + ((AttributeExtensibleXMLObject)soapObject).getUnknownAttributes() + .put(UsageBearing.WSSE_USAGE_ATTR_NAME, + DatatypeHelper.listToStringValue(usages, " ")); + } else { + throw new IllegalArgumentException("Specified object was neither UsageBearing nor AttributeExtensible"); + } + } + + /** + * Gets the list value of the wsse:Usage attribute from the given SOAP object. + * + * @param soapObject the SOAP object to add the attribute to + * + * @return the list of usages, or null if not present + */ + public static List getWSSEUsages(XMLObject soapObject) { + if (soapObject instanceof UsageBearing) { + List value = ((UsageBearing)soapObject).getWSSEUsages(); + if (value != null) { + return value; + } + } + if (soapObject instanceof AttributeExtensibleXMLObject) { + String value = DatatypeHelper.safeTrimOrNullString(((AttributeExtensibleXMLObject)soapObject) + .getUnknownAttributes().get(UsageBearing.WSSE_USAGE_ATTR_NAME)); + if (value != null) { + DatatypeHelper.stringToList(value, XMLHelper.LIST_DELIMITERS); + } + } + return null; + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/AllowPostdating.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/AllowPostdating.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/AllowPostdating.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +/** + * The wst:AllowPostdating element. + * + * @see "WS-Trust 1.3, Chapter 5 Renewal Binding." + * + */ +public interface AllowPostdating extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "AllowPostdating"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AllowPostdatingType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/AuthenticationType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/AuthenticationType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/AuthenticationType.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:AuthenticationType element. + * + * @see "WS-Trust 1.3, Chapter 9.2 Key and Encryption Requirements." + * + */ +public interface AuthenticationType extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "AuthenticationType"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Authenticator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Authenticator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Authenticator.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The wst:Authenticator element. + * + * @see "WS-Trust 1.3, Chapter 8.9 Authenticating Exchanges." + * + */ +public interface Authenticator extends ElementExtensibleXMLObject, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Authenticator"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AuthenticatorType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Returns the wst:CombinedHash child element. + * + * @return the {@link CombinedHash} element. + */ + public CombinedHash getCombinedHash(); + + /** + * Sets the wst:CombinedHash child element. + * + * @param combinedHash the {@link CombinedHash} to set. + */ + public void setCombinedHash(CombinedHash combinedHash); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/BinaryExchange.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/BinaryExchange.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/BinaryExchange.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.schema.XSString; + +/** + * The wst:BinaryExchange element. + * + * @see "WS-Trust 1.3, Chapter 8.3 Binary Exchanges and Negotiations." + * + */ +public interface BinaryExchange extends XSString, AttributeExtensibleXMLObject, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "BinaryExchange"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "BinaryExchangeType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** The ValueType attribute name. */ + public static final String VALUE_TYPE_ATTRIB_NAME = "ValueType"; + + /** The EncodingType attribute name. */ + public static final String ENCODING_TYPE_ATTRIB_NAME = "EncodingType"; + + /** + * Returns the ValueType attribute URI value. + * + * @return the ValueType attribute value or null. + */ + public String getValueType(); + + /** + * Sets the ValueType attribute URI value. + * + * @param newValueType the ValueType attribute value. + */ + public void setValueType(String newValueType); + + /** + * Returns the EncodingType attribute value. + * + * @return the EncodingType attribute value. + */ + public String getEncodingType(); + + /** + * Sets the EncodingType attribute value. + * + * @param newEncodingType the EncodingType attribute value. + */ + public void setEncodingType(String newEncodingType); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/BinarySecret.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/BinarySecret.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/BinarySecret.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,74 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.schema.XSBase64Binary; + +/** + * The wst:BinarySecret element. + * + * @see Entropy + * @see "WS-Trust 1.3, Chapter 3.3 Binary Secrets." + * + */ +public interface BinarySecret extends XSBase64Binary, AttributeExtensibleXMLObject, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "BinarySecret"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "BinarySecretType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** wst:BinarySecret/@Type attribute local name. */ + public static final String TYPE_ATTRIB_NAME = "Type"; + + /** Type attribute AsymmetricKey URI. */ + public static final String TYPE_ASYMMETRIC_KEY = WSTrustConstants.WST_NS + "/AsymmetricKey"; + + /** Type attribute SymmetricKey URI. */ + public static final String TYPE_SYMMETRIC_KEY = WSTrustConstants.WST_NS + "/SymmetricKey"; + + /** Type attribute Nonce URI. */ + public static final String TYPE_NONCE = WSTrustConstants.WST_NS + "/Nonce"; + + /** + * Returns the wst:BinarySecret/@Type attribute value. + * + * @return the Type attribute value. + */ + public String getType(); + + /** + * Sets the wst:BinarySecret/@Type attribute value. + * + * @param type the Type attribute value to set. + */ + public void setType(String type); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/CancelTarget.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/CancelTarget.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/CancelTarget.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * The wst:CancelTarget element. + * + * @see "WS-Trust 1.3, Chapter 6 Cancel Binding." + * + */ +public interface CancelTarget extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "CancelTarget"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "CancelTargetType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Get the unknown child element. + * + * @return the child element + */ + public XMLObject getUnknownXMLObject(); + + /** + * Set the unknown child element. + * + * @param unknownObject the new child element + */ + public void setUnknownXMLObject(XMLObject unknownObject); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/CanonicalizationAlgorithm.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/CanonicalizationAlgorithm.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/CanonicalizationAlgorithm.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:CanonicalizationAlgorithm element. + * + * @see "WS-Trust 1.3, Chapter 9.2 Key and Encryption Requirements." + * + */ +public interface CanonicalizationAlgorithm extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "CanonicalizationAlgorithm"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Challenge.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Challenge.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Challenge.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSString; + +/** + * The wst:Challenge element. + * + * @see "WS-Trust 1.3, Chapter 8.2 Signature Challenges." + * + */ +public interface Challenge extends XSString, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Challenge"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Claims.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Claims.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Claims.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The wst:Claims element. + * + * @see "WS-Trust 1.3, Chapter 4.1 Requesting a Security Token." + * + */ +public interface Claims extends AttributeExtensibleXMLObject, ElementExtensibleXMLObject, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Claims"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ClaimsType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** The wst:Claims/@Dialect attribute local name. */ + public static final String DIALECT_ATTRIB_NAME = "Dialect"; + + /** + * Returns the wst:Claims/@Dialect attribute value. + * + * @return the Dialect attribute value + */ + public String getDialect(); + + /** + * Sets the wst:Claims/@Dialect attribute value. + * + * @param dialect the Dialect attribute value. + */ + public void setDialect(String dialect); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Code.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Code.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Code.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:Code element within a wst:Status element. + * + * @see Status + * @see "WS-Trust 1.3, Chapter 7 Validation Binding." + * + */ +public interface Code extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Code"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "StatusCodeOpenEnum"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Status/Code 'valid' URI value . */ + public static final String VALID= WSTrustConstants.WST_NS + "/status/valid"; + + /** Status/Code 'invalid' URI value. */ + public static final String INVALID= WSTrustConstants.WST_NS + "/status/invalid"; + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/CombinedHash.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/CombinedHash.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/CombinedHash.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSBase64Binary; + +/** + * The wst:CombinedHash element. + * + * @see "WS-Trust 1.3, Chapter 8.9 Authenticating Exchanges." + * + */ +public interface CombinedHash extends XSBase64Binary, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "CombinedHash"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** The fixed string "AUTH-HASH" used in computing the value of the combined hash. */ + public static final String AUTH_HASH = "AUTH-HASH"; +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/ComputedKey.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/ComputedKey.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/ComputedKey.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:ComputedKey element. + * + * @see "WS-Trust 1.3, Chapter 4.4.4 Returning Computed Keys." + * + */ +public interface ComputedKey extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "ComputedKey"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ComputedKeyOpenEnum"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** The ComputedKey PSHA1 URI. */ + public static final String PSHA1= WSTrustConstants.WST_NS + "/CK/PSHA1"; + + /** The ComputedKey HASH URI. */ + public static final String HASH= WSTrustConstants.WST_NS + "/CK/HASH"; +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/ComputedKeyAlgorithm.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/ComputedKeyAlgorithm.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/ComputedKeyAlgorithm.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:ComputedKeyAlgorithm element. + * + * @see "WS-Trust 1.3, Chapter 9.2 Key and Encryption Requirements." + * + */ +public interface ComputedKeyAlgorithm extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "ComputedKeyAlgorithm"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Delegatable.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Delegatable.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Delegatable.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSBoolean; + +/** + * The wst:Delegatable element. + * + * @see "WS-Trust 1.3, Chapter 9.3 Delegation and Forwarding Requirements." + * + */ +public interface Delegatable extends XSBoolean, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Delegatable"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/DelegateTo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/DelegateTo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/DelegateTo.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * The wst:DelegateTo element. + * + * @see "WS-Trust 1.3, Chapter 9.3 Delegation and Forwarding Requirements." + * + */ +public interface DelegateTo extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "DelegateTo"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "DelegateToType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Get the unknown child element. + * + * @return the child element + */ + public XMLObject getUnknownXMLObject(); + + /** + * Set the unknown child element. + * + * @param unknownObject the new child element + */ + public void setUnknownXMLObject(XMLObject unknownObject); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/EncryptWith.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/EncryptWith.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/EncryptWith.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:EncryptWith element. + * + * @see "WS-Trust 1.3, Chapter 9.2 Key and Encryption Requirements." + * + */ +public interface EncryptWith extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "EncryptWith"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Encryption.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Encryption.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Encryption.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * The wst:Encryption element. + * + * @see "WS-Trust 1.3, Chapter 9.2 Key and Encryption Requirements." + * + */ +public interface Encryption extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Encryption"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "EncryptionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Get the unknown child element. + * + * @return the child element + */ + public XMLObject getUnknownXMLObject(); + + /** + * Set the unknown child element. + * + * @param unknownObject the new child element + */ + public void setUnknownXMLObject(XMLObject unknownObject); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/EncryptionAlgorithm.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/EncryptionAlgorithm.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/EncryptionAlgorithm.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:EncryptionAlgorithm element. + * + * @see "WS-Trust 1.3, Chapter 9.2 Key and Encryption Requirements." + * + */ +public interface EncryptionAlgorithm extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "EncryptionAlgorithm"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Entropy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Entropy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Entropy.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The wst:Entropy element. + * + * @see "WS-Trust 1.3, Chapter 4.1 Requesting a Security Token." + * + */ +public interface Entropy extends AttributeExtensibleXMLObject, ElementExtensibleXMLObject, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME= "Entropy"; + + /** Default element name. */ + public static final QName ELEMENT_NAME= + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "EntropyType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** The wst:Claims/@Dialect attribute local name. */ + public static final String DIALECT_ATTRIB_NAME = "EntropyType"; + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Forwardable.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Forwardable.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Forwardable.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSBoolean; + +/** + * The wst:Forwardable element. + * + * @see "WS-Trust 1.3, Chapter 9.3 Delegation and Forwarding Requirements." + * + */ +public interface Forwardable extends XSBoolean, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME= "Forwardable"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/IssuedTokens.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/IssuedTokens.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/IssuedTokens.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +/** + * The wst:IssuedTokens element. + * + * @see "WS-Trust 1.3, Chapter 4.5 Returning Security Tokens in Headers." + * + */ +public interface IssuedTokens extends RequestSecurityTokenResponseCollection { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "IssuedTokens"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Issuer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Issuer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Issuer.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wsaddressing.EndpointReferenceType; + +/** + * The wst:Issuer element. + * + * @see "WS-Trust 1.3, Chapter 9.1 On-Behalf-Of Parameters." + * + */ +public interface Issuer extends EndpointReferenceType, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Issuer"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/KeyExchangeToken.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/KeyExchangeToken.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/KeyExchangeToken.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The wst:KeyExchangeToken element. + * + * @see "WS-Trust 1.3, Chapter 8.4 Key Exchange Tokens." + * + */ +public interface KeyExchangeToken extends ElementExtensibleXMLObject, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "KeyExchangeToken"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "KeyExchangeTokenType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/KeySize.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/KeySize.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/KeySize.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSInteger; + +/** + * The wst:KeySize element. + * + */ +public interface KeySize extends XSInteger, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "KeySize"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/KeyType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/KeyType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/KeyType.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:KeyType element. + * + * @see "WS-Trust 1.3, Chapter 9.2 Key and Encryption Requirements." + * + */ +public interface KeyType extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "KeyType"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "KeyTypeOpenEnum"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** The KeyType PublicKey URI. */ + public static final String PUBLIC_KEY = WSTrustConstants.WST_NS + "/PublicKey"; + + /** The KeyType SymmetricKey URI. */ + public static final String SYMMETRIC_KEY = WSTrustConstants.WST_NS + "/SymmetricKey"; + + /** The KeyType Bearer URI. */ + public static final String BEARER = WSTrustConstants.WST_NS + "/Bearer"; + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/KeyWrapAlgorithm.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/KeyWrapAlgorithm.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/KeyWrapAlgorithm.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:KeyWrapAlgorithm element. + * + * @see "WS-Trust 1.3, Chapter 9.2 Key and Encryption Requirements." + * + */ +public interface KeyWrapAlgorithm extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "KeyWrapAlgorithm"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Lifetime.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Lifetime.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Lifetime.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.Created; +import org.opensaml.ws.wssecurity.Expires; + +/** + * The wst:Lifetime element. + * + */ +public interface Lifetime extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Lifetime"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "LifetimeType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Returns the wsu:Created child element. + * + * @return the {@link Created} child element or null. + */ + public Created getCreated(); + + /** + * Sets the wsu:Created child element. + * + * @param created the {@link Created} child element to set. + */ + public void setCreated(Created created); + + /** + * Returns the wsu:Expires child element. + * + * @return the {@link Expires} child element or null. + */ + public Expires getExpires(); + + /** + * Sets the wsu:Expires child element. + * + * @param expires the {@link Expires} child element. + */ + public void setExpires(Expires expires); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/OnBehalfOf.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/OnBehalfOf.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/OnBehalfOf.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * The wst:OnBehalfOf element. + * + * @see "WS-Trust 1.3, Chapter 9.1 On-Behalf-Of Parameters." + * + */ +public interface OnBehalfOf extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "OnBehalfOf"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "OnBehalfOfType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Get the unknown child element. + * + * @return the child element + */ + public XMLObject getUnknownXMLObject(); + + /** + * Set the unknown child element. + * + * @param unknownObject the new child element + */ + public void setUnknownXMLObject(XMLObject unknownObject); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Participant.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Participant.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Participant.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +/** + * The wst:Participant element. + * + * @see "WS-Trust 1.3, Chapter 9.5 Authorized Token Participants." + * + */ +public interface Participant extends ParticipantType { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Participant"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/ParticipantType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/ParticipantType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/ParticipantType.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * Interface ParticipantType complex type. + * + */ +public interface ParticipantType extends WSTrustObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ParticipantType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Get the unknown child element. + * + * @return the child element + */ + public XMLObject getUnknownXMLObject(); + + /** + * Set the unknown child element. + * + * @param unknownObject the new child element + */ + public void setUnknownXMLObject(XMLObject unknownObject); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Participants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Participants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Participants.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The wst:Participants element. + * + * @see "WS-Trust 1.3, Chapter 9.5 Authorized Token Participants." + * + */ +public interface Participants extends ElementExtensibleXMLObject, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Participants"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ParticipantsType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Returns the wst:Primary child element. + * + * @return the {@link Primary} child element or null. + */ + public Primary getPrimary(); + + /** + * Sets the wst:Primary child element. + * + * @param primary the {@link Primary} child element to set. + */ + public void setPrimary(Primary primary); + + /** + * Returns the list of wst:Participant child elements . + * + * @return the list of {@link Participant} child elements + */ + public List getParticipants(); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Primary.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Primary.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Primary.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +/** + * The wst:Primary element. + * + * @see "WS-Trust 1.3, Chapter 9.5 Authorized Token Participants." + * + */ +public interface Primary extends ParticipantType { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Primary"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/ProofEncryption.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/ProofEncryption.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/ProofEncryption.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * The wst:ProofEncryption element. + * + * @see "WS-Trust 1.3, Chapter 9.2 Key and Encryption Requirements." + * + */ +public interface ProofEncryption extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "ProofEncryption"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ProofEncryptionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Get the unknown child element. + * + * @return the child element + */ + public XMLObject getUnknownXMLObject(); + + /** + * Set the unknown child element. + * + * @param unknownObject the new child element + */ + public void setUnknownXMLObject(XMLObject unknownObject); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Reason.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Reason.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Reason.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSString; + +/** + * The <wst:Reason> child element of a <wst:Status> element. + * + * @see Status + * + */ +public interface Reason extends XSString, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Reason"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RenewTarget.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RenewTarget.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RenewTarget.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * The wst:RenewTarget element. + * + * @see "WS-Trust 1.3, Chapter 5 Renewal Binding." + * + */ +public interface RenewTarget extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME= "RenewTarget"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RenewTargetType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Get the unknown child element. + * + * @return the child element + */ + public XMLObject getUnknownXMLObject(); + + /** + * Set the unknown child element. + * + * @param unknownObject the new child element + */ + public void setUnknownXMLObject(XMLObject unknownObject); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Renewing.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Renewing.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Renewing.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,108 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * The wst:Renewing element. + * + * @see "WS-Trust 1.3, Chapter 5 Renewal Binding." + * + */ +public interface Renewing extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Renewing"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RenewingType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** The wst:Renewing/@Allow attribute local name. */ + public static final String ALLOW_ATTRIB_NAME = "Allow"; + + /** The wst:Renewing/@OK attribute local name. */ + public static final String OK_ATTRIB_NAME = "OK"; + + /** + * Returns the wst:Renewing/@Allow attribute value. + * + * @return the Allow attribute value + */ + public Boolean isAllow(); + + /** + * Returns the wst:Renewing/@Allow attribute value. + * + * @return the Allow attribute value + */ + public XSBooleanValue isAllowXSBoolean(); + + /** + * Sets the wst:Renewing/@Allow attribute value. + * + * @param allow the Allow attribute value. + */ + public void setAllow(Boolean allow); + + /** + * Sets the wst:Renewing/@Allow attribute value. + * + * @param allow the Allow attribute value. + */ + public void setAllow(XSBooleanValue allow); + + /** + * Returns the wst:Renewing/@OK attribute value. + * + * @return the OK attribute value + */ + public Boolean isOK(); + + /** + * Returns the wst:Renewing/@OK attribute value. + * + * @return the OK attribute value + */ + public XSBooleanValue isOKXSBoolean(); + + /** + * Sets the wst:Renewing/@OK attribute value. + * + * @param ok the OK attribute value. + */ + public void setOK(Boolean ok); + + /** + * Sets the wst:Renewing/@OK attribute value. + * + * @param ok the OK attribute value. + */ + public void setOK(XSBooleanValue ok); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestKET.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestKET.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestKET.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +/** + * The wst:RequestKET element. + * + * @see "WS-Trust 1.3, Chapter 8.4 Key Exchange Tokens." + * + */ +public interface RequestKET extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "RequestKET"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestKETType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestSecurityToken.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestSecurityToken.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestSecurityToken.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The wst:RequestSecurityToken element. + * + * @see "WS-Trust 1.3 Specification" + * + */ +public interface RequestSecurityToken extends ElementExtensibleXMLObject, AttributeExtensibleXMLObject, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME= "RequestSecurityToken"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestSecurityTokenType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * The Context attribute name. + */ + public static final String CONTEXT_ATTRIB_NAME = "Context"; + + /** + * Returns the Context attribute value. + * + * @return The Context attribute value or null. + */ + public String getContext(); + + /** + * Sets the Context attribute value. + * + * @param context The Context attribute value + */ + public void setContext(String context); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestSecurityTokenCollection.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestSecurityTokenCollection.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestSecurityTokenCollection.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import java.util.List; + +import javax.xml.namespace.QName; + +/** + * The wst:RequestSecurityTokenCollection element. + * + * @see "WS-Trust 1.3 Specification" + * + */ +public interface RequestSecurityTokenCollection extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "RequestSecurityTokenCollection"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestSecurityTokenCollectionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Returns the list of wst:RequestSecurityToken child elements + * contained in the RSTC. + * + * @return the list of {@link RequestSecurityToken}s. + */ + public List getRequestSecurityTokens(); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestSecurityTokenResponse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestSecurityTokenResponse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestSecurityTokenResponse.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * The wst:RequestSecurityTokenResponse element. + * + * @see "WS-Trust 1.3 Specification" + * + */ +public interface RequestSecurityTokenResponse extends ElementExtensibleXMLObject, AttributeExtensibleXMLObject, + WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME= "RequestSecurityTokenResponse"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestSecurityTokenResponseType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * The Context attribute name. + */ + public static final String CONTEXT_ATTRIB_NAME = "Context"; + + /** + * Returns the Context attribute value. + * + * @return The Context attribute value or null. + */ + public String getContext(); + + /** + * Sets the Context attribute value. + * + * @param context The Context attribute value + */ + public void setContext(String context); + +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestSecurityTokenResponseCollection.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestSecurityTokenResponseCollection.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestSecurityTokenResponseCollection.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; + +/** + * The wst:RequestSecurityTokenResponseCollection element. + * + * @see "WS-Trust 1.3 Specification" + * + */ +public interface RequestSecurityTokenResponseCollection extends AttributeExtensibleXMLObject, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "RequestSecurityTokenResponseCollection"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestSecurityTokenResponseCollectionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Returns the list of wst:RequestSecurityTokenResponse child elements. + * + * @return The list of {@link RequestSecurityTokenResponse}s. + */ + public List getRequestSecurityTokenResponses(); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestType.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:RequestType element. + * + */ +public interface RequestType extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "RequestType"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestTypeOpenEnum"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + // Single action request types + + /** RequestType Issue URI. */ + public static final String ISSUE = WSTrustConstants.WST_NS + "/Issue"; + + /** RequestType Renew URI. */ + public static final String RENEW = WSTrustConstants.WST_NS + "/Renew"; + + /** RequestType Cancel URI. */ + public static final String CANCEL = WSTrustConstants.WST_NS + "/Cancel"; + + /** RequestType STSCancel URI. */ + public static final String STSCANCEL = WSTrustConstants.WST_NS + "/STSCancel"; + + /** RequestType Validate URI. */ + public static final String VALIDATE = WSTrustConstants.WST_NS + "/Validate"; + + /** RequestType Key Exchange Token (KET) URI. */ + public static final String KET = WSTrustConstants.WST_NS + "/KET"; + + // Batch action request types + + /** RequestType BatchIssue URI. */ + public static final String BATCH_ISSUE = WSTrustConstants.WST_NS + "/BatchIssue"; + + /** RequestType BatchRenew URI. */ + public static final String BATCH_RENEW = WSTrustConstants.WST_NS + "/BatchRenew"; + + /** RequestType BatchCancel URI. */ + public static final String BATCH_CANCEL = WSTrustConstants.WST_NS + "/BatchCancel"; + + /** RequestType BatchValidate URI. */ + public static final String BATCH_VALIDATE = WSTrustConstants.WST_NS + "/BatchValidate"; + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedAttachedReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedAttachedReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedAttachedReference.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +/** + * The wst:RequestedAttachedReference element. + * + * @see "WS-Trust 1.3, Chapter 4.4.2 Requested References." + * + */ +public interface RequestedAttachedReference extends RequestedReferenceType { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "RequestedAttachedReference"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedProofToken.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedProofToken.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedProofToken.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * The wst:RequestedProofToken element. + * + * @see "WS-Trust 1.3, Chapters 4.4.3 Keys and Entropy" + * + */ +public interface RequestedProofToken extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "RequestedProofToken"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestedProofTokenType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Get the unknown child element. + * + * @return the child element + */ + public XMLObject getUnknownXMLObject(); + + /** + * Set the unknown child element. + * + * @param unknownObject the new child element + */ + public void setUnknownXMLObject(XMLObject unknownObject); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedReferenceType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedReferenceType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedReferenceType.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wssecurity.SecurityTokenReference; + +/** + * Interface for RequestedReferenceType complex type. + * + */ +public interface RequestedReferenceType extends WSTrustObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestedReferenceType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Returns the wsse:SecurityTokenReference child element. + * + * @return the {@link SecurityTokenReference} child element or + * null. + */ + public SecurityTokenReference getSecurityTokenReference(); + + /** + * Sets the wsse:SecurityTokenReference child element. + * + * @param securityTokenReference + * The {@link SecurityTokenReference} child element to be set. + */ + public void setSecurityTokenReference(SecurityTokenReference securityTokenReference); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedSecurityToken.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedSecurityToken.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedSecurityToken.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * The wst:RequestedSecurityToken element. + * + * @see "WS-Trust 1.3, Chapter 4.4 Returning a Security Token." + * + */ +public interface RequestedSecurityToken extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "RequestedSecurityToken"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestedSecurityTokenType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Get the unknown child element. + * + * @return the child element + */ + public XMLObject getUnknownXMLObject(); + + /** + * Set the unknown child element. + * + * @param unknownObject the new child element + */ + public void setUnknownXMLObject(XMLObject unknownObject); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedTokenCancelled.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedTokenCancelled.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedTokenCancelled.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +/** + * The wst:RequestedTokenCancelled element. + * + * @see "WS-Trust 1.3, Chapter 6 Cancel Binding." + * + */ +public interface RequestedTokenCancelled extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "RequestedTokenCancelled"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestedTokenCancelledType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedUnattachedReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedUnattachedReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/RequestedUnattachedReference.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +/** + * The wst:RequestedUnattachedReference element. + * + * @see "WS-Trust 1.3, Chapter 4.4.2 Requested References." + * + */ +public interface RequestedUnattachedReference extends RequestedReferenceType { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "RequestedUnattachedReference"; + + /** Default element name */ + public final static QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/SignChallenge.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/SignChallenge.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/SignChallenge.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +/** + * The wst:SignChallenge element. + * + * @see "WS-Trust 1.3, Chapter 8.2 Signature Challenges." + * + */ +public interface SignChallenge extends SignChallengeType { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "SignChallenge"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/SignChallengeResponse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/SignChallengeResponse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/SignChallengeResponse.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +/** + * The wst:SignChallengeResponse element. + * + * @see "WS-Trust 1.3, Chapter 8.2 Signature Challenges." + * + */ +public interface SignChallengeResponse extends SignChallengeType { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME= "SignChallengeResponse"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/SignChallengeType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/SignChallengeType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/SignChallengeType.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * SignChallengeType complex type. + * + */ +public interface SignChallengeType extends AttributeExtensibleXMLObject, ElementExtensibleXMLObject, WSTrustObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "SignChallengeType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Returns the wst:Challenge child element. + * + * @return the {@link Challenge} child element or null. + */ + public Challenge getChallenge(); + + /** + * Sets the wst:Challenge child element. + * + * @param challenge the {@link Challenge} child element to set. + */ + public void setChallenge(Challenge challenge); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/SignWith.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/SignWith.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/SignWith.java 17 Aug 2012 15:08:54 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:SignWith element. + * + * @see "WS-Trust 1.3, Chapter 9.2 Key and Encryption Requirements." + * + */ +public interface SignWith extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "SignWith"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/SignatureAlgorithm.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/SignatureAlgorithm.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/SignatureAlgorithm.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:SignatureAlgorithm element. + * + * @see "WS-Trust 1.3, Chapter 9.2 Key and Encryption Requirements." + * + */ +public interface SignatureAlgorithm extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "SignatureAlgorithm"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/Status.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/Status.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/Status.java 17 Aug 2012 15:08:57 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +/** + * The wst:Status element. + * + * @see "WS-Trust 1.3, Chapter 7 Validation Binding." + * + */ +public interface Status extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "Status"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Returns the wst:Code child element. + * + * @return the {@link Code} child element or null + */ + public Code getCode(); + + /** + * Sets the wst:Code child element. + * + * @param code the {@link Code} child element to set. + */ + public void setCode(Code code); + + /** + * Returns the wst:Reason child element. + * + * @return the {@link Reason} child element or null. + */ + public Reason getReason(); + + /** + * Sets the wst:Reason child element. + * + * @param reason the {@link Reason} child element to set. + */ + public void setReason(Reason reason); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/TokenType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/TokenType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/TokenType.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.schema.XSURI; + +/** + * The wst:TokenType element. + * + */ +public interface TokenType extends XSURI, WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "TokenType"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** TokenType Status URI. */ + public static final String STATUS = WSTrustConstants.WST_NS + "/RSTR/Status"; + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/UseKey.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/UseKey.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/UseKey.java 17 Aug 2012 15:08:56 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * The wst:UseKey element. + * + * @see "WS-Trust 1.3, Chapter 9.2 Key and Encryption Requirements." + * + */ +public interface UseKey extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "UseKey"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "UseKeyType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** The wst:UseKey/@Sig attribute local name. */ + public static final String SIG_ATTRIB_NAME = "Sig"; + + /** + * Get the unknown child element. + * + * @return the child element + */ + public XMLObject getUnknownXMLObject(); + + /** + * Set the unknown child element. + * + * @param unknownObject the new child element + */ + public void setUnknownXMLObject(XMLObject unknownObject); + + /** + * Returns the wst:UseKey/@Sig attribute value. + * + * @return the Sig attribute value or null + */ + public String getSig(); + + /** + * Sets the wst:UseKey/@Sig attribute value. + * + * @param sig the Sig attribute value to set. + */ + public void setSig(String sig); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/ValidateTarget.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/ValidateTarget.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/ValidateTarget.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.XMLObject; + +/** + * The wst:ValidateTarget element. + * + * @see "WS-Trust 1.3, Chapter 7 Validation Binding." + * + */ +public interface ValidateTarget extends WSTrustObject { + + /** Element local name. */ + public static final String ELEMENT_LOCAL_NAME = "ValidateTarget"; + + /** Default element name. */ + public static final QName ELEMENT_NAME = + new QName(WSTrustConstants.WST_NS, ELEMENT_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ValidateTargetType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(WSTrustConstants.WST_NS, TYPE_LOCAL_NAME, WSTrustConstants.WST_PREFIX); + + /** + * Get the unknown child element. + * + * @return the child element + */ + public XMLObject getUnknownXMLObject(); + + /** + * Set the unknown child element. + * + * @param unknownObject the new child element + */ + public void setUnknownXMLObject(XMLObject unknownObject); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/WSTrustConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/WSTrustConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/WSTrustConstants.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,153 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import javax.xml.namespace.QName; + +/** + * The WS-Trust 1.3 constants. + * + * @see "WS-Trust 1.3 Specification" + * + */ +public final class WSTrustConstants { + + // + // WS-Trust + // + + /** WS-Trust version. */ + public static final String WST_VERSION= "1.3"; + + /** WS-Trust namespace prefix. */ + public static final String WST_PREFIX= "wst"; + + /** WS-Trust 1.3 namespace. */ + public static final String WST_NS= "http://docs.oasis-open.org/ws-sx/ws-trust/200512"; + + // + // WS-Addressing + // + + //* WS-Addressing RequestSecurityToken (RST) action URIs. + + /** WS-Addressing RequestSecurityToken (RST) action URI 'Issue'. */ + public static final String WSA_ACTION_RST_ISSUE= WST_NS + "/RST" + "/Issue"; + + /** WS-Addressing RequestSecurityToken (RST) action URI 'Cancel'. */ + public static final String WSA_ACTION_RST_CANCEL= WST_NS + "/RST" + "/Cancel"; + + /** WS-Addressing RequestSecurityToken (RST) action URI 'STSCancel'. */ + public static final String WSA_ACTION_RST_STSCANCEL= WST_NS + "/RST" + "/STSCancel"; + + /** WS-Addressing RequestSecurityToken (RST) action URI 'Validate'. */ + public static final String WSA_ACTION_RST_VALIDATE= WST_NS + "/RST" + "/Validate"; + + /** WS-Addressing RequestSecurityToken (RST) action URI 'Renew'. */ + public static final String WSA_ACTION_RST_RENEW= WST_NS + "/RST" + "/Renew"; + + /** WS-Addressing RequestSecurityToken (RST) action URI 'KET'. */ + public static final String WSA_ACTION_RST_KET= WST_NS + "/RST" + "/KET"; + + + // WS-Addressing RequestSecurityTokenResponse (RSTR) action URIs. + + /** WS-Addressing RequestSecurityTokenResponse (RSTR) action URI 'Issue'. */ + public static final String WSA_ACTION_RSTR_ISSUE= WST_NS + "/RSTR" + "/Issue"; + + /** WS-Addressing RequestSecurityTokenResponse (RSTR) action URI 'Cancel'. */ + public static final String WSA_ACTION_RSTR_CANCEL= WST_NS + "/RSTR" + "/Cancel"; + + /** WS-Addressing RequestSecurityTokenResponse (RSTR) action URI 'CancelFinal'. */ + public static final String WSA_ACTION_RSTR_CANCEL_FINAL= WST_NS + "/RSTR" + "/CancelFinal"; + + /** WS-Addressing RequestSecurityTokenResponse (RSTR) action URI 'Validate'. */ + public static final String WSA_ACTION_RSTR_VALIDATE= WST_NS + "/RSTR" + "/Validate"; + + /** WS-Addressing RequestSecurityTokenResponse (RSTR) action URI 'ValidateFinal'. */ + public static final String WSA_ACTION_RSTR_VALIDATE_FINAL= WST_NS + "/RSTR" + "/ValidateFinal"; + + /** WS-Addressing RequestSecurityTokenResponse (RSTR) action URI 'Renew'. */ + public static final String WSA_ACTION_RSTR_RENEW= WST_NS + "/RSTR" + "/Renew"; + + /** WS-Addressing RequestSecurityTokenResponse (RSTR) action URI 'RenewFinal'. */ + public static final String WSA_ACTION_RSTR_RENEW_FINAL= WST_NS + "/RSTR" + "/RenewFinal"; + + /** WS-Addressing RequestSecurityTokenResponse (RSTR) action URI 'KET'. */ + public static final String WSA_ACTION_RSTR_KET= WST_NS + "/RSTR" + "/KET"; + + /** WS-Addressing RequestSecurityTokenResponse (RSTR) action URI 'KETFinal'. */ + public static final String WSA_ACTION_RSTR_KET_FINAL= WST_NS + "/RSTR" + "/KETFinal"; + + + // WS-Addressing RequestSecurityTokenResponseCollection (RSTRC) action URIs. + + /** WS-Addressing RequestSecurityTokenResponseCollection (RSTRC) action URI 'Issue'. */ + public static final String WSA_ACTION_RSTRC_ISSUE_FINAL= WST_NS + "/RSTRC" + "/IssueFinal"; + + + // SOAP fault codes. + + /** WS-Trust SOAP fault code: "wst:InvalidRequest". */ + public static final QName SOAP_FAULT_INVALID_REQUEST = + new QName(WST_NS, "InvalidRequest", WST_PREFIX); + + /** WS-Trust SOAP fault code: "wst:FailedAuthentication". */ + public static final QName SOAP_FAULT_FAILED_AUTHENTICATION = + new QName(WST_NS, "FailedAuthentication", WST_PREFIX); + + /** WS-Trust SOAP fault code: "wst:RequestFailed". */ + public static final QName SOAP_FAULT_REQUEST_FAILED = + new QName(WST_NS, "RequestFailed", WST_PREFIX); + + /** WS-Trust SOAP fault code: "wst:InvalidSecurityToken". */ + public static final QName SOAP_FAULT_INVALID_SECURITY_TOKEN = + new QName(WST_NS, "InvalidSecurityToken", WST_PREFIX); + + /** WS-Trust SOAP fault code: "wst:AuthenticationBadElements". */ + public static final QName SOAP_FAULT_AUTHENTICATION_BAD_ELEMENTS = + new QName(WST_NS, "AuthenticationBadElements", WST_PREFIX); + + /** WS-Trust SOAP fault code: "wst:BadRequest". */ + public static final QName SOAP_FAULT_BAD_REQUEST = + new QName(WST_NS, "BadRequest", WST_PREFIX); + + /** WS-Trust SOAP fault code: "wst:ExpiredData". */ + public static final QName SOAP_FAULT_EXPIRED_DATA = + new QName(WST_NS, "ExpiredData", WST_PREFIX); + + /** WS-Trust SOAP fault code: "wst:InvalidTimeRange". */ + public static final QName SOAP_FAULT_INVALID_TIME_RANGE = + new QName(WST_NS, "InvalidTimeRange", WST_PREFIX); + + /** WS-Trust SOAP fault code: "wst:InvalidScope". */ + public static final QName SOAP_FAULT_INVALID_SCOPE = + new QName(WST_NS, "InvalidScope", WST_PREFIX); + + /** WS-Trust SOAP fault code: "wst:RenewNeeded". */ + public static final QName SOAP_FAULT_RENEW_NEEDED = + new QName(WST_NS, "RenewNeeded", WST_PREFIX); + + /** WS-Trust SOAP fault code: "wst:UnableToRenew". */ + public static final QName SOAP_FAULT_UNABLE_TO_RENEW = + new QName(WST_NS, "UnableToRenew", WST_PREFIX); + + /** Constructor. Private to prevent instantiation. */ + private WSTrustConstants() { } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/WSTrustObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/WSTrustObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/WSTrustObject.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import org.opensaml.xml.XMLObject; + +/** + * WSTrustObject is the base interface for all the WS-Trust elements. + * + * @see "WS-Trust 1.3 Specification" + * + */ +public interface WSTrustObject extends XMLObject { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/WSTrustObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/WSTrustObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/WSTrustObjectBuilder.java 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust; + +import org.opensaml.xml.XMLObjectBuilder; + +/** + * WSTrustObjectBuilder. + */ +public interface WSTrustObjectBuilder + extends XMLObjectBuilder { + + /** + * Builds a WS-Trust object of the given type. + * + * @return the built object + */ + public WSTrustObjectType buildObject(); +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/package.html 17 Aug 2012 15:08:55 -0000 1.1 @@ -0,0 +1,11 @@ + + +

+XMLObject interfaces for WS-Trust 1.3 elements. +

+

+The OASIS WS-Trust 1.3 specification defines extensions that build on [WS-Security 2004] to provide a framework for +requesting and issuing security tokens, and to broker trust relationships. +

+ + \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AbstractWSTrustObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AbstractWSTrustObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AbstractWSTrustObject.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.WSTrustObject; +import org.opensaml.xml.validation.AbstractValidatingXMLObject; + +/** + * AbstractWSTrustObject. + */ +public abstract class AbstractWSTrustObject extends AbstractValidatingXMLObject implements WSTrustObject { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public AbstractWSTrustObject(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AbstractWSTrustObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AbstractWSTrustObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AbstractWSTrustObjectBuilder.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.WSTrustObject; +import org.opensaml.ws.wstrust.WSTrustObjectBuilder; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * AbstractWSTrustObjectBuilder. + * + * @param the type of WSTrustObject being built + * + */ +public abstract class AbstractWSTrustObjectBuilder + extends AbstractXMLObjectBuilder + implements WSTrustObjectBuilder { + + /** {@inheritDoc} */ + public abstract WSTrustObjectType buildObject(); + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AbstractWSTrustObjectMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AbstractWSTrustObjectMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AbstractWSTrustObjectMarshaller.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.io.MarshallingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Element; + +/** + * An abstract marshaller implementation for XMLObjects from {@link org.opensaml.ws.wstrust}. + * + */ +public abstract class AbstractWSTrustObjectMarshaller extends AbstractXMLObjectMarshaller { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(AbstractWSTrustObjectMarshaller.class); + + /** Constructor. */ + protected AbstractWSTrustObjectMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + log.debug("{} has no more attribute to marshall.", xmlObject.getElementQName().getLocalPart()); + + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + log.debug("{} has no content to marshall.", xmlObject.getElementQName().getLocalPart()); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AbstractWSTrustObjectUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AbstractWSTrustObjectUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AbstractWSTrustObjectUnmarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; + +/** + * An abstract unmarshaller implementation for XMLObjects from {@link org.opensaml.ws.wstrust}. + * + */ +public abstract class AbstractWSTrustObjectUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(AbstractWSTrustObjectUnmarshaller.class); + + /** Constructor. */ + protected AbstractWSTrustObjectUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + log.warn("{} ignoring unknown child element {}", parentXMLObject.getElementQName().getLocalPart(), + childXMLObject.getElementQName().getLocalPart()); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + log.warn("{} ignoring unknown attribute {}", xmlObject.getElementQName().getLocalPart(), attribute + .getLocalName()); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + log.warn("{} ignoring unknown element content: {}", xmlObject.getElementQName().getLocalPart(), elementContent); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AllowPostdatingBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AllowPostdatingBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AllowPostdatingBuilder.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.AllowPostdating; + +/** + * Builder for the AllowPostdating element. + * + */ +public class AllowPostdatingBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public AllowPostdating buildObject() { + return buildObject(AllowPostdating.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public AllowPostdating buildObject(String namespaceURI, String localName, + String namespacePrefix) { + return new AllowPostdatingImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AllowPostdatingImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AllowPostdatingImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AllowPostdatingImpl.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.List; + +import org.opensaml.ws.wstrust.AllowPostdating; +import org.opensaml.xml.XMLObject; + +/** + * AllowPostdatingImpl. + * + */ +public class AllowPostdatingImpl extends AbstractWSTrustObject implements AllowPostdating { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public AllowPostdatingImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AllowPostdatingMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AllowPostdatingMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AllowPostdatingMarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Marshaller for the AllowPostdating element. + * + */ +public class AllowPostdatingMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AllowPostdatingUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AllowPostdatingUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AllowPostdatingUnmarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Unmarshaller for the wst:AllowPostdating element. + * + */ +public class AllowPostdatingUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticationTypeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticationTypeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticationTypeBuilder.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.AuthenticationType; + +/** + * Builder for the AuthenticationType element. + * + */ +public class AuthenticationTypeBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public AuthenticationType buildObject() { + return buildObject(AuthenticationType.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public AuthenticationType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthenticationTypeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticationTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticationTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticationTypeImpl.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.AuthenticationType; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * AddressImpl. + * + */ +public class AuthenticationTypeImpl extends XSURIImpl implements AuthenticationType { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public AuthenticationTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticationTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticationTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticationTypeMarshaller.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the AuthenticationType element. + * + */ +public class AuthenticationTypeMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticationTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticationTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticationTypeUnmarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the wst:AuthenticationType element. + * + */ +public class AuthenticationTypeUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticatorBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticatorBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticatorBuilder.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Authenticator; + +/** + * Builder for the Authenticator element. + * + */ +public class AuthenticatorBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Authenticator buildObject() { + return buildObject(Authenticator.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Authenticator buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthenticatorImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticatorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticatorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticatorImpl.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,85 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wstrust.Authenticator; +import org.opensaml.ws.wstrust.CombinedHash; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * AuthenticatorImpl. + * + */ +public class AuthenticatorImpl extends AbstractWSTrustObject implements Authenticator { + + /** the wst:Authenticator/wst:CombinedHash child element. */ + private CombinedHash combinedHash; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public AuthenticatorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public CombinedHash getCombinedHash() { + return combinedHash; + } + + /** {@inheritDoc} */ + public void setCombinedHash(CombinedHash newCombinedHash) { + combinedHash = prepareForAssignment(combinedHash, newCombinedHash); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (combinedHash != null) { + children.add(combinedHash); + } + children.addAll(unknownChildren); + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticatorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticatorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticatorMarshaller.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * Marshaller for the Authenticator element. + * + */ +public class AuthenticatorMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticatorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticatorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/AuthenticatorUnmarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.Authenticator; +import org.opensaml.ws.wstrust.CombinedHash; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for the wst:Authenticator element. + * + */ +public class AuthenticatorUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Authenticator authenticator = (Authenticator) parentXMLObject; + + if (childXMLObject instanceof CombinedHash) { + authenticator.setCombinedHash((CombinedHash) childXMLObject); + } else { + authenticator.getUnknownXMLObjects().add(childXMLObject); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinaryExchangeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinaryExchangeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinaryExchangeBuilder.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.BinaryExchange; + +/** + * Builder for the BinaryExchange element. + * + */ +public class BinaryExchangeBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public BinaryExchange buildObject() { + return buildObject(BinaryExchange.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public BinaryExchange buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new BinaryExchangeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinaryExchangeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinaryExchangeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinaryExchangeImpl.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.BinaryExchange; +import org.opensaml.xml.schema.impl.XSStringImpl; +import org.opensaml.xml.util.AttributeMap; + +/** + * BinaryExchangeImpl. + * + */ +public class BinaryExchangeImpl extends XSStringImpl implements BinaryExchange { + + /** The wst:BinaryExchange/@ValueType attribute value. */ + private String valueType; + + /** The wst:BinaryExchange/@EncodingType attribute value. */ + private String encodingType; + + /** xs:anyAttribute for this element. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public BinaryExchangeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public String getEncodingType() { + return encodingType; + } + + /** {@inheritDoc} */ + public void setEncodingType(String newEncodingType) { + encodingType = prepareForAssignment(encodingType, newEncodingType); + } + + /** {@inheritDoc} */ + public String getValueType() { + return valueType; + } + + /** {@inheritDoc} */ + public void setValueType(String newValueType) { + valueType = prepareForAssignment(valueType, newValueType); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinaryExchangeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinaryExchangeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinaryExchangeMarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.BinaryExchange; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.schema.impl.XSStringMarshaller; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for the BinaryExchange element. + * + * @see BinaryExchange + * + */ +public class BinaryExchangeMarshaller extends XSStringMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + BinaryExchange binaryExchange = (BinaryExchange) xmlObject; + + String valueType = DatatypeHelper.safeTrimOrNullString(binaryExchange.getValueType()); + if (valueType != null) { + domElement.setAttributeNS(null, BinaryExchange.VALUE_TYPE_ATTRIB_NAME, valueType); + } + String encodingType = DatatypeHelper.safeTrimOrNullString(binaryExchange.getEncodingType()); + if (encodingType != null) { + domElement.setAttributeNS(null, BinaryExchange.ENCODING_TYPE_ATTRIB_NAME, encodingType); + } + + XMLHelper.marshallAttributeMap(binaryExchange.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinaryExchangeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinaryExchangeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinaryExchangeUnmarshaller.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.BinaryExchange; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.impl.XSStringUnmarshaller; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for the <wst:BinaryExchange> element. + * + * @see BinaryExchange + * + */ +public class BinaryExchangeUnmarshaller extends XSStringUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + BinaryExchange binaryExchange = (BinaryExchange) xmlObject; + + String attrName = attribute.getLocalName(); + if (BinaryExchange.VALUE_TYPE_ATTRIB_NAME.equals(attrName)) { + binaryExchange.setValueType(attribute.getValue()); + } else if (BinaryExchange.ENCODING_TYPE_ATTRIB_NAME.equals(attrName)) { + binaryExchange.setEncodingType(attribute.getValue()); + } else { + XMLHelper.unmarshallToAttributeMap(binaryExchange.getUnknownAttributes(), attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinarySecretBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinarySecretBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinarySecretBuilder.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.BinarySecret; + +/** + * Builder for the BinarySecret element. + * + */ +public class BinarySecretBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public BinarySecret buildObject() { + return buildObject(BinarySecret.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public BinarySecret buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new BinarySecretImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinarySecretImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinarySecretImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinarySecretImpl.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,71 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.List; + +import org.opensaml.ws.wstrust.BinarySecret; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.impl.XSBase64BinaryImpl; +import org.opensaml.xml.util.AttributeMap; + +/** + * BinarySecretImpl. + * + */ +public class BinarySecretImpl extends XSBase64BinaryImpl implements BinarySecret { + + /** The Type attribute value. */ + private String type; + + /** Wildcard attributes. */ + private AttributeMap unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public BinarySecretImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public String getType() { + return type; + } + + /** {@inheritDoc} */ + public void setType(String newType) { + type = prepareForAssignment(type, newType); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinarySecretMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinarySecretMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinarySecretMarshaller.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.BinarySecret; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.schema.impl.XSBase64BinaryMarshaller; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for the BinarySecret element. + * + * @see BinarySecret + * + */ +public class BinarySecretMarshaller extends XSBase64BinaryMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + BinarySecret bs = (BinarySecret) xmlObject; + if (bs.getType() != null) { + domElement.setAttributeNS(null, BinarySecret.TYPE_ATTRIB_NAME, bs.getType()); + } + + XMLHelper.marshallAttributeMap(bs.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinarySecretUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinarySecretUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/BinarySecretUnmarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.BinarySecret; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.impl.XSBase64BinaryUnmarshaller; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for the <wst:BinarySecret> element. + * + */ +public class BinarySecretUnmarshaller extends XSBase64BinaryUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + BinarySecret bs = (BinarySecret) xmlObject; + if (BinarySecret.TYPE_ATTRIB_NAME.equals(attribute.getLocalName())) { + bs.setType(attribute.getValue()); + } else { + XMLHelper.unmarshallToAttributeMap(bs.getUnknownAttributes(), attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CancelTargetBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CancelTargetBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CancelTargetBuilder.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.CancelTarget; + +/** + * Builder for the CancelTarget element. + * + */ +public class CancelTargetBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public CancelTarget buildObject() { + return buildObject(CancelTarget.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public CancelTarget buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new CancelTargetImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CancelTargetImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CancelTargetImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CancelTargetImpl.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.CancelTarget; +import org.opensaml.xml.XMLObject; + +/** + * CancelTargetImpl. + * + */ +public class CancelTargetImpl extends AbstractWSTrustObject implements CancelTarget { + + /** Wildcard child element. */ + private XMLObject unknownChild; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public CancelTargetImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public XMLObject getUnknownXMLObject() { + return unknownChild; + } + + /** {@inheritDoc} */ + public void setUnknownXMLObject(XMLObject unknownObject) { + prepareForAssignment(unknownChild, unknownObject); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (unknownChild != null) { + children.add(unknownChild); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CancelTargetMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CancelTargetMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CancelTargetMarshaller.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * Marshaller for the CancelTarget element. + * + */ +public class CancelTargetMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CancelTargetUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CancelTargetUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CancelTargetUnmarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.CancelTarget; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for the wst:CancelTarget element. + * + */ +public class CancelTargetUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + CancelTarget ct = (CancelTarget) parentXMLObject; + ct.setUnknownXMLObject(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CanonicalizationAlgorithmBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CanonicalizationAlgorithmBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CanonicalizationAlgorithmBuilder.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.CanonicalizationAlgorithm; + +/** + * Builder for the CanonicalizationAlgorithm element. + * + */ +public class CanonicalizationAlgorithmBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public CanonicalizationAlgorithm buildObject() { + return buildObject(CanonicalizationAlgorithm.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public CanonicalizationAlgorithm buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new CanonicalizationAlgorithmImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CanonicalizationAlgorithmImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CanonicalizationAlgorithmImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CanonicalizationAlgorithmImpl.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.CanonicalizationAlgorithm; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * CanonicalizationAlgorithmImpl. + * + */ +public class CanonicalizationAlgorithmImpl extends XSURIImpl implements CanonicalizationAlgorithm { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public CanonicalizationAlgorithmImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CanonicalizationAlgorithmMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CanonicalizationAlgorithmMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CanonicalizationAlgorithmMarshaller.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the CanonicalizationAlgorithm element. + * + */ +public class CanonicalizationAlgorithmMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CanonicalizationAlgorithmUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CanonicalizationAlgorithmUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CanonicalizationAlgorithmUnmarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the wst:CanonicalizationAlgorithm element. + * + */ +public class CanonicalizationAlgorithmUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ChallengeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ChallengeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ChallengeBuilder.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Challenge; + +/** + * Builder for the Challenge element. + * + */ +public class ChallengeBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Challenge buildObject() { + return buildObject(Challenge.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Challenge buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ChallengeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ChallengeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ChallengeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ChallengeImpl.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Challenge; +import org.opensaml.xml.schema.impl.XSStringImpl; + +/** + * ChallengeImpl. + * + */ +public class ChallengeImpl extends XSStringImpl implements Challenge { + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public ChallengeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ChallengeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ChallengeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ChallengeMarshaller.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSStringMarshaller; + +/** + * Marshaller for the Challenge element. + * + */ +public class ChallengeMarshaller extends XSStringMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ChallengeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ChallengeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ChallengeUnmarshaller.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSStringUnmarshaller; + +/** + * Unmarshaller for the wst:Challenge element. + * + */ +public class ChallengeUnmarshaller extends XSStringUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ClaimsBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ClaimsBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ClaimsBuilder.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Claims; + +/** + * Builder for the Claims element. + * + */ +public class ClaimsBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Claims buildObject() { + return buildObject(Claims.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Claims buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ClaimsImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ClaimsImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ClaimsImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ClaimsImpl.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,93 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wstrust.Claims; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * ClaimsImpl. + * + */ +public class ClaimsImpl extends AbstractWSTrustObject implements Claims { + + /** The Dialect attribute value. */ + private String dialect; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ClaimsImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public String getDialect() { + return dialect; + } + + /** {@inheritDoc} */ + public void setDialect(String newDialect) { + dialect = prepareForAssignment(dialect, newDialect); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + children.addAll(unknownChildren); + return Collections.unmodifiableList(children); + } + + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ClaimsMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ClaimsMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ClaimsMarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.Claims; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for the Claims element. + * + */ +public class ClaimsMarshaller extends AbstractWSTrustObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Claims claims = (Claims) xmlObject; + if (claims.getDialect() != null) { + domElement.setAttributeNS(null, Claims.DIALECT_ATTRIB_NAME, claims.getDialect()); + } + + XMLHelper.marshallAttributeMap(claims.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ClaimsUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ClaimsUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ClaimsUnmarshaller.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Claims; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + + + +/** + * Unmarshaller for the wst:Claims element. + * + */ +public class ClaimsUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Claims claims = (Claims) xmlObject; + if (Claims.DIALECT_ATTRIB_NAME.equals(attribute.getLocalName())) { + claims.setDialect(attribute.getValue()); + } else { + XMLHelper.unmarshallToAttributeMap(claims.getUnknownAttributes(), attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Claims claims = (Claims) parentXMLObject; + claims.getUnknownXMLObjects().add(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CodeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CodeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CodeBuilder.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Code; + +/** + * Builder for the Code element. + * + */ +public class CodeBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Code buildObject() { + return buildObject(Code.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Code buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new CodeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CodeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CodeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CodeImpl.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Code; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * CodeImpl. + * + */ +public class CodeImpl extends XSURIImpl implements Code { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public CodeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CodeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CodeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CodeMarshaller.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the Code element. + * + */ +public class CodeMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CodeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CodeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CodeUnmarshaller.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the :Code element. + * + */ +public class CodeUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashBuilder.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.CombinedHash; + +/** + * Builder for the CombinedHash element. + * + */ +public class CombinedHashBuilder extends AbstractWSTrustObjectBuilder { + + public CombinedHash buildObject() { + return buildObject(CombinedHash.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public CombinedHash buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new CombinedHashImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashImpl.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.CombinedHash; +import org.opensaml.xml.schema.impl.XSBase64BinaryImpl; + +/** + * CombinedHashImpl. + * + */ +public class CombinedHashImpl extends XSBase64BinaryImpl implements CombinedHash { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public CombinedHashImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashMarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSBase64BinaryMarshaller; + +/** + * Marshaller for the CombinedHash element. + * + */ +public class CombinedHashMarshaller extends XSBase64BinaryMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/CombinedHashUnmarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSBase64BinaryUnmarshaller; + +/** + * Unmarshaller for the wst:CombinedHash element. + * + */ +public class CombinedHashUnmarshaller extends XSBase64BinaryUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyAlgorithmBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyAlgorithmBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyAlgorithmBuilder.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.ComputedKeyAlgorithm; + +/** + * Builder for the ComputedKeyAlgorithm element. + * + */ +public class ComputedKeyAlgorithmBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public ComputedKeyAlgorithm buildObject() { + return buildObject(ComputedKeyAlgorithm.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ComputedKeyAlgorithm buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ComputedKeyAlgorithmImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyAlgorithmImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyAlgorithmImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyAlgorithmImpl.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.ComputedKeyAlgorithm; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * ComputedKeyAlgorithmImpl. + * + */ +public class ComputedKeyAlgorithmImpl extends XSURIImpl implements ComputedKeyAlgorithm { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ComputedKeyAlgorithmImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyAlgorithmMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyAlgorithmMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyAlgorithmMarshaller.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the ComputedKeyAlgorithm element. + * + */ +public class ComputedKeyAlgorithmMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyAlgorithmUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyAlgorithmUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyAlgorithmUnmarshaller.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the wst:ComputedKeyAlgorithm element. + * + */ +public class ComputedKeyAlgorithmUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyBuilder.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.ComputedKey; + +/** + * Builder for the ComputedKey element. + * + */ +public class ComputedKeyBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public ComputedKey buildObject() { + return buildObject(ComputedKey.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ComputedKey buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ComputedKeyImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyImpl.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.ComputedKey; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * ComputedKeyImpl. + * + */ +public class ComputedKeyImpl extends XSURIImpl implements ComputedKey { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ComputedKeyImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyMarshaller.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the ComputedKey element. + * + */ +public class ComputedKeyMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ComputedKeyUnmarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the wst:ComputedKey element. + * + */ +public class ComputedKeyUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegatableBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegatableBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegatableBuilder.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Delegatable; + +/** + * Builder for the Delegatable element. + * + */ +public class DelegatableBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Delegatable buildObject() { + return buildObject(Delegatable.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Delegatable buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DelegatableImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegatableImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegatableImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegatableImpl.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.List; + +import org.opensaml.ws.wstrust.Delegatable; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * DelegatableImpl. + * + */ +public class DelegatableImpl extends AbstractWSTrustObject implements Delegatable { + + /** Default value. */ + private static final Boolean DEFAULT_VALUE = Boolean.FALSE; + + /** The wst:Forwardable content. */ + private XSBooleanValue value; + + /** + * Constructor. Default value is FALSE. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public DelegatableImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + value = new XSBooleanValue(DEFAULT_VALUE, false); + } + + /** {@inheritDoc} */ + public XSBooleanValue getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setValue(XSBooleanValue newValue) { + if (newValue != null) { + value = prepareForAssignment(value, newValue); + } else { + value = prepareForAssignment(value, new XSBooleanValue(DEFAULT_VALUE, false)); + } + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegatableMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegatableMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegatableMarshaller.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.Delegatable; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for the Delegatable element. + * + */ +public class DelegatableMarshaller extends AbstractWSTrustObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + Delegatable delegatable = (Delegatable) xmlObject; + XSBooleanValue value= delegatable.getValue(); + XMLHelper.appendTextContent(domElement, value.toString()); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegatableUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegatableUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegatableUnmarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.Delegatable; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * Unmarshaller for the wst:Delegatable element. + * + */ +public class DelegatableUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + if (elementContent != null) { + Delegatable delegatable = (Delegatable) xmlObject; + XSBooleanValue value = XSBooleanValue.valueOf(elementContent); + delegatable.setValue(value); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegateToBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegateToBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegateToBuilder.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.DelegateTo; + +/** + * Builder for the DelegateTo element. + * + */ +public class DelegateToBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public DelegateTo buildObject() { + return buildObject(DelegateTo.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public DelegateTo buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DelegateToImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegateToImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegateToImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegateToImpl.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.DelegateTo; +import org.opensaml.xml.XMLObject; + +/** + * DelegateToImpl. + * + */ +public class DelegateToImpl extends AbstractWSTrustObject implements DelegateTo { + + /** Wildcard child element. */ + private XMLObject unknownChild; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public DelegateToImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public XMLObject getUnknownXMLObject() { + return unknownChild; + } + + /** {@inheritDoc} */ + public void setUnknownXMLObject(XMLObject unknownObject) { + unknownChild = prepareForAssignment(unknownChild, unknownObject); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (unknownChild != null) { + children.add(unknownChild); + } + return Collections.unmodifiableList(children); + } + + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegateToMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegateToMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegateToMarshaller.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * Marshaller for the DelegateTo element. + * + */ +public class DelegateToMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegateToUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegateToUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/DelegateToUnmarshaller.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.DelegateTo; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for the <wst:DelegateTo> element. + * + */ +public class DelegateToUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + DelegateTo delegateTo = (DelegateTo) parentXMLObject; + delegateTo.setUnknownXMLObject(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptWithBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptWithBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptWithBuilder.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.EncryptWith; + +/** + * Builder for the EncryptWith element. + * + */ +public class EncryptWithBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public EncryptWith buildObject() { + return buildObject(EncryptWith.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public EncryptWith buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EncryptWithImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptWithImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptWithImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptWithImpl.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.EncryptWith; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * EncryptWithImpl. + * + */ +public class EncryptWithImpl extends XSURIImpl implements EncryptWith { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public EncryptWithImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptWithMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptWithMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptWithMarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the EncryptWith element. + * + */ +public class EncryptWithMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptWithUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptWithUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptWithUnmarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the wst:EncryptWith element. + * + */ +public class EncryptWithUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionAlgorithmBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionAlgorithmBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionAlgorithmBuilder.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.EncryptionAlgorithm; + +/** + * Builder for the EncryptionAlgorithm element. + * + */ +public class EncryptionAlgorithmBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public EncryptionAlgorithm buildObject() { + return buildObject(EncryptionAlgorithm.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public EncryptionAlgorithm buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EncryptionAlgorithmImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionAlgorithmImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionAlgorithmImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionAlgorithmImpl.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.EncryptionAlgorithm; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * EncryptionAlgorithmImpl. + * + */ +public class EncryptionAlgorithmImpl extends XSURIImpl implements EncryptionAlgorithm { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public EncryptionAlgorithmImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionAlgorithmMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionAlgorithmMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionAlgorithmMarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the EncryptionAlgorithm element. + * + */ +public class EncryptionAlgorithmMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionAlgorithmUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionAlgorithmUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionAlgorithmUnmarshaller.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the wst:EncryptionAlgorithm element. + * + */ +public class EncryptionAlgorithmUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionBuilder.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Encryption; + +/** + * Builder for the Encryption element. + * + */ +public class EncryptionBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Encryption buildObject() { + return buildObject(Encryption.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Encryption buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EncryptionImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionImpl.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.Encryption; +import org.opensaml.xml.XMLObject; + +/** + * EncryptionImpl. + * + */ +public class EncryptionImpl extends AbstractWSTrustObject implements Encryption { + + /** Wildcard child element. */ + private XMLObject unknownChild; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public EncryptionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public XMLObject getUnknownXMLObject() { + return unknownChild; + } + + /** {@inheritDoc} */ + public void setUnknownXMLObject(XMLObject unknownObject) { + unknownChild = prepareForAssignment(unknownChild, unknownObject); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (unknownChild != null) { + children.add(unknownChild); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionMarshaller.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * Marshaller for the Encryption element. + * + */ +public class EncryptionMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EncryptionUnmarshaller.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Encryption; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + + + +/** + * Unmarshaller for the wst:Encryption element. + * + */ +public class EncryptionUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Encryption enc = (Encryption) parentXMLObject; + enc.setUnknownXMLObject(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EntropyBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EntropyBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EntropyBuilder.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Entropy; + +/** + * Builder for the Entropy element. + * + */ +public class EntropyBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Entropy buildObject() { + return buildObject(Entropy.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Entropy buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EntropyImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EntropyImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EntropyImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EntropyImpl.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wstrust.Entropy; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * EntropyImpl. + * + */ +public class EntropyImpl extends AbstractWSTrustObject implements Entropy { + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public EntropyImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + children.addAll(unknownChildren); + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EntropyMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EntropyMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EntropyMarshaller.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Entropy; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + + +/** + * Marshaller for the Entropy element. + * + */ +public class EntropyMarshaller extends AbstractWSTrustObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Entropy entropy = (Entropy) xmlObject; + XMLHelper.marshallAttributeMap(entropy.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EntropyUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EntropyUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/EntropyUnmarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Claims; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + + + +/** + * Unmarshaller for the wst:Entropy element. + * + */ +public class EntropyUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Claims claims = (Claims) xmlObject; + XMLHelper.unmarshallToAttributeMap(claims.getUnknownAttributes(), attribute); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Claims claims = (Claims) parentXMLObject; + claims.getUnknownXMLObjects().add(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ForwardableBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ForwardableBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ForwardableBuilder.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Forwardable; + +/** + * Builder for the Forwardable element. + * + */ +public class ForwardableBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Forwardable buildObject() { + return buildObject(Forwardable.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Forwardable buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ForwardableImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ForwardableImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ForwardableImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ForwardableImpl.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.List; + +import org.opensaml.ws.wstrust.Forwardable; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * ForwardableImpl. + * + */ +public class ForwardableImpl extends AbstractWSTrustObject implements Forwardable { + + /** Default value. */ + private static final Boolean DEFAULT_VALUE = Boolean.TRUE; + + /** The wst:Forwardable content. */ + private XSBooleanValue value; + + /** + * Constructor. Default value is TRUE. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ForwardableImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + value = new XSBooleanValue(DEFAULT_VALUE, false); + } + + /** {@inheritDoc} */ + public XSBooleanValue getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setValue(XSBooleanValue newValue) { + if (newValue != null) { + value = prepareForAssignment(value, newValue); + } else { + value = prepareForAssignment(value, new XSBooleanValue(DEFAULT_VALUE, false)); + } + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ForwardableMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ForwardableMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ForwardableMarshaller.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.Forwardable; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for the Forwardable element. + * + */ +public class ForwardableMarshaller extends AbstractWSTrustObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + Forwardable forwardable = (Forwardable) xmlObject; + XSBooleanValue value= forwardable.getValue(); + XMLHelper.appendTextContent(domElement, value.toString()); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ForwardableUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ForwardableUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ForwardableUnmarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.Forwardable; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * Unmarshaller for the wst:Forwardable element. + * + */ +public class ForwardableUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + if (elementContent != null) { + Forwardable forwardable = (Forwardable) xmlObject; + XSBooleanValue value = XSBooleanValue.valueOf(elementContent); + forwardable.setValue(value); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuedTokensBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuedTokensBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuedTokensBuilder.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.IssuedTokens; + +/** + * Builder for the IssuedTokens element. + * + */ +public class IssuedTokensBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public IssuedTokens buildObject() { + return buildObject(IssuedTokens.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public IssuedTokens buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new IssuedTokensImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuedTokensImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuedTokensImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuedTokensImpl.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.IssuedTokens; + +/** + * IssuedTokensImpl. + * + */ +public class IssuedTokensImpl extends RequestSecurityTokenResponseCollectionImpl implements IssuedTokens { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public IssuedTokensImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuedTokensMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuedTokensMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuedTokensMarshaller.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Marshaller for the IssuedTokens element. + * + */ +public class IssuedTokensMarshaller extends RequestSecurityTokenResponseCollectionMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuedTokensUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuedTokensUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuedTokensUnmarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Unmarshaller for the wst:IssuedTokens element. + * + */ +public class IssuedTokensUnmarshaller extends RequestSecurityTokenResponseCollectionUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuerBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuerBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuerBuilder.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Issuer; + +/** + * Builder for the Issuer element. + * + */ +public class IssuerBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Issuer buildObject() { + return buildObject(Issuer.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Issuer buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new IssuerImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuerImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuerImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuerImpl.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wsaddressing.impl.EndpointReferenceTypeImpl; +import org.opensaml.ws.wstrust.Issuer; + +/** + * IssuerImpl. + * + */ +public class IssuerImpl extends EndpointReferenceTypeImpl implements Issuer { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public IssuerImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuerMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuerMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuerMarshaller.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wsaddressing.impl.EndpointReferenceTypeMarshaller; + +/** + * Marshaller for the Issuer element. + * + */ +public class IssuerMarshaller extends EndpointReferenceTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuerUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuerUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/IssuerUnmarshaller.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wsaddressing.impl.EndpointReferenceTypeUnmarshaller; + +/** + * IssuerUnmarshaller. + * + */ +public class IssuerUnmarshaller extends EndpointReferenceTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyExchangeTokenBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyExchangeTokenBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyExchangeTokenBuilder.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.KeyExchangeToken; + +/** + * Builder for the KeyExchangeToken element. + * + */ +public class KeyExchangeTokenBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public KeyExchangeToken buildObject() { + return buildObject(KeyExchangeToken.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public KeyExchangeToken buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new KeyExchangeTokenImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyExchangeTokenImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyExchangeTokenImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyExchangeTokenImpl.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wstrust.KeyExchangeToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * KeyExchangeTokenImpl. + * + */ +public class KeyExchangeTokenImpl extends AbstractWSTrustObject implements KeyExchangeToken { + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public KeyExchangeTokenImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return Collections.unmodifiableList(unknownChildren); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyExchangeTokenMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyExchangeTokenMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyExchangeTokenMarshaller.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * Marshaller for the KeyExchangeToken element. + * + */ +public class KeyExchangeTokenMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyExchangeTokenUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyExchangeTokenUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyExchangeTokenUnmarshaller.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.KeyExchangeToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for the wst:KeyExchangeToken element. + * + */ +public class KeyExchangeTokenUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + KeyExchangeToken ket = (KeyExchangeToken) parentXMLObject; + ket.getUnknownXMLObjects().add(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeySizeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeySizeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeySizeBuilder.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.KeySize; + +/** + * Builder for the KeySize element. + * + */ +public class KeySizeBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public KeySize buildObject() { + return buildObject(KeySize.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public KeySize buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new KeySizeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeySizeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeySizeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeySizeImpl.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.KeySize; +import org.opensaml.xml.schema.impl.XSIntegerImpl; + +/** + * KeySizeImpl. + * + */ +public class KeySizeImpl extends XSIntegerImpl implements KeySize { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public KeySizeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeySizeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeySizeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeySizeMarshaller.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSIntegerMarshaller; + +/** + * Marshaller for the KeySize element. + * + */ +public class KeySizeMarshaller extends XSIntegerMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeySizeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeySizeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeySizeUnmarshaller.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSIntegerUnmarshaller; + +/** + * Unmarshaller for the wst:KeySize element. + * + */ +public class KeySizeUnmarshaller extends XSIntegerUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyTypeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyTypeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyTypeBuilder.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.KeyType; + +/** + * Builder for the KeyType element. + * + */ +public class KeyTypeBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public KeyType buildObject() { + return buildObject(KeyType.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public KeyType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new KeyTypeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyTypeImpl.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.KeyType; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * KeyTypeImpl. + * + */ +public class KeyTypeImpl extends XSURIImpl implements KeyType { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public KeyTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyTypeMarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the KeyType element. + * + */ +public class KeyTypeMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyTypeUnmarshaller.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the wst:KeyType element. + * + */ +public class KeyTypeUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyWrapAlgorithmBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyWrapAlgorithmBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyWrapAlgorithmBuilder.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.KeyWrapAlgorithm; + +/** + * Builder for the KeyWrapAlgorithm element. + * + */ +public class KeyWrapAlgorithmBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public KeyWrapAlgorithm buildObject() { + return buildObject(KeyWrapAlgorithm.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public KeyWrapAlgorithm buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new KeyWrapAlgorithmImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyWrapAlgorithmImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyWrapAlgorithmImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyWrapAlgorithmImpl.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.KeyWrapAlgorithm; +import org.opensaml.xml.schema.impl.XSStringImpl; + +/** + * KeyWrapAlgorithmImpl. + * + */ +public class KeyWrapAlgorithmImpl extends XSStringImpl implements KeyWrapAlgorithm { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public KeyWrapAlgorithmImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyWrapAlgorithmMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyWrapAlgorithmMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyWrapAlgorithmMarshaller.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the KeyWrapAlgorithm element. + * + */ +public class KeyWrapAlgorithmMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyWrapAlgorithmUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyWrapAlgorithmUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/KeyWrapAlgorithmUnmarshaller.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the wst:KeyWrapAlgorithm element. + * + */ +public class KeyWrapAlgorithmUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/LifetimeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/LifetimeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/LifetimeBuilder.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Lifetime; + +/** + * Builder for the Lifetime element. + * + */ +public class LifetimeBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Lifetime buildObject() { + return buildObject(Lifetime.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Lifetime buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new LifetimeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/LifetimeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/LifetimeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/LifetimeImpl.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wssecurity.Created; +import org.opensaml.ws.wssecurity.Expires; +import org.opensaml.ws.wstrust.Lifetime; +import org.opensaml.xml.XMLObject; + +/** + * LifetimeImpl. + * + */ +public class LifetimeImpl extends AbstractWSTrustObject implements Lifetime { + + /** The wsu:Created child element. */ + private Created created; + + /** The wsu:Expires child element. */ + private Expires expires; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public LifetimeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public Created getCreated() { + return created; + } + + /** {@inheritDoc} */ + public Expires getExpires() { + return expires; + } + + /** {@inheritDoc} */ + public void setCreated(Created newCreated) { + created = prepareForAssignment(created, newCreated); + } + + /** {@inheritDoc} */ + public void setExpires(Expires newExpires) { + expires = prepareForAssignment(expires, newExpires); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (created != null) { + children.add(created); + } + if (expires != null) { + children.add(expires); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/LifetimeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/LifetimeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/LifetimeMarshaller.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Marshaller for the Lifetime element. + * + */ +public class LifetimeMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/LifetimeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/LifetimeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/LifetimeUnmarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wssecurity.Created; +import org.opensaml.ws.wssecurity.Expires; +import org.opensaml.ws.wstrust.Lifetime; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + + +/** + * Unmarshaller for the wst:Lifetime element. + * + */ +public class LifetimeUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Lifetime lifetime = (Lifetime) parentXMLObject; + if (childXMLObject instanceof Created) { + lifetime.setCreated((Created) childXMLObject); + } else if (childXMLObject instanceof Expires) { + lifetime.setExpires((Expires) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/OnBehalfOfBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/OnBehalfOfBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/OnBehalfOfBuilder.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.OnBehalfOf; + +/** + * Builder for the OnBehalfOf element. + * + */ +public class OnBehalfOfBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public OnBehalfOf buildObject() { + return buildObject(OnBehalfOf.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public OnBehalfOf buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new OnBehalfOfImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/OnBehalfOfImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/OnBehalfOfImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/OnBehalfOfImpl.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.OnBehalfOf; +import org.opensaml.xml.XMLObject; + +/** + * OnBehalfOfImpl. + * + */ +public class OnBehalfOfImpl extends AbstractWSTrustObject implements OnBehalfOf { + + /** Wildcard child element. */ + private XMLObject unknownChild; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public OnBehalfOfImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public XMLObject getUnknownXMLObject() { + return unknownChild; + } + + /** {@inheritDoc} */ + public void setUnknownXMLObject(XMLObject unknownObject) { + unknownChild = prepareForAssignment(unknownChild, unknownObject); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List children = new ArrayList(); + if (unknownChild != null) { + children.add(unknownChild); + } + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/OnBehalfOfMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/OnBehalfOfMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/OnBehalfOfMarshaller.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * Marshaller for the OnBehalfOf element. + * + */ +public class OnBehalfOfMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/OnBehalfOfUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/OnBehalfOfUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/OnBehalfOfUnmarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.OnBehalfOf; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for the wst:OnBehalfOf element. + * + */ +public class OnBehalfOfUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + OnBehalfOf obo = (OnBehalfOf) parentXMLObject; + obo.setUnknownXMLObject(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantBuilder.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Participant; + +/** + * Builder for the Participant element. + * + */ +public class ParticipantBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Participant buildObject() { + return buildObject(Participant.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Participant buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ParticipantImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantImpl.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Participant; + +/** + * ParticipantImpl. + * + */ +public class ParticipantImpl extends ParticipantTypeImpl implements Participant { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ParticipantImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantMarshaller.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * PrimaryMarshaller. + * + */ +public class ParticipantMarshaller extends ParticipantTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantTypeImpl.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.ParticipantType; +import org.opensaml.xml.XMLObject; + +/** + * ParticipantTypeImpl. + * + */ +public class ParticipantTypeImpl extends AbstractWSTrustObject implements ParticipantType { + + /** Unknown child elements. */ + private XMLObject unknownChild; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public ParticipantTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public XMLObject getUnknownXMLObject() { + return unknownChild; + } + + /** {@inheritDoc} */ + public void setUnknownXMLObject(XMLObject unknownObject) { + unknownChild = prepareForAssignment(unknownChild, unknownObject); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (unknownChild != null) { + children.add(unknownChild); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantTypeMarshaller.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * ParticipantTypeMarshaller. + * + */ +public class ParticipantTypeMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantTypeUnmarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.ParticipantType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * ParticipantTypeUnmarshaller. + * + */ +public class ParticipantTypeUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ParticipantType pt = (ParticipantType) parentXMLObject; + pt.setUnknownXMLObject(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantUnmarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * PrimaryUnmarshaller. + * + */ +public class ParticipantUnmarshaller extends ParticipantTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantsBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantsBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantsBuilder.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Participants; + +/** + * Builder for the Participants element. + * + */ +public class ParticipantsBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Participants buildObject() { + return buildObject(Participants.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Participants buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ParticipantsImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantsImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantsImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantsImpl.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,99 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wstrust.Participant; +import org.opensaml.ws.wstrust.Participants; +import org.opensaml.ws.wstrust.Primary; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * ParticipantsImpl. + * + */ +public class ParticipantsImpl extends AbstractWSTrustObject implements Participants { + + /** The {@link Primary} child element. */ + private Primary primary; + + /** The list of {@link Participant} child elements. */ + private List participants; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ParticipantsImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + participants = new ArrayList(); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public Primary getPrimary() { + return primary; + } + + /** {@inheritDoc} */ + public void setPrimary(Primary newPrimary) { + primary = prepareForAssignment(primary, newPrimary); + } + + /** {@inheritDoc} */ + public List getParticipants() { + return participants; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List children = new ArrayList(); + if (primary != null) { + children.add(primary); + } + + children.addAll(participants); + + children.addAll(unknownChildren); + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantsMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantsMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantsMarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * ParticipantsMarshaller. + * + */ +public class ParticipantsMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantsUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantsUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ParticipantsUnmarshaller.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.Participant; +import org.opensaml.ws.wstrust.Participants; +import org.opensaml.ws.wstrust.Primary; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * ParticipantsUnmarshaller. + * + */ +public class ParticipantsUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Participants participants = (Participants) parentXMLObject; + + if (childXMLObject instanceof Primary) { + participants.setPrimary((Primary) childXMLObject); + } else if (childXMLObject instanceof Participant) { + participants.getParticipants().add((Participant) childXMLObject); + } else { + participants.getUnknownXMLObjects().add(childXMLObject); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/PrimaryBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/PrimaryBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/PrimaryBuilder.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Primary; + +/** + * Builder for the Primary element. + * + */ +public class PrimaryBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Primary buildObject() { + return buildObject(Primary.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Primary buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new PrimaryImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/PrimaryImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/PrimaryImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/PrimaryImpl.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Primary; + +/** + * PrimaryImpl. + * + */ +public class PrimaryImpl extends ParticipantTypeImpl implements Primary { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public PrimaryImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/PrimaryMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/PrimaryMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/PrimaryMarshaller.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * PrimaryMarshaller. + * + */ +public class PrimaryMarshaller extends ParticipantTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/PrimaryUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/PrimaryUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/PrimaryUnmarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * PrimaryUnmarshaller. + * + */ +public class PrimaryUnmarshaller extends ParticipantTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ProofEncryptionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ProofEncryptionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ProofEncryptionBuilder.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.ProofEncryption; + +/** + * Builder for the ProofEncryption element. + * + */ +public class ProofEncryptionBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public ProofEncryption buildObject() { + return buildObject(ProofEncryption.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ProofEncryption buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ProofEncryptionImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ProofEncryptionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ProofEncryptionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ProofEncryptionImpl.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.ProofEncryption; +import org.opensaml.xml.XMLObject; + +/** + * ProofEncryptionImpl. + * + */ +public class ProofEncryptionImpl extends AbstractWSTrustObject implements ProofEncryption { + + /** Wildcard child element. */ + private XMLObject unknownChild; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ProofEncryptionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public XMLObject getUnknownXMLObject() { + return unknownChild; + } + + /** {@inheritDoc} */ + public void setUnknownXMLObject(XMLObject unknownObject) { + unknownChild = prepareForAssignment(unknownChild, unknownObject); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (unknownChild != null) { + children.add(unknownChild); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ProofEncryptionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ProofEncryptionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ProofEncryptionMarshaller.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * Marshaller for the ProofEncryption element. + * + */ +public class ProofEncryptionMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ProofEncryptionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ProofEncryptionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ProofEncryptionUnmarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.ProofEncryption; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for the wst:ProofEncryption element. + * + */ +public class ProofEncryptionUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ProofEncryption pe = (ProofEncryption) parentXMLObject; + pe.setUnknownXMLObject(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ReasonBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ReasonBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ReasonBuilder.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Reason; + +/** + * Builder for the Reason element. + * + */ +public class ReasonBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Reason buildObject() { + return buildObject(Reason.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Reason buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ReasonImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ReasonImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ReasonImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ReasonImpl.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Reason; +import org.opensaml.xml.schema.impl.XSStringImpl; + +/** + * ReasonImpl. + * + */ +public class ReasonImpl extends XSStringImpl implements Reason { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ReasonImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ReasonMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ReasonMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ReasonMarshaller.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSStringMarshaller; + +/** + * Marshaller for the Reason element. + * + */ +public class ReasonMarshaller extends XSStringMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ReasonUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ReasonUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ReasonUnmarshaller.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSStringUnmarshaller; + +/** + * Unmarshaller for the wst:Reason element. + * + */ +public class ReasonUnmarshaller extends XSStringUnmarshaller { + + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewTargetBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewTargetBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewTargetBuilder.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RenewTarget; + +/** + * Builder for the RenewTarget element. + * + */ +public class RenewTargetBuilder extends AbstractWSTrustObjectBuilder { + + public RenewTarget buildObject() { + return buildObject(RenewTarget.ELEMENT_NAME); + } + + public RenewTarget buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RenewTargetImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewTargetImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewTargetImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewTargetImpl.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.RenewTarget; +import org.opensaml.xml.XMLObject; + +/** + * RenewTargetImpl. + * + */ +public class RenewTargetImpl extends AbstractWSTrustObject implements RenewTarget { + + /** Wildcard child element. */ + private XMLObject unknownChild; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RenewTargetImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public XMLObject getUnknownXMLObject() { + return unknownChild; + } + + /** {@inheritDoc} */ + public void setUnknownXMLObject(XMLObject unknownObject) { + unknownChild = unknownObject; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (unknownChild != null) { + children.add(unknownChild); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewTargetMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewTargetMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewTargetMarshaller.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * Marshaller for the RenewTarget element. + * + */ +public class RenewTargetMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewTargetUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewTargetUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewTargetUnmarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RenewTarget; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + + + +/** + * Unmarshaller for the <wst:RenewTarget> element. + * + */ +public class RenewTargetUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + RenewTarget rt = (RenewTarget) parentXMLObject; + rt.setUnknownXMLObject(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewingBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewingBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewingBuilder.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Renewing; + +/** + * Builder for the Renewing element. + * + */ +public class RenewingBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Renewing buildObject() { + return buildObject(Renewing.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Renewing buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RenewingImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewingImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewingImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewingImpl.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,112 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.List; + +import org.opensaml.ws.wstrust.Renewing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * RenewingImpl. + * + */ +public class RenewingImpl extends AbstractWSTrustObject implements Renewing { + + /** The Allow attribute value. */ + private XSBooleanValue allow; + + /** The OK attribute value. */ + private XSBooleanValue ok; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RenewingImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public Boolean isAllow() { + if (allow != null) { + return allow.getValue(); + } + + // Note: Default is true here, rather than the more common default of false. + return Boolean.TRUE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isAllowXSBoolean() { + return allow; + } + + /** {@inheritDoc} */ + public void setAllow(Boolean newAllow) { + if (newAllow != null) { + allow = prepareForAssignment(allow, new XSBooleanValue(newAllow, false)); + } else { + allow = prepareForAssignment(allow, null); + } + } + + /** {@inheritDoc} */ + public void setAllow(XSBooleanValue newAllow) { + allow = prepareForAssignment(allow, newAllow); + } + + /** {@inheritDoc} */ + public Boolean isOK() { + if (ok != null) { + return ok.getValue(); + } + + // Default is false. + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isOKXSBoolean() { + return ok; + } + + /** {@inheritDoc} */ + public void setOK(Boolean newOK) { + if (newOK != null) { + ok = prepareForAssignment(ok, new XSBooleanValue(newOK, false)); + } else { + ok = prepareForAssignment(ok, null); + } + } + + /** {@inheritDoc} */ + public void setOK(XSBooleanValue newOK) { + ok = prepareForAssignment(ok, newOK); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewingMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewingMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewingMarshaller.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.Renewing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * Marshaller for the Renewing element. + * + */ +public class RenewingMarshaller extends AbstractWSTrustObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Renewing renewing = (Renewing) xmlObject; + + if (renewing.isAllowXSBoolean() != null) { + domElement.setAttributeNS(null, Renewing.ALLOW_ATTRIB_NAME, renewing.isAllowXSBoolean().toString()); + } + + if (renewing.isOKXSBoolean() != null) { + domElement.setAttributeNS(null, Renewing.OK_ATTRIB_NAME, renewing.isOKXSBoolean().toString()); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewingUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewingUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RenewingUnmarshaller.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.Renewing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for the empty wst:Renewing element. + * + */ +public class RenewingUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + Renewing renewing = (Renewing) xmlObject; + + if (attribute.getLocalName().equals(Renewing.ALLOW_ATTRIB_NAME)) { + renewing.setAllow(XSBooleanValue.valueOf(attribute.getValue())); + } else if (attribute.getLocalName().equals(Renewing.OK_ATTRIB_NAME)) { + renewing.setOK(XSBooleanValue.valueOf(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestKETBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestKETBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestKETBuilder.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestKET; + +/** + * Builder for the RequestKET element. + * + */ +public class RequestKETBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public RequestKET buildObject() { + return buildObject(RequestKET.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RequestKET buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestKETImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestKETImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestKETImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestKETImpl.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.List; + +import org.opensaml.ws.wstrust.RequestKET; +import org.opensaml.xml.XMLObject; + +/** + * RequestKETImpl. + * + */ +public class RequestKETImpl extends AbstractWSTrustObject implements RequestKET { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RequestKETImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestKETMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestKETMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestKETMarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Marshaller for the RequestKET element. + * + */ +public class RequestKETMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestKETUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestKETUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestKETUnmarshaller.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Unmarshaller for the wst:RequestKET element. + * + */ +public class RequestKETUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenBuilder.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestSecurityToken; + +/** + * Builder for the RequestSecurityToken element. + * + * @see org.opensaml.ws.wstrust.RequestSecurityToken + * + */ +public class RequestSecurityTokenBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public RequestSecurityToken buildObject() { + return buildObject(RequestSecurityToken.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RequestSecurityToken buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestSecurityTokenImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenCollectionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenCollectionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenCollectionBuilder.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestSecurityTokenCollection; + +/** + * Builder for the RequestSecurityTokenCollection element. + * + */ +public class RequestSecurityTokenCollectionBuilder extends + AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public RequestSecurityTokenCollection buildObject() { + return buildObject(RequestSecurityTokenCollection.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RequestSecurityTokenCollection buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestSecurityTokenCollectionImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenCollectionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenCollectionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenCollectionImpl.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.RequestSecurityToken; +import org.opensaml.ws.wstrust.RequestSecurityTokenCollection; +import org.opensaml.xml.XMLObject; + +/** + * RequestSecurityTokenCollectionImpl. + * + */ +public class RequestSecurityTokenCollectionImpl extends AbstractWSTrustObject + implements RequestSecurityTokenCollection { + + /** The list of wst:RequestSecurityToken child elements. */ + private List requestSecurityTokens; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RequestSecurityTokenCollectionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + requestSecurityTokens = new ArrayList(); + } + + /** {@inheritDoc} */ + public List getRequestSecurityTokens() { + return requestSecurityTokens; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List children = new ArrayList(); + children.addAll(requestSecurityTokens); + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenCollectionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenCollectionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenCollectionMarshaller.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,26 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +/** + * Marshaller for the RequestSecurityTokenCollection element. + * + */ +public class RequestSecurityTokenCollectionMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenCollectionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenCollectionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenCollectionUnmarshaller.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestSecurityToken; +import org.opensaml.ws.wstrust.RequestSecurityTokenCollection; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + + +/** + * RequestSecurityTokenCollectionUnmarshaller. + * + */ +public class RequestSecurityTokenCollectionUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + RequestSecurityTokenCollection rstc = (RequestSecurityTokenCollection) parentXMLObject; + if (childXMLObject instanceof RequestSecurityToken) { + rstc.getRequestSecurityTokens().add((RequestSecurityToken) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenImpl.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,91 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wstrust.RequestSecurityToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * RequestSecurityTokenImpl. + * + */ +public class RequestSecurityTokenImpl extends AbstractWSTrustObject implements RequestSecurityToken { + + /** Context attribute value. */ + private String context; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RequestSecurityTokenImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public String getContext() { + return context; + } + + /** {@inheritDoc} */ + public void setContext(String newContext) { + context = prepareForAssignment(context, newContext); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + children.addAll(unknownChildren); + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenMarshaller.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestSecurityToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for the RequestSecurityToken element. + * + */ +public class RequestSecurityTokenMarshaller extends AbstractWSTrustObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + RequestSecurityToken rst = (RequestSecurityToken) xmlObject; + if (rst.getContext() != null) { + domElement.setAttributeNS(null, RequestSecurityToken.CONTEXT_ATTRIB_NAME, rst.getContext()); + } + + XMLHelper.marshallAttributeMap(rst.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseBuilder.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestSecurityTokenResponse; + +/** + * Builder for the RequestSecurityTokenResponse element. + * + */ +public class RequestSecurityTokenResponseBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public RequestSecurityTokenResponse buildObject() { + return buildObject(RequestSecurityTokenResponse.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RequestSecurityTokenResponse buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestSecurityTokenResponseImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseCollectionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseCollectionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseCollectionBuilder.java 17 Aug 2012 15:08:45 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestSecurityTokenResponseCollection; + +/** + * Builder for the RequestSecurityTokenResponseCollection element. + * + */ +public class RequestSecurityTokenResponseCollectionBuilder extends + AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public RequestSecurityTokenResponseCollection buildObject() { + return buildObject(RequestSecurityTokenResponseCollection.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RequestSecurityTokenResponseCollection buildObject( String namespaceURI, String localName, + String namespacePrefix) { + return new RequestSecurityTokenResponseCollectionImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseCollectionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseCollectionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseCollectionImpl.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,74 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.RequestSecurityTokenResponse; +import org.opensaml.ws.wstrust.RequestSecurityTokenResponseCollection; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; + +/** + * RequestSecurityTokenResponseCollectionImpl. + * + */ +public class RequestSecurityTokenResponseCollectionImpl extends AbstractWSTrustObject implements + RequestSecurityTokenResponseCollection { + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** The list of wst:RequestSecurityTokenResponse child elements. */ + private List requestSecurityTokenResponses; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + * + */ + public RequestSecurityTokenResponseCollectionImpl(String namespaceURI, String elementLocalName, + String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + requestSecurityTokenResponses = new ArrayList(); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getRequestSecurityTokenResponses() { + return requestSecurityTokenResponses; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List children = new ArrayList(); + children.addAll(requestSecurityTokenResponses); + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseCollectionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseCollectionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseCollectionMarshaller.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestSecurityTokenResponseCollection; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for the RequestSecurityTokenResponseCollection element. + * + */ +public class RequestSecurityTokenResponseCollectionMarshaller extends AbstractWSTrustObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + RequestSecurityTokenResponseCollection rstrc = (RequestSecurityTokenResponseCollection) xmlObject; + XMLHelper.marshallAttributeMap(rstrc.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseCollectionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseCollectionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseCollectionUnmarshaller.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestSecurityTokenResponse; +import org.opensaml.ws.wstrust.RequestSecurityTokenResponseCollection; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + + +/** + * RequestSecurityTokenResponseCollectionUnmarshaller. + * + */ +public class RequestSecurityTokenResponseCollectionUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + RequestSecurityTokenResponseCollection rstrc = (RequestSecurityTokenResponseCollection) xmlObject; + XMLHelper.unmarshallToAttributeMap(rstrc.getUnknownAttributes(), attribute); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + RequestSecurityTokenResponseCollection rstrc = (RequestSecurityTokenResponseCollection) parentXMLObject; + if (childXMLObject instanceof RequestSecurityTokenResponse) { + rstrc.getRequestSecurityTokenResponses().add((RequestSecurityTokenResponse) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseImpl.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,91 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wstrust.RequestSecurityTokenResponse; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * RequestSecurityTokenResponseImpl. + * + */ +public class RequestSecurityTokenResponseImpl extends AbstractWSTrustObject implements RequestSecurityTokenResponse { + + /** Context attribute value. */ + private String context; + + /** Wildcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RequestSecurityTokenResponseImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public String getContext() { + return context; + } + + /** {@inheritDoc} */ + public void setContext(String newContext) { + context = prepareForAssignment(context, newContext); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + children.addAll(unknownChildren); + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseMarshaller.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestSecurityTokenResponse; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for the RequestSecurityTokenResponse element. + * + */ +public class RequestSecurityTokenResponseMarshaller extends AbstractWSTrustObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + RequestSecurityTokenResponse rstr= (RequestSecurityTokenResponse) xmlObject; + if (rstr.getContext() != null) { + domElement.setAttributeNS(null, RequestSecurityTokenResponse.CONTEXT_ATTRIB_NAME, rstr.getContext()); + } + XMLHelper.marshallAttributeMap(rstr.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenResponseUnmarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestSecurityTokenResponse; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + + + +/** + * RequestSecurityTokenResponseUnmarshaller. + * + */ +public class RequestSecurityTokenResponseUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + RequestSecurityTokenResponse rstr = (RequestSecurityTokenResponse) xmlObject; + if (RequestSecurityTokenResponse.CONTEXT_ATTRIB_NAME.equals(attribute.getLocalName())) { + rstr.setContext(attribute.getValue()); + } else { + XMLHelper.unmarshallToAttributeMap(rstr.getUnknownAttributes(), attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + RequestSecurityTokenResponse rstr = (RequestSecurityTokenResponse) parentXMLObject; + rstr.getUnknownXMLObjects().add(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestSecurityTokenUnmarshaller.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.RequestSecurityToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * RequestSecurityTokenUnmarshaller. + * + */ +public class RequestSecurityTokenUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + RequestSecurityToken rst = (RequestSecurityToken) xmlObject; + if (RequestSecurityToken.CONTEXT_ATTRIB_NAME.equals(attribute.getLocalName())) { + rst.setContext(attribute.getValue()); + } else { + XMLHelper.unmarshallToAttributeMap(rst.getUnknownAttributes(), attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + RequestSecurityToken rst = (RequestSecurityToken) parentXMLObject; + rst.getUnknownXMLObjects().add(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestTypeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestTypeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestTypeBuilder.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestType; + +/** + * Builder for the RequestType element. + * + * @see org.opensaml.ws.wstrust.RequestType + * + */ +public class RequestTypeBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public RequestType buildObject() { + return buildObject(RequestType.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RequestType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestTypeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestTypeImpl.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestType; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * RequestTypeImpl. + * + */ +public class RequestTypeImpl extends XSURIImpl implements RequestType { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RequestTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestTypeMarshaller.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the RequestType element. + * + */ +public class RequestTypeMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestTypeUnmarshaller.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the <wst:RequestType> element. + * + */ +public class RequestTypeUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedAttachedReferenceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedAttachedReferenceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedAttachedReferenceBuilder.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestedAttachedReference; + +/** + * Builder for the RequestedAttachedReference element. + * + */ +public class RequestedAttachedReferenceBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public RequestedAttachedReference buildObject() { + return buildObject(RequestedAttachedReference.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RequestedAttachedReference buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestedAttachedReferenceImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedAttachedReferenceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedAttachedReferenceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedAttachedReferenceImpl.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestedAttachedReference; + +/** + * RequestedAttachedReferenceImpl. + * + */ +public class RequestedAttachedReferenceImpl extends RequestedReferenceTypeImpl implements + RequestedAttachedReference { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RequestedAttachedReferenceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedAttachedReferenceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedAttachedReferenceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedAttachedReferenceMarshaller.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Marshaller for the RequestedAttachedReference element. + * + */ +public class RequestedAttachedReferenceMarshaller extends RequestedReferenceTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedAttachedReferenceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedAttachedReferenceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedAttachedReferenceUnmarshaller.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Unmarshaller for the wst:RequestedAttachedReference element. + * + */ +public class RequestedAttachedReferenceUnmarshaller extends RequestedReferenceTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedProofTokenBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedProofTokenBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedProofTokenBuilder.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestedProofToken; + +/** + * Builder for the RequestedProofToken element. + * + */ +public class RequestedProofTokenBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public RequestedProofToken buildObject() { + return buildObject(RequestedProofToken.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RequestedProofToken buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestedProofTokenImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedProofTokenImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedProofTokenImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedProofTokenImpl.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.RequestedProofToken; +import org.opensaml.xml.XMLObject; + +/** + * RequestedProofTokenImpl. + * + */ +public class RequestedProofTokenImpl extends AbstractWSTrustObject implements RequestedProofToken { + + /** Unknown child element. */ + private XMLObject unknownChild; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RequestedProofTokenImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public XMLObject getUnknownXMLObject() { + return unknownChild; + } + + /** {@inheritDoc} */ + public void setUnknownXMLObject(XMLObject unknownObject) { + unknownChild = prepareForAssignment(unknownChild, unknownObject); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (unknownChild != null) { + children.add(unknownChild); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedProofTokenMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedProofTokenMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedProofTokenMarshaller.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * Marshaller for the RequestedProofToken element. + * + */ +public class RequestedProofTokenMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedProofTokenUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedProofTokenUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedProofTokenUnmarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.RequestedProofToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for the wst:RequestedProofToken element. + * + */ +public class RequestedProofTokenUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + RequestedProofToken rpt = (RequestedProofToken) parentXMLObject; + rpt.setUnknownXMLObject(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedReferenceTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedReferenceTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedReferenceTypeImpl.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wssecurity.SecurityTokenReference; +import org.opensaml.ws.wstrust.RequestedReferenceType; +import org.opensaml.xml.XMLObject; + +/** + * RequestedReferenceTypeImpl. + * + */ +public class RequestedReferenceTypeImpl extends AbstractWSTrustObject implements RequestedReferenceType { + + /** SecurityTokenReference child element. */ + private SecurityTokenReference securityTokenReference; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public RequestedReferenceTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public SecurityTokenReference getSecurityTokenReference() { + return securityTokenReference; + } + + /** {@inheritDoc} */ + public void setSecurityTokenReference(SecurityTokenReference newSecurityTokenReference) { + securityTokenReference = prepareForAssignment(securityTokenReference, newSecurityTokenReference); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List children = new ArrayList(); + if (securityTokenReference != null) { + children.add(securityTokenReference); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedReferenceTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedReferenceTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedReferenceTypeMarshaller.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +/** + * RequestedReferenceTypeMarshaller. + * + */ +public class RequestedReferenceTypeMarshaller extends AbstractWSTrustObjectMarshaller { + + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedReferenceTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedReferenceTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedReferenceTypeUnmarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wssecurity.SecurityTokenReference; +import org.opensaml.ws.wstrust.RequestedReferenceType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + + + +/** + * Unmarshaller for the element of type RequestedReferenceType. + * + */ +public class RequestedReferenceTypeUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + RequestedReferenceType rrt = (RequestedReferenceType) parentXMLObject; + if (childXMLObject instanceof SecurityTokenReference) { + rrt.setSecurityTokenReference((SecurityTokenReference) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedSecurityTokenBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedSecurityTokenBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedSecurityTokenBuilder.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestedSecurityToken; + +/** + * Builder for the RequestedSecurityToken element. + * + */ +public class RequestedSecurityTokenBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public RequestedSecurityToken buildObject() { + return buildObject(RequestedSecurityToken.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RequestedSecurityToken buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestedSecurityTokenImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedSecurityTokenImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedSecurityTokenImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedSecurityTokenImpl.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.RequestedSecurityToken; +import org.opensaml.xml.XMLObject; + +/** + * RequestedSecurityTokenImpl. + * + */ +public class RequestedSecurityTokenImpl extends AbstractWSTrustObject implements RequestedSecurityToken { + + /** Wildcard child element. */ + private XMLObject unknownChild; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RequestedSecurityTokenImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public XMLObject getUnknownXMLObject() { + return unknownChild; + } + + /** {@inheritDoc} */ + public void setUnknownXMLObject(XMLObject unknownObject) { + unknownChild = unknownObject; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (unknownChild != null) { + children.add(unknownChild); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedSecurityTokenMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedSecurityTokenMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedSecurityTokenMarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Marshaller for the RequestedSecurityToken element. + * + */ +public class RequestedSecurityTokenMarshaller extends AbstractWSTrustObjectMarshaller { + + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedSecurityTokenUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedSecurityTokenUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedSecurityTokenUnmarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.RequestedSecurityToken; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for the <wst:RequestedSecurityToken> element. + * + */ +public class RequestedSecurityTokenUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + RequestedSecurityToken reqToken = (RequestedSecurityToken) parentXMLObject; + reqToken.setUnknownXMLObject(childXMLObject); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedTokenCancelledBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedTokenCancelledBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedTokenCancelledBuilder.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestedTokenCancelled; + +/** + * Builder for the RequestedTokenCancelled element. + * + */ +public class RequestedTokenCancelledBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public RequestedTokenCancelled buildObject() { + return buildObject(RequestedTokenCancelled.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RequestedTokenCancelled buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestedTokenCancelledImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedTokenCancelledImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedTokenCancelledImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedTokenCancelledImpl.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.List; + +import org.opensaml.ws.wstrust.RequestedTokenCancelled; +import org.opensaml.xml.XMLObject; + +/** + * RequestedTokenCancelledImpl. + * + */ +public class RequestedTokenCancelledImpl extends AbstractWSTrustObject implements RequestedTokenCancelled { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RequestedTokenCancelledImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedTokenCancelledMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedTokenCancelledMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedTokenCancelledMarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Marshaller for the RequestedTokenCancelled element. + * + */ +public class RequestedTokenCancelledMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedTokenCancelledUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedTokenCancelledUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedTokenCancelledUnmarshaller.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Unmarshaller for the empty wst:RequestedTokenCancelled element. + * + */ +public class RequestedTokenCancelledUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedUnattachedReferenceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedUnattachedReferenceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedUnattachedReferenceBuilder.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestedUnattachedReference; + +/** + * Builder for the RequestedUnattachedReference element. + * + */ +public class RequestedUnattachedReferenceBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public RequestedUnattachedReference buildObject() { + return buildObject(RequestedUnattachedReference.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RequestedUnattachedReference buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestedUnattachedReferenceImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedUnattachedReferenceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedUnattachedReferenceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedUnattachedReferenceImpl.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.RequestedUnattachedReference; + +/** + * RequestedUnattachedReferenceImpl. + * + */ +public class RequestedUnattachedReferenceImpl extends RequestedReferenceTypeImpl implements + RequestedUnattachedReference { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public RequestedUnattachedReferenceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedUnattachedReferenceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedUnattachedReferenceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedUnattachedReferenceMarshaller.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Marshaller for the RequestedUnattachedReference element. + * + */ +public class RequestedUnattachedReferenceMarshaller extends RequestedReferenceTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedUnattachedReferenceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedUnattachedReferenceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/RequestedUnattachedReferenceUnmarshaller.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Unmarshaller for the wst:RequestedUnattachedReference element. + * + */ +public class RequestedUnattachedReferenceUnmarshaller extends RequestedReferenceTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeBuilder.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.SignChallenge; + +/** + * Builder for the SignChallenge element. + * + */ +public class SignChallengeBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public SignChallenge buildObject() { + return buildObject(SignChallenge.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public SignChallenge buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SignChallengeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeImpl.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.SignChallenge; + +/** + * SignChallengeImpl. + * + */ +public class SignChallengeImpl extends SignChallengeTypeImpl implements SignChallenge { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public SignChallengeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeMarshaller.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Marshaller for the SignChallenge element. + * + */ +public class SignChallengeMarshaller extends SignChallengeTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeResponseBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeResponseBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeResponseBuilder.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.SignChallengeResponse; + +/** + * Builder for the SignChallengeResponse element. + * + */ +public class SignChallengeResponseBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public SignChallengeResponse buildObject() { + return buildObject(SignChallengeResponse.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public SignChallengeResponse buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SignChallengeResponseImpl(namespaceURI, localName, namespacePrefix); } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeResponseImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeResponseImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeResponseImpl.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.SignChallengeResponse; + +/** + * SignChallengeImpl. + * + */ +public class SignChallengeResponseImpl extends SignChallengeTypeImpl implements SignChallengeResponse { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public SignChallengeResponseImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeResponseMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeResponseMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeResponseMarshaller.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Marshaller for the SignChallengeResponse element. + * + */ +public class SignChallengeResponseMarshaller extends SignChallengeTypeMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeResponseUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeResponseUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeResponseUnmarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Unmarshaller for the wst:SignChallengeResponse element. + * + */ +public class SignChallengeResponseUnmarshaller extends SignChallengeTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeTypeImpl.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,95 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.ws.wstrust.Challenge; +import org.opensaml.ws.wstrust.SignChallengeType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * SignChallengeTypeImpl. + * + */ +public class SignChallengeTypeImpl extends AbstractWSTrustObject implements SignChallengeType { + + /** Wilcard child elements. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** Wildcard attributes. */ + private AttributeMap unknownAttributes; + + /** {@link Challenge} child element. */ + private Challenge challenge; + + /** + * Constructor. + * + * @param namespaceURI namespace of the element + * @param elementLocalName name of the element + * @param namespacePrefix namespace prefix of the element + */ + public SignChallengeTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public Challenge getChallenge() { + return challenge; + } + + /** {@inheritDoc} */ + public void setChallenge(Challenge newChallenge) { + challenge = prepareForAssignment(challenge, newChallenge); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List children = new ArrayList(); + if (challenge != null) { + children.add(challenge); + } + children.addAll(unknownChildren); + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeTypeMarshaller.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.SignChallengeType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + + +/** + * SignChallengeTypeMarshaller. + * + */ +public class SignChallengeTypeMarshaller extends AbstractWSTrustObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + SignChallengeType signChallengeType = (SignChallengeType) xmlObject; + XMLHelper.marshallAttributeMap(signChallengeType.getUnknownAttributes(), domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeTypeUnmarshaller.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.Challenge; +import org.opensaml.ws.wstrust.SignChallengeType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for the SignChallengeType element. + * + * + */ +public class SignChallengeTypeUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + SignChallengeType signChallengeType= (SignChallengeType) xmlObject; + XMLHelper.unmarshallToAttributeMap(signChallengeType.getUnknownAttributes(), attribute); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + SignChallengeType signChallengeType= (SignChallengeType) parentXMLObject; + + if (childXMLObject instanceof Challenge) { + signChallengeType.setChallenge((Challenge) childXMLObject); + } else { + signChallengeType.getUnknownXMLObjects().add(childXMLObject); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignChallengeUnmarshaller.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Unmarshaller for the wst:SignChallenge element. + * + */ +public class SignChallengeUnmarshaller extends SignChallengeTypeUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignWithBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignWithBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignWithBuilder.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.SignWith; + +/** + * Builder for the SignWith element. + * + */ +public class SignWithBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public SignWith buildObject() { + return buildObject(SignWith.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public SignWith buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SignWithImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignWithImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignWithImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignWithImpl.java 17 Aug 2012 15:08:40 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.SignWith; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * SignWithImpl. + * + */ +public class SignWithImpl extends XSURIImpl implements SignWith { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public SignWithImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignWithMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignWithMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignWithMarshaller.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the SignWith element. + * + */ +public class SignWithMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignWithUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignWithUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignWithUnmarshaller.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the wst:SignWith element. + * + */ +public class SignWithUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignatureAlgorithmBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignatureAlgorithmBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignatureAlgorithmBuilder.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.SignatureAlgorithm; + +/** + * Builder for the SignatureAlgorithm element. + * + */ +public class SignatureAlgorithmBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public SignatureAlgorithm buildObject() { + return buildObject(SignatureAlgorithm.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public SignatureAlgorithm buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SignatureAlgorithmImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignatureAlgorithmImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignatureAlgorithmImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignatureAlgorithmImpl.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.SignatureAlgorithm; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * SignatureAlgorithmImpl. + * + */ +public class SignatureAlgorithmImpl extends XSURIImpl implements SignatureAlgorithm { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public SignatureAlgorithmImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignatureAlgorithmMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignatureAlgorithmMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignatureAlgorithmMarshaller.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the SignatureAlgorithm element. + * + */ +public class SignatureAlgorithmMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignatureAlgorithmUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignatureAlgorithmUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/SignatureAlgorithmUnmarshaller.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the wst:SignatureAlgorithm element. + * + */ +public class SignatureAlgorithmUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/StatusBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/StatusBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/StatusBuilder.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.Status; + +/** + * Builder for the Status element. + * + */ +public class StatusBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public Status buildObject() { + return buildObject(Status.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public Status buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/StatusImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/StatusImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/StatusImpl.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.Code; +import org.opensaml.ws.wstrust.Reason; +import org.opensaml.ws.wstrust.Status; +import org.opensaml.xml.XMLObject; + +/** + * StatusImpl. + * + */ +public class StatusImpl extends AbstractWSTrustObject implements Status { + + /** The Code child element. */ + private Code code; + + /** The Reason child element. */ + private Reason reason; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public StatusImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public Code getCode() { + return code; + } + + /** {@inheritDoc} */ + public Reason getReason() { + return reason; + } + + /** {@inheritDoc} */ + public void setCode(Code newCode) { + code = prepareForAssignment(code, newCode); + } + + /** {@inheritDoc} */ + public void setReason(Reason newReason) { + reason = prepareForAssignment(reason, newReason); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (code != null) { + children.add(code); + } + if (reason != null) { + children.add(reason); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/StatusMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/StatusMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/StatusMarshaller.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +/** + * Marshaller for the Status element. + * + */ +public class StatusMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/StatusUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/StatusUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/StatusUnmarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.Code; +import org.opensaml.ws.wstrust.Reason; +import org.opensaml.ws.wstrust.Status; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for the wst:Status element. + * + */ +public class StatusUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Status status= (Status) parentXMLObject; + + if (childXMLObject instanceof Code) { + status.setCode((Code) childXMLObject); + } else if (childXMLObject instanceof Reason) { + status.setReason((Reason) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/TokenTypeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/TokenTypeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/TokenTypeBuilder.java 17 Aug 2012 15:08:42 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.TokenType; + +/** + * Builder for the TokenType element. + * + * @see org.opensaml.ws.wstrust.TokenType + * + */ +public class TokenTypeBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public TokenType buildObject() { + return buildObject(TokenType.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public TokenType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new TokenTypeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/TokenTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/TokenTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/TokenTypeImpl.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.TokenType; +import org.opensaml.xml.schema.impl.XSURIImpl; + +/** + * TokenTypeImpl. + * + */ +public class TokenTypeImpl extends XSURIImpl implements TokenType { + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public TokenTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/TokenTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/TokenTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/TokenTypeMarshaller.java 17 Aug 2012 15:08:48 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIMarshaller; + +/** + * Marshaller for the TokenType element. + * + */ +public class TokenTypeMarshaller extends XSURIMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/TokenTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/TokenTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/TokenTypeUnmarshaller.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.xml.schema.impl.XSURIUnmarshaller; + +/** + * Unmarshaller for the wst:TokenType element. + * + */ +public class TokenTypeUnmarshaller extends XSURIUnmarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/UseKeyBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/UseKeyBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/UseKeyBuilder.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.UseKey; + +/** + * Builder for the UseKey element. + * + */ +public class UseKeyBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public UseKey buildObject() { + return buildObject(UseKey.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public UseKey buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new UseKeyImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/UseKeyImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/UseKeyImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/UseKeyImpl.java 17 Aug 2012 15:08:43 -0000 1.1 @@ -0,0 +1,79 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.UseKey; +import org.opensaml.xml.XMLObject; + +/** + * UseKeyImpl. + * + */ +public class UseKeyImpl extends AbstractWSTrustObject implements UseKey { + + /** Wildcard child element. */ + private XMLObject unknownChild; + + /** wst:UseKey/@Sig attribute value. */ + private String sig; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public UseKeyImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getSig() { + return sig; + } + + /** {@inheritDoc} */ + public void setSig(String newSig) { + sig = prepareForAssignment(sig, newSig); + } + + /** {@inheritDoc} */ + public XMLObject getUnknownXMLObject() { + return unknownChild; + } + + /** {@inheritDoc} */ + public void setUnknownXMLObject(XMLObject unknownObject) { + unknownChild = prepareForAssignment(unknownChild, unknownObject); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (unknownChild != null) { + children.add(unknownChild); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/UseKeyMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/UseKeyMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/UseKeyMarshaller.java 17 Aug 2012 15:08:46 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.UseKey; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * Marshaller for the UseKey element. + * + */ +public class UseKeyMarshaller extends AbstractWSTrustObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + UseKey useKey = (UseKey) xmlObject; + if (useKey.getSig() != null) { + domElement.setAttributeNS(null, UseKey.SIG_ATTRIB_NAME, useKey.getSig()); + } + super.marshallAttributes(xmlObject, domElement); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/UseKeyUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/UseKeyUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/UseKeyUnmarshaller.java 17 Aug 2012 15:08:50 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.UseKey; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for the wst:UseKey element. + * + */ +public class UseKeyUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + UseKey uk = (UseKey) xmlObject; + + if (UseKey.SIG_ATTRIB_NAME.equals(attribute.getLocalName())) { + uk.setSig(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + UseKey uk = (UseKey) parentXMLObject; + uk.setUnknownXMLObject(childXMLObject); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ValidateTargetBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ValidateTargetBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ValidateTargetBuilder.java 17 Aug 2012 15:08:41 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import org.opensaml.ws.wstrust.ValidateTarget; + +/** + * Builder for the ValidateTarget element. + * + */ +public class ValidateTargetBuilder extends AbstractWSTrustObjectBuilder { + + /** {@inheritDoc} */ + public ValidateTarget buildObject() { + return buildObject(ValidateTarget.ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ValidateTarget buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ValidateTargetImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ValidateTargetImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ValidateTargetImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ValidateTargetImpl.java 17 Aug 2012 15:08:47 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.ws.wstrust.ValidateTarget; +import org.opensaml.xml.XMLObject; + +/** + * ValidateTargetImpl. + * + */ +public class ValidateTargetImpl extends AbstractWSTrustObject implements ValidateTarget { + + /** Wildcard child element. */ + private XMLObject unknownChild; + + /** + * Constructor. + * + * @param namespaceURI The namespace of the element + * @param elementLocalName The local name of the element + * @param namespacePrefix The namespace prefix of the element + */ + public ValidateTargetImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public XMLObject getUnknownXMLObject() { + return unknownChild; + } + + /** {@inheritDoc} */ + public void setUnknownXMLObject(XMLObject unknownObject) { + unknownChild = prepareForAssignment(unknownChild, unknownObject); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (unknownChild != null) { + children.add(unknownChild); + } + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ValidateTargetMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ValidateTargetMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ValidateTargetMarshaller.java 17 Aug 2012 15:08:49 -0000 1.1 @@ -0,0 +1,28 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + + +/** + * Marshaller for the ValidateTarget element. + * + */ +public class ValidateTargetMarshaller extends AbstractWSTrustObjectMarshaller { + +} Index: 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ValidateTargetUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ValidateTargetUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/openws/org/opensaml/ws/wstrust/impl/ValidateTargetUnmarshaller.java 17 Aug 2012 15:08:44 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.ws.wstrust.impl; + + +import org.opensaml.ws.wstrust.ValidateTarget; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for the wst:ValidateTarget element. + * + */ +public class ValidateTargetUnmarshaller extends AbstractWSTrustObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ValidateTarget vt = (ValidateTarget) parentXMLObject; + vt.setUnknownXMLObject(childXMLObject); + } + +} Index: 3rdParty_sources/quartz/org/quartz/Calendar.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/Calendar.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/Calendar.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,104 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ + + +package org.quartz; + +/** + *

+ * An interface to be implemented by objects that define spaces of time that + * should be included or excluded from a {@link Trigger}'s + * normal 'firing' schedule. + *

+ * + * @author James House + * @author Juergen Donnerstag + */ +public interface Calendar extends java.io.Serializable { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + int MONTH = 0; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Set a new base calendar or remove the existing one. + *

+ */ + public void setBaseCalendar(Calendar baseCalendar); + + /** + *

+ * Get the base calendar. Will be null, if not set. + *

+ */ + public Calendar getBaseCalendar(); + + /** + *

+ * Determine whether the given time (in milliseconds) is 'included' by the + * Calendar. + *

+ */ + public boolean isTimeIncluded(long timeStamp); + + /** + *

+ * Determine the next time (in milliseconds) that is 'included' by the + * Calendar after the given time. + *

+ */ + public long getNextIncludedTime(long timeStamp); + + /** + *

+ * Return the description given to the Calendar instance by + * its creator (if any). + *

+ * + * @return null if no description was set. + */ + public String getDescription(); + + /** + *

+ * Set a description for the Calendar instance - may be + * useful for remembering/displaying the purpose of the calendar, though + * the description has no meaning to Quartz. + *

+ */ + public void setDescription(String description); +} Index: 3rdParty_sources/quartz/org/quartz/CriticalSchedulerException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/CriticalSchedulerException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/CriticalSchedulerException.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,53 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ + +package org.quartz; + +/** + *

+ * An exception that is thrown to indicate that there has been a critical + * failure within the scheduler's core services (such as loss of database + * connectivity). + *

+ * + * @author James House + */ +public class CriticalSchedulerException extends SchedulerException { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a CriticalSchedulerException with the given message. + *

+ */ + public CriticalSchedulerException(String msg, int errCode) { + super(msg); + setErrorCode(errCode); + } +} Index: 3rdParty_sources/quartz/org/quartz/CronExpression.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/CronExpression.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/CronExpression.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,1388 @@ +package org.quartz; + +import java.io.Serializable; +import java.text.ParseException; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; +import java.util.SortedSet; +import java.util.StringTokenizer; +import java.util.TimeZone; +import java.util.TreeSet; + +/** + * Provides a parser and evaluator for unix-like cron expressions. Cron + * expressions provide the ability to specify complex time combinations such as + * "At 8:00am every Monday through Friday" or "At 1:30am every + * last Friday of the month". + *

+ * Cron expressions are comprised of 6 required fields and one optional field + * separated by white space. The fields respectively are described as follows: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Field Name Allowed Values Allowed Special Characters
Seconds  + * 0-59  + * , - * /
Minutes  + * 0-59  + * , - * /
Hours  + * 0-23  + * , - * /
Day-of-month  + * 1-31  + * , - * ? / L W C
Month  + * 1-12 or JAN-DEC  + * , - * /
Day-of-Week  + * 1-7 or SUN-SAT  + * , - * ? / L #
Year (Optional)  + * empty, 1970-2099  + * , - * /
+ *

+ * The '*' character is used to specify all values. For example, "*" + * in the minute field means "every minute". + *

+ * The '?' character is allowed for the day-of-month and day-of-week fields. It + * is used to specify 'no specific value'. This is useful when you need to + * specify something in one of the two fileds, but not the other. + *

+ * The '-' character is used to specify ranges For example "10-12" in + * the hour field means "the hours 10, 11 and 12". + *

+ * The ',' character is used to specify additional values. For example + * "MON,WED,FRI" in the day-of-week field means "the days Monday, + * Wednesday, and Friday". + *

+ * The '/' character is used to specify increments. For example "0/15" + * in the seconds field means "the seconds 0, 15, 30, and 45". And + * "5/15" in the seconds field means "the seconds 5, 20, 35, and + * 50". Specifying '*' before the '/' is equivalent to specifying 0 is + * the value to start with. Essentially, for each field in the expression, there + * is a set of numbers that can be turned on or off. For seconds and minutes, + * the numbers range from 0 to 59. For hours 0 to 23, for days of the month 0 to + * 31, and for months 1 to 12. The "/" character simply helps you turn + * on every "nth" value in the given set. Thus "7/6" in the + * month field only turns on month "7", it does NOT mean every 6th + * month, please note that subtlety. + *

+ * The 'L' character is allowed for the day-of-month and day-of-week fields. + * This character is short-hand for "last", but it has different + * meaning in each of the two fields. For example, the value "L" in + * the day-of-month field means "the last day of the month" - day 31 + * for January, day 28 for February on non-leap years. If used in the + * day-of-week field by itself, it simply means "7" or + * "SAT". But if used in the day-of-week field after another value, it + * means "the last xxx day of the month" - for example "6L" + * means "the last friday of the month". When using the 'L' option, it + * is important not to specify lists, or ranges of values, as you'll get + * confusing results. + *

+ * The 'W' character is allowed for the day-of-month field. This character + * is used to specify the weekday (Monday-Friday) nearest the given day. As an + * example, if you were to specify "15W" as the value for the + * day-of-month field, the meaning is: "the nearest weekday to the 15th of + * the month". So if the 15th is a Saturday, the trigger will fire on + * Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the + * 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th. + * However if you specify "1W" as the value for day-of-month, and the + * 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not + * 'jump' over the boundary of a month's days. The 'W' character can only be + * specified when the day-of-month is a single day, not a range or list of days. + *

+ * The 'L' and 'W' characters can also be combined for the day-of-month + * expression to yield 'LW', which translates to "last weekday of the + * month". + *

+ * The '#' character is allowed for the day-of-week field. This character is + * used to specify "the nth" XXX day of the month. For example, the + * value of "6#3" in the day-of-week field means the third Friday of + * the month (day 6 = Friday and "#3" = the 3rd one in the month). + * Other examples: "2#1" = the first Monday of the month and + * "4#5" = the fifth Wednesday of the month. Note that if you specify + * "#5" and there is not 5 of the given day-of-week in the month, then + * no firing will occur that month. + *

+ * + *

+ * The legal characters and the names of months and days of the week are not + * case sensitive. + * + *

+ * NOTES: + *

    + *
  • Support for specifying both a day-of-week and a day-of-month value is + * not complete (you'll need to use the '?' character in on of these fields). + *
  • + *
+ *

+ * + * + * @author Sharada Jambula, James House + * @author Contributions from Mads Henderson + * @author Refactoring from CronTrigger to CronExpression by Aaron Craven + */ +public class CronExpression implements Serializable, Cloneable { + + private static final long serialVersionUID = 12423409423L; + + protected static final int SECOND = 0; + protected static final int MINUTE = 1; + protected static final int HOUR = 2; + protected static final int DAY_OF_MONTH = 3; + protected static final int MONTH = 4; + protected static final int DAY_OF_WEEK = 5; + protected static final int YEAR = 6; + protected static final int ALL_SPEC_INT = 99; // '*' + protected static final int NO_SPEC_INT = 98; // '?' + protected static final Integer ALL_SPEC = new Integer(ALL_SPEC_INT); + protected static final Integer NO_SPEC = new Integer(NO_SPEC_INT); + + protected static Map monthMap = new HashMap(20); + protected static Map dayMap = new HashMap(60); + static { + monthMap.put("JAN", new Integer(0)); + monthMap.put("FEB", new Integer(1)); + monthMap.put("MAR", new Integer(2)); + monthMap.put("APR", new Integer(3)); + monthMap.put("MAY", new Integer(4)); + monthMap.put("JUN", new Integer(5)); + monthMap.put("JUL", new Integer(6)); + monthMap.put("AUG", new Integer(7)); + monthMap.put("SEP", new Integer(8)); + monthMap.put("OCT", new Integer(9)); + monthMap.put("NOV", new Integer(10)); + monthMap.put("DEC", new Integer(11)); + + dayMap.put("SUN", new Integer(1)); + dayMap.put("MON", new Integer(2)); + dayMap.put("TUE", new Integer(3)); + dayMap.put("WED", new Integer(4)); + dayMap.put("THU", new Integer(5)); + dayMap.put("FRI", new Integer(6)); + dayMap.put("SAT", new Integer(7)); + } + + private String cronExpression = null; + private TimeZone timeZone = null; + protected transient TreeSet seconds; + protected transient TreeSet minutes; + protected transient TreeSet hours; + protected transient TreeSet daysOfMonth; + protected transient TreeSet months; + protected transient TreeSet daysOfWeek; + protected transient TreeSet years; + + protected transient boolean lastdayOfWeek = false; + protected transient int nthdayOfWeek = 0; + protected transient boolean lastdayOfMonth = false; + protected transient boolean nearestWeekday = false; + protected transient boolean calendardayOfWeek = false; + protected transient boolean calendardayOfMonth = false; + protected transient boolean expressionParsed = false; + + /** + * Constructs a new CronExpression based on the specified + * parameter. + * + * @param cronExpression String representation of the cron expression the + * new object should represent + * @throws java.text.ParseException + * if the string expression cannot be parsed into a valid + * CronExpression + */ + public CronExpression(String cronExpression) throws ParseException { + if (cronExpression == null) { + throw new IllegalArgumentException("cronExpression cannot be null"); + } + + this.cronExpression = cronExpression; + + buildExpression(cronExpression.toUpperCase(Locale.US)); + } + + /** + * Indicates whether the given date satisfies the cron expression. Note that + * milliseconds are ignored, so two Dates falling on different milliseconds + * of the same second will always have the same result here. + * + * @param date the date to evaluate + * @return a boolean indicating whether the given date satisfies the cron + * expression + */ + public boolean isSatisfiedBy(Date date) { + Calendar testDateCal = Calendar.getInstance(); + testDateCal.setTime(date); + testDateCal.set(Calendar.MILLISECOND, 0); + Date originalDate = testDateCal.getTime(); + + testDateCal.add(Calendar.SECOND, -1); + + if (getTimeAfter(testDateCal.getTime()).equals(originalDate)) { + return true; + } else { + return false; + } + } + + /** + * Returns the next date/time after the given date/time which + * satisfies the cron expression. + * + * @param date the date/time at which to begin the search for the next valid + * date/time + * @return the next valid date/time + */ + public Date getNextValidTimeAfter(Date date) { + return getTimeAfter(date); + } + + /** + *

+ * Returns the time zone for which the cronExpression of + * this CronTrigger will be resolved. + *

+ */ + public TimeZone getTimeZone() { + if (timeZone == null) timeZone = TimeZone.getDefault(); + + return timeZone; + } + + /** + *

+ * Sets the time zone for which the cronExpression of this + * CronTrigger will be resolved. + *

+ */ + public void setTimeZone(TimeZone timeZone) { + this.timeZone = timeZone; + } + + /** + * Returns the string representation of the CronExpression + * + * @return a string representation of the CronExpression + */ + public String toString() { + return cronExpression; + } + + /** + * Indicates whether the specified cron expression can be parsed into a + * valid cron expression + * + * @param cronExpression the expression to evaluate + * @return a boolean indicating whether the given expression is a valid cron + * expression + */ + public static boolean isValidExpression(String cronExpression) { + + try { + new CronExpression(cronExpression); + } catch (ParseException pe) { + return false; + } + + return true; + } + + //////////////////////////////////////////////////////////////////////////// + // + // Expression Parsing Functions + // + //////////////////////////////////////////////////////////////////////////// + + protected void buildExpression(String expression) throws ParseException { + expressionParsed = true; + + try { + + if (seconds == null) seconds = new TreeSet(); + if (minutes == null) minutes = new TreeSet(); + if (hours == null) hours = new TreeSet(); + if (daysOfMonth == null) daysOfMonth = new TreeSet(); + if (months == null) months = new TreeSet(); + if (daysOfWeek == null) daysOfWeek = new TreeSet(); + if (years == null) years = new TreeSet(); + + int exprOn = SECOND; + + StringTokenizer exprsTok = new StringTokenizer(expression, " \t", + false); + + while (exprsTok.hasMoreTokens() && exprOn <= YEAR) { + String expr = exprsTok.nextToken().trim(); + StringTokenizer vTok = new StringTokenizer(expr, ","); + while (vTok.hasMoreTokens()) { + String v = vTok.nextToken(); + storeExpressionVals(0, v, exprOn); + } + + exprOn++; + } + + if (exprOn <= DAY_OF_WEEK) + throw new ParseException("Unexpected end of expression.", + expression.length()); + + if (exprOn <= YEAR) storeExpressionVals(0, "*", YEAR); + + } catch (ParseException pe) { + throw pe; + } catch (Exception e) { + throw new ParseException("Illegal cron expression format (" + + e.toString() + ")", 0); + } + } + + protected int storeExpressionVals(int pos, String s, int type) + throws ParseException { + int incr = 0; + int i = skipWhiteSpace(pos, s); + if (i >= s.length()) return i; + char c = s.charAt(i); + if ((c >= 'A') && (c <= 'Z') && (!s.equals("L")) && (!s.equals("LW"))) { + String sub = s.substring(i, i + 3); + int sval = -1; + int eval = -1; + if (type == MONTH) { + sval = getMonthNumber(sub) + 1; + if (sval < 0) + throw new ParseException("Invalid Month value: '" + sub + + "'", i); + if (s.length() > i + 3) { + c = s.charAt(i + 3); + if (c == '-') { + i += 4; + sub = s.substring(i, i + 3); + eval = getMonthNumber(sub) + 1; + if (eval < 0) + throw new ParseException( + "Invalid Month value: '" + sub + "'", i); + } + } + } else if (type == DAY_OF_WEEK) { + sval = getDayOfWeekNumber(sub); + if (sval < 0) + throw new ParseException("Invalid Day-of-Week value: '" + + sub + "'", i); + if (s.length() > i + 3) { + c = s.charAt(i + 3); + if (c == '-') { + i += 4; + sub = s.substring(i, i + 3); + eval = getDayOfWeekNumber(sub); + if (eval < 0) + throw new ParseException( + "Invalid Day-of-Week value: '" + sub + + "'", i); + if (sval > eval) + throw new ParseException( + "Invalid Day-of-Week sequence: " + sval + + " > " + eval, i); + + } else if (c == '#') { + try { + i += 4; + nthdayOfWeek = Integer.parseInt(s.substring(i)); + if (nthdayOfWeek < 1 || nthdayOfWeek > 5) + throw new Exception(); + } catch (Exception e) { + throw new ParseException( + "A numeric value between 1 and 5 must follow the '#' option", + i); + } + } else if (c == 'L') { + lastdayOfWeek = true; + i++; + } + } + + } else { + throw new ParseException( + "Illegal characters for this position: '" + sub + "'", + i); + } + if (eval != -1) incr = 1; + addToSet(sval, eval, incr, type); + return (i + 3); + } + + if (c == '?') { + i++; + if ((i + 1) < s.length() + && (s.charAt(i) != ' ' && s.charAt(i + 1) != '\t')) + throw new ParseException("Illegal character after '?': " + + s.charAt(i), i); + if (type != DAY_OF_WEEK && type != DAY_OF_MONTH) + throw new ParseException( + "'?' can only be specfied for Day-of-Month or Day-of-Week.", + i); + if (type == DAY_OF_WEEK && !lastdayOfMonth) { + int val = ((Integer) daysOfMonth.last()).intValue(); + if (val == NO_SPEC_INT) + throw new ParseException( + "'?' can only be specfied for Day-of-Month -OR- Day-of-Week.", + i); + } + + addToSet(NO_SPEC_INT, -1, 0, type); + return i; + } + + if (c == '*' || c == '/') { + if (c == '*' && (i + 1) >= s.length()) { + addToSet(ALL_SPEC_INT, -1, incr, type); + return i + 1; + } else if (c == '/' + && ((i + 1) >= s.length() || s.charAt(i + 1) == ' ' || s + .charAt(i + 1) == '\t')) throw new ParseException( + "'/' must be followed by an integer.", i); + else if (c == '*') i++; + c = s.charAt(i); + if (c == '/') { // is an increment specified? + i++; + if (i >= s.length()) + throw new ParseException("Unexpected end of string.", i); + + incr = getNumericValue(s, i); + + i++; + if (incr > 10) i++; + if (incr > 59 && (type == SECOND || type == MINUTE)) throw new ParseException( + "Increment > 60 : " + incr, i); + else if (incr > 23 && (type == HOUR)) throw new ParseException( + "Increment > 24 : " + incr, i); + else if (incr > 31 && (type == DAY_OF_MONTH)) throw new ParseException( + "Increment > 31 : " + incr, i); + else if (incr > 7 && (type == DAY_OF_WEEK)) throw new ParseException( + "Increment > 7 : " + incr, i); + else if (incr > 12 && (type == MONTH)) + throw new ParseException("Increment > 12 : " + incr, i); + } else + incr = 1; + + addToSet(ALL_SPEC_INT, -1, incr, type); + return i; + } else if (c == 'L') { + i++; + if (type == DAY_OF_MONTH) lastdayOfMonth = true; + if (type == DAY_OF_WEEK) addToSet(7, 7, 0, type); + if(type == DAY_OF_MONTH && s.length() > i) { + c = s.charAt(i); + if(c == 'W') { + nearestWeekday = true; + i++; + } + } + return i; + } else if (c >= '0' && c <= '9') { + int val = Integer.parseInt(String.valueOf(c)); + i++; + if (i >= s.length()) addToSet(val, -1, -1, type); + else { + c = s.charAt(i); + if (c >= '0' && c <= '9') { + ValueSet vs = getValue(val, s, i); + val = vs.value; + i = vs.pos; + } + i = checkNext(i, s, val, type); + return i; + } + } else + throw new ParseException("Unexpected character: " + c, i); + + return i; + } + + protected int checkNext(int pos, String s, int val, int type) + throws ParseException { + int end = -1; + int i = pos; + + if (i >= s.length()) { + addToSet(val, end, -1, type); + return i; + } + + char c = s.charAt(pos); + + if (c == 'L') { + if (type == DAY_OF_WEEK) lastdayOfWeek = true; + else + throw new ParseException("'L' option is not valid here. (pos=" + + i + ")", i); + TreeSet set = getSet(type); + set.add(new Integer(val)); + i++; + return i; + } + + if (c == 'W') { + if(type == DAY_OF_MONTH) nearestWeekday = true; + else + throw new ParseException("'W' option is not valid here. (pos=" + + i + ")", i); + TreeSet set = getSet(type); + set.add(new Integer(val)); + i++; + return i; + } + + if (c == '#') { + if (type != DAY_OF_WEEK) + throw new ParseException( + "'#' option is not valid here. (pos=" + i + ")", i); + i++; + try { + nthdayOfWeek = Integer.parseInt(s.substring(i)); + if (nthdayOfWeek < 1 || nthdayOfWeek > 5) + throw new Exception(); + } catch (Exception e) { + throw new ParseException( + "A numeric value between 1 and 5 must follow the '#' option", + i); + } + + TreeSet set = getSet(type); + set.add(new Integer(val)); + i++; + return i; + } + + if (c == 'C') { + if (type == DAY_OF_WEEK) calendardayOfWeek = true; + else if (type == DAY_OF_MONTH) calendardayOfMonth = true; + else + throw new ParseException("'C' option is not valid here. (pos=" + + i + ")", i); + TreeSet set = getSet(type); + set.add(new Integer(val)); + i++; + return i; + } + + if (c == '-') { + i++; + c = s.charAt(i); + int v = Integer.parseInt(String.valueOf(c)); + end = v; + i++; + if (i >= s.length()) { + addToSet(val, end, 1, type); + return i; + } + c = s.charAt(i); + if (c >= '0' && c <= '9') { + ValueSet vs = getValue(v, s, i); + int v1 = vs.value; + end = v1; + i = vs.pos; + } + if (i < s.length() && ((c = s.charAt(i)) == '/')) { + i++; + c = s.charAt(i); + int v2 = Integer.parseInt(String.valueOf(c)); + i++; + if (i >= s.length()) { + addToSet(val, end, v2, type); + return i; + } + c = s.charAt(i); + if (c >= '0' && c <= '9') { + ValueSet vs = getValue(v2, s, i); + int v3 = vs.value; + addToSet(val, end, v3, type); + i = vs.pos; + return i; + } else { + addToSet(val, end, v2, type); + return i; + } + } else { + addToSet(val, end, 1, type); + return i; + } + } + + if (c == '/') { + i++; + c = s.charAt(i); + int v2 = Integer.parseInt(String.valueOf(c)); + i++; + if (i >= s.length()) { + addToSet(val, end, v2, type); + return i; + } + c = s.charAt(i); + if (c >= '0' && c <= '9') { + ValueSet vs = getValue(v2, s, i); + int v3 = vs.value; + addToSet(val, end, v3, type); + i = vs.pos; + return i; + } else + throw new ParseException("Unexpected character '" + c + + "' after '/'", i); + } + + addToSet(val, end, 0, type); + i++; + return i; + } + + public String getCronExpression() { + return cronExpression; + } + + public String getExpressionSummary() { + StringBuffer buf = new StringBuffer(); + + buf.append("seconds: "); + buf.append(getExpressionSetSummary(seconds)); + buf.append("\n"); + buf.append("minutes: "); + buf.append(getExpressionSetSummary(minutes)); + buf.append("\n"); + buf.append("hours: "); + buf.append(getExpressionSetSummary(hours)); + buf.append("\n"); + buf.append("daysOfMonth: "); + buf.append(getExpressionSetSummary(daysOfMonth)); + buf.append("\n"); + buf.append("months: "); + buf.append(getExpressionSetSummary(months)); + buf.append("\n"); + buf.append("daysOfWeek: "); + buf.append(getExpressionSetSummary(daysOfWeek)); + buf.append("\n"); + buf.append("lastdayOfWeek: "); + buf.append(lastdayOfWeek); + buf.append("\n"); + buf.append("nearestWeekday: "); + buf.append(nearestWeekday); + buf.append("\n"); + buf.append("NthDayOfWeek: "); + buf.append(nthdayOfWeek); + buf.append("\n"); + buf.append("lastdayOfMonth: "); + buf.append(lastdayOfMonth); + buf.append("\n"); + buf.append("calendardayOfWeek: "); + buf.append(calendardayOfWeek); + buf.append("\n"); + buf.append("calendardayOfMonth: "); + buf.append(calendardayOfMonth); + buf.append("\n"); + buf.append("years: "); + buf.append(getExpressionSetSummary(years)); + buf.append("\n"); + + return buf.toString(); + } + + protected String getExpressionSetSummary(java.util.Set set) { + + if (set.contains(NO_SPEC)) return "?"; + if (set.contains(ALL_SPEC)) return "*"; + + StringBuffer buf = new StringBuffer(); + + Iterator itr = set.iterator(); + boolean first = true; + while (itr.hasNext()) { + Integer iVal = (Integer) itr.next(); + String val = iVal.toString(); + if (!first) buf.append(","); + buf.append(val); + first = false; + } + + return buf.toString(); + } + + protected String getExpressionSetSummary(java.util.ArrayList list) { + + if (list.contains(NO_SPEC)) return "?"; + if (list.contains(ALL_SPEC)) return "*"; + + StringBuffer buf = new StringBuffer(); + + Iterator itr = list.iterator(); + boolean first = true; + while (itr.hasNext()) { + Integer iVal = (Integer) itr.next(); + String val = iVal.toString(); + if (!first) buf.append(","); + buf.append(val); + first = false; + } + + return buf.toString(); + } + + protected int skipWhiteSpace(int i, String s) { + for (; i < s.length() && (s.charAt(i) == ' ' || s.charAt(i) == '\t'); i++) + ; + + return i; + } + + protected int findNextWhiteSpace(int i, String s) { + for (; i < s.length() && (s.charAt(i) != ' ' || s.charAt(i) != '\t'); i++) + ; + + return i; + } + + protected void addToSet(int val, int end, int incr, int type) + throws ParseException { + TreeSet set = getSet(type); + + if (type == SECOND || type == MINUTE) { + if ((val < 0 || val > 59 || end > 59) && (val != ALL_SPEC_INT)) + throw new ParseException( + "Minute and Second values must be between 0 and 59", + -1); + } else if (type == HOUR) { + if ((val < 0 || val > 23 || end > 23) && (val != ALL_SPEC_INT)) + throw new ParseException( + "Hour values must be between 0 and 23", -1); + } else if (type == DAY_OF_MONTH) { + if ((val < 1 || val > 31 || end > 31) && (val != ALL_SPEC_INT) + && (val != NO_SPEC_INT)) + throw new ParseException( + "Day of month values must be between 1 and 31", -1); + } else if (type == MONTH) { + if ((val < 1 || val > 12 || end > 12) && (val != ALL_SPEC_INT)) + throw new ParseException( + "Month values must be between 1 and 12", -1); + } else if (type == DAY_OF_WEEK) { + if ((val == 0 || val > 7 || end > 7) && (val != ALL_SPEC_INT) + && (val != NO_SPEC_INT)) + throw new ParseException( + "Day-of-Week values must be between 1 and 7", -1); + } + + if ((incr == 0 || incr == -1) && val != ALL_SPEC_INT) { + if (val != -1) set.add(new Integer(val)); + else + set.add(NO_SPEC); + return; + } + + int startAt = val; + int stopAt = end; + + if (val == ALL_SPEC_INT && incr <= 0) { + incr = 1; + set.add(ALL_SPEC); // put in a marker, but also fill values + } + + if (type == SECOND || type == MINUTE) { + if (stopAt == -1) stopAt = 59; + if (startAt == -1 || startAt == ALL_SPEC_INT) startAt = 0; + } else if (type == HOUR) { + if (stopAt == -1) stopAt = 23; + if (startAt == -1 || startAt == ALL_SPEC_INT) startAt = 0; + } else if (type == DAY_OF_MONTH) { + if (stopAt == -1) stopAt = 31; + if (startAt == -1 || startAt == ALL_SPEC_INT) startAt = 1; + } else if (type == MONTH) { + if (stopAt == -1) stopAt = 12; + if (startAt == -1 || startAt == ALL_SPEC_INT) startAt = 1; + } else if (type == DAY_OF_WEEK) { + if (stopAt == -1) stopAt = 7; + if (startAt == -1 || startAt == ALL_SPEC_INT) startAt = 1; + } else if (type == YEAR) { + if (stopAt == -1) stopAt = 2099; + if (startAt == -1 || startAt == ALL_SPEC_INT) startAt = 1970; + } + + for (int i = startAt; i <= stopAt; i += incr) + set.add(new Integer(i)); + } + + protected TreeSet getSet(int type) { + switch (type) { + case SECOND: + return seconds; + case MINUTE: + return minutes; + case HOUR: + return hours; + case DAY_OF_MONTH: + return daysOfMonth; + case MONTH: + return months; + case DAY_OF_WEEK: + return daysOfWeek; + case YEAR: + return years; + default: + return null; + } + } + + protected ValueSet getValue(int v, String s, int i) { + char c = s.charAt(i); + String s1 = String.valueOf(v); + while (c >= '0' && c <= '9') { + s1 += c; + i++; + if (i >= s.length()) break; + c = s.charAt(i); + } + ValueSet val = new ValueSet(); + if (i < s.length()) val.pos = i; + else + val.pos = i + 1; + val.value = Integer.parseInt(s1); + return val; + } + + protected int getNumericValue(String s, int i) { + int endOfVal = findNextWhiteSpace(i, s); + String val = s.substring(i, endOfVal); + return Integer.parseInt(val); + } + + protected int getMonthNumber(String s) { + Integer integer = (Integer) monthMap.get(s); + + if (integer == null) return -1; + + return integer.intValue(); + } + + protected int getDayOfWeekNumber(String s) { + Integer integer = (Integer) dayMap.get(s); + + if (integer == null) return -1; + + return integer.intValue(); + } + + protected Date getTime(int sc, int mn, int hr, int dayofmn, int mon) { + try { + Calendar cl = Calendar.getInstance(getTimeZone()); + //cl.add(Calendar.DAY_OF_MONTH,); + if (hr >= 0 && hr <= 12) cl.set(Calendar.AM_PM, Calendar.AM); + if (hr >= 13 && hr <= 23) cl.set(Calendar.AM_PM, Calendar.PM); + cl.setLenient(false); + if (sc != -1) cl.set(Calendar.SECOND, sc); + if (mn != -1) cl.set(Calendar.MINUTE, mn); + if (hr != -1) cl.set(Calendar.HOUR_OF_DAY, hr); + if (dayofmn != -1) cl.set(Calendar.DAY_OF_MONTH, dayofmn); + if (mon != -1) cl.set(Calendar.MONTH, mon); + return cl.getTime(); + } catch (Exception e) { + return null; + } + } + + //////////////////////////////////////////////////////////////////////////// + // + // Computation Functions + // + //////////////////////////////////////////////////////////////////////////// + + protected Date getTimeAfter(Date afterTime) { + + Calendar cl = Calendar.getInstance(getTimeZone()); + + // move ahead one second, since we're computing the time *after* the + // given time + afterTime = new Date(afterTime.getTime() + 1000); + // CronTrigger does not deal with milliseconds + cl.setTime(afterTime); + cl.set(Calendar.MILLISECOND, 0); + + boolean gotOne = false; + // loop until we've computed the next time, or we've past the endTime + while (!gotOne) { + + //if (endTime != null && cl.getTime().after(endTime)) return null; + + SortedSet st = null; + int t = 0; + + int sec = cl.get(Calendar.SECOND); + int min = cl.get(Calendar.MINUTE); + + // get second................................................. + st = seconds.tailSet(new Integer(sec)); + if (st != null && st.size() != 0) { + sec = ((Integer) st.first()).intValue(); + } else { + sec = ((Integer) seconds.first()).intValue(); + min++; + cl.set(Calendar.MINUTE, min); + } + cl.set(Calendar.SECOND, sec); + + min = cl.get(Calendar.MINUTE); + int hr = cl.get(Calendar.HOUR_OF_DAY); + t = -1; + + // get minute................................................. + st = minutes.tailSet(new Integer(min)); + if (st != null && st.size() != 0) { + t = min; + min = ((Integer) st.first()).intValue(); + } else { + min = ((Integer) minutes.first()).intValue(); + hr++; + } + if (min != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, min); + setCalendarHour(cl, hr); + continue; + } + cl.set(Calendar.MINUTE, min); + + hr = cl.get(Calendar.HOUR_OF_DAY); + int day = cl.get(Calendar.DAY_OF_MONTH); + t = -1; + + // get hour................................................... + st = hours.tailSet(new Integer(hr)); + if (st != null && st.size() != 0) { + t = hr; + hr = ((Integer) st.first()).intValue(); + } else { + hr = ((Integer) hours.first()).intValue(); + day++; + } + if (hr != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.DAY_OF_MONTH, day); + setCalendarHour(cl, hr); + continue; + } + cl.set(Calendar.HOUR_OF_DAY, hr); + + day = cl.get(Calendar.DAY_OF_MONTH); + int mon = cl.get(Calendar.MONTH) + 1; + // '+ 1' because calendar is 0-based for this field, and we are + // 1-based + t = -1; + int tmon = mon; + + // get day................................................... + boolean dayOfMSpec = !daysOfMonth.contains(NO_SPEC); + boolean dayOfWSpec = !daysOfWeek.contains(NO_SPEC); + if (dayOfMSpec && !dayOfWSpec) { // get day by day of month rule + st = daysOfMonth.tailSet(new Integer(day)); + if (lastdayOfMonth) { + if(!nearestWeekday) { + t = day; + day = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); + } + else { + t = day; + day = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); + + java.util.Calendar tcal = java.util.Calendar.getInstance(); + tcal.set(Calendar.SECOND, 0); + tcal.set(Calendar.MINUTE, 0); + tcal.set(Calendar.HOUR_OF_DAY, 0); + tcal.set(Calendar.DAY_OF_MONTH, day); + tcal.set(Calendar.MONTH, mon - 1); + tcal.set(Calendar.YEAR, cl.get(Calendar.YEAR)); + + int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); + int dow = tcal.get(Calendar.DAY_OF_WEEK); + + if(dow == Calendar.SATURDAY && day == 1) + day += 2; + else if(dow == Calendar.SATURDAY) + day -= 1; + else if(dow == Calendar.SUNDAY && day == ldom) + day -= 2; + else if(dow == Calendar.SUNDAY) + day += 1; + + tcal.set(Calendar.SECOND, sec); + tcal.set(Calendar.MINUTE, min); + tcal.set(Calendar.HOUR_OF_DAY, hr); + tcal.set(Calendar.DAY_OF_MONTH, day); + tcal.set(Calendar.MONTH, mon - 1); + Date nTime = tcal.getTime(); + if(nTime.before(afterTime)) { + day = 1; + mon++; + } + } + } else if(nearestWeekday) { + t = day; + day = ((Integer) daysOfMonth.first()).intValue(); + + java.util.Calendar tcal = java.util.Calendar.getInstance(); + tcal.set(Calendar.SECOND, 0); + tcal.set(Calendar.MINUTE, 0); + tcal.set(Calendar.HOUR_OF_DAY, 0); + tcal.set(Calendar.DAY_OF_MONTH, day); + tcal.set(Calendar.MONTH, mon - 1); + tcal.set(Calendar.YEAR, cl.get(Calendar.YEAR)); + + int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); + int dow = tcal.get(Calendar.DAY_OF_WEEK); + + if(dow == Calendar.SATURDAY && day == 1) + day += 2; + else if(dow == Calendar.SATURDAY) + day -= 1; + else if(dow == Calendar.SUNDAY && day == ldom) + day -= 2; + else if(dow == Calendar.SUNDAY) + day += 1; + + + tcal.set(Calendar.SECOND, sec); + tcal.set(Calendar.MINUTE, min); + tcal.set(Calendar.HOUR_OF_DAY, hr); + tcal.set(Calendar.DAY_OF_MONTH, day); + tcal.set(Calendar.MONTH, mon - 1); + Date nTime = tcal.getTime(); + if(nTime.before(afterTime)) { + day = ((Integer) daysOfMonth.first()).intValue();; + mon++; + } + } + else if (st != null && st.size() != 0) { + t = day; + day = ((Integer) st.first()).intValue(); + } else { + day = ((Integer) daysOfMonth.first()).intValue(); + mon++; + } + + if (day != t || mon != tmon) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, day); + cl.set(Calendar.MONTH, mon - 1); + // '- 1' because calendar is 0-based for this field, and we + // are 1-based + continue; + } + } else if (dayOfWSpec && !dayOfMSpec) { // get day by day of week rule + if (lastdayOfWeek) { // are we looking for the last XXX day of + // the month? + int dow = ((Integer) daysOfWeek.first()).intValue(); // desired + // d-o-w + int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w + int daysToAdd = 0; + if (cDow < dow) daysToAdd = dow - cDow; + if (cDow > dow) daysToAdd = dow + (7 - cDow); + + int lDay = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); + + if (day + daysToAdd > lDay) { // did we already miss the + // last one? + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon); + // no '- 1' here because we are promoting the month + continue; + } + + // find date of last occurance of this day in this month... + while ((day + daysToAdd + 7) <= lDay) + daysToAdd += 7; + + day += daysToAdd; + + if (daysToAdd > 0) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, day); + cl.set(Calendar.MONTH, mon - 1); + // '- 1' here because we are not promoting the month + continue; + } + + } else if (nthdayOfWeek != 0) { + // are we looking for the Nth XXX day in the month? + int dow = ((Integer) daysOfWeek.first()).intValue(); // desired + // d-o-w + int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w + int daysToAdd = 0; + if (cDow < dow) daysToAdd = dow - cDow; + else if (cDow > dow) daysToAdd = dow + (7 - cDow); + + boolean dayShifted = false; + if (daysToAdd > 0) dayShifted = true; + + day += daysToAdd; + int weekOfMonth = day / 7; + if (day % 7 > 0) weekOfMonth++; + + daysToAdd = (nthdayOfWeek - weekOfMonth) * 7; + day += daysToAdd; + if (daysToAdd < 0 + || day > getLastDayOfMonth(mon, cl + .get(Calendar.YEAR))) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon); + // no '- 1' here because we are promoting the month + continue; + } else if (daysToAdd > 0 || dayShifted) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, day); + cl.set(Calendar.MONTH, mon - 1); + // '- 1' here because we are NOT promoting the month + continue; + } + } else { + int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w + int dow = ((Integer) daysOfWeek.first()).intValue(); // desired + // d-o-w + st = daysOfWeek.tailSet(new Integer(cDow)); + if (st != null && st.size() > 0) { + dow = ((Integer) st.first()).intValue(); + } + + int daysToAdd = 0; + if (cDow < dow) daysToAdd = dow - cDow; + if (cDow > dow) daysToAdd = dow + (7 - cDow); + + int lDay = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); + + if (day + daysToAdd > lDay) { // will we pass the end of + // the month? + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon); + // no '- 1' here because we are promoting the month + continue; + } else if (daysToAdd > 0) { // are we swithing days? + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, day + daysToAdd); + cl.set(Calendar.MONTH, mon - 1); + // '- 1' because calendar is 0-based for this field, + // and we are 1-based + continue; + } + } + } else { // dayOfWSpec && !dayOfMSpec + throw new UnsupportedOperationException( + "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented."); + // TODO: + } + cl.set(Calendar.DAY_OF_MONTH, day); + + mon = cl.get(Calendar.MONTH) + 1; + // '+ 1' because calendar is 0-based for this field, and we are + // 1-based + int year = cl.get(Calendar.YEAR); + t = -1; + + // test for expressions that never generate a valid fire date, + // but keep looping... + if (year > 2099) return null; + + // get month................................................... + st = months.tailSet(new Integer(mon)); + if (st != null && st.size() != 0) { + t = mon; + mon = ((Integer) st.first()).intValue(); + } else { + mon = ((Integer) months.first()).intValue(); + year++; + } + if (mon != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon - 1); + // '- 1' because calendar is 0-based for this field, and we are + // 1-based + cl.set(Calendar.YEAR, year); + continue; + } + cl.set(Calendar.MONTH, mon - 1); + // '- 1' because calendar is 0-based for this field, and we are + // 1-based + + year = cl.get(Calendar.YEAR); + t = -1; + + // get year................................................... + st = years.tailSet(new Integer(year)); + if (st != null && st.size() != 0) { + t = year; + year = ((Integer) st.first()).intValue(); + } else + return null; // ran out of years... + + if (year != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, 0); + // '- 1' because calendar is 0-based for this field, and we are + // 1-based + cl.set(Calendar.YEAR, year); + continue; + } + cl.set(Calendar.YEAR, year); + + gotOne = true; + } // while( !done ) + + return cl.getTime(); + } + + /** + * Advance the calendar to the particular hour paying particular attention + * to daylight saving problems. + * + * @param cal + * @param hour + */ + protected void setCalendarHour(Calendar cal, int hour) { + cal.set(java.util.Calendar.HOUR_OF_DAY, hour); + if (cal.get(java.util.Calendar.HOUR_OF_DAY) != hour && hour != 24) { + cal.set(java.util.Calendar.HOUR_OF_DAY, hour + 1); + } + } + + protected Date getTimeBefore(Date endTime) // TODO: implement + { + return null; + } + + protected boolean isLeapYear(int year) { + if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) return true; + else + return false; + } + + protected int getLastDayOfMonth(int monthNum, int year) { + + switch (monthNum) { + case 1: + return 31; + case 2: + return (isLeapYear(year)) ? 29 : 28; + case 3: + return 31; + case 4: + return 30; + case 5: + return 31; + case 6: + return 30; + case 7: + return 31; + case 8: + return 31; + case 9: + return 30; + case 10: + return 31; + case 11: + return 30; + case 12: + return 31; + default: + throw new IllegalArgumentException("Illegal month number: " + + monthNum); + } + } + + + private void readObject(java.io.ObjectInputStream stream) + throws java.io.IOException, ClassNotFoundException { + stream.defaultReadObject(); + try { + buildExpression(cronExpression); + } catch (Exception ignore) { + } // never happens + } + + public Object clone() { + CronExpression copy = null; + try { + copy = new CronExpression(getCronExpression()); + copy.setTimeZone(getTimeZone()); + } catch (ParseException ex) { // never happens since the source is valid... + throw new IncompatibleClassChangeError("Not Cloneable."); + } + return copy; + } +} + +class ValueSet { + public int value; + + public int pos; +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/CronTrigger.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/CronTrigger.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/CronTrigger.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,969 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import java.text.ParseException; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + + +/** + *

+ * A concrete {@link Trigger} that is used to fire a {@link org.quartz.JobDetail} + * at given moments in time, defined with Unix 'cron-like' definitions. + *

+ * + *

+ * For those unfamiliar with "cron", this means being able to create a firing + * schedule such as: "At 8:00am every Monday through Friday" or "At 1:30am + * every last Friday of the month". + *

+ * + *

+ * The format of a "Cron-Expression" string is documented on the + * {@link org.quartz.CronExpression} class. + *

+ * + *

+ * Here are some full examples:
+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Expression Meaning
"0 0 12 * * ?"  + * Fire at 12pm (noon) every day
"0 15 10 ? * *"  + * Fire at 10:15am every day
"0 15 10 * * ?"  + * Fire at 10:15am every day
"0 15 10 * * ? *"  + * Fire at 10:15am every day
"0 15 10 * * ? 2005"  + * Fire at 10:15am every day during the year 2005 + *
"0 * 14 * * ?"  + * Fire every minute starting at 2pm and ending at 2:59pm, every day + *
"0 0/5 14 * * ?"  + * Fire every 5 minutes starting at 2pm and ending at 2:55pm, every day + *
"0 0/5 14,18 * * ?"  + * Fire every 5 minutes starting at 2pm and ending at 2:55pm, AND fire every 5 minutes starting at 6pm and ending at 6:55pm, every day + *
"0 0-5 14 * * ?"  + * Fire every minute starting at 2pm and ending at 2:05pm, every day + *
"0 10,44 14 ? 3 WED"  + * Fire at 2:10pm and at 2:44pm every Wednesday in the month of March. + *
"0 15 10 ? * MON-FRI"  + * Fire at 10:15am every Monday, Tuesday, Wednesday, Thursday and Friday + *
"0 15 10 15 * ?"  + * Fire at 10:15am on the 15th day of every month + *
"0 15 10 L * ?"  + * Fire at 10:15am on the last day of every month + *
"0 15 10 ? * 6L"  + * Fire at 10:15am on the last Friday of every month + *
"0 15 10 ? * 6L"  + * Fire at 10:15am on the last Friday of every month + *
"0 15 10 ? * 6L 2002-2005"  + * Fire at 10:15am on every last friday of every month during the years 2002, 2003, 2004 and 2005 + *
"0 15 10 ? * 6#3"  + * Fire at 10:15am on the third Friday of every month + *
+ *

+ * + *

+ * Pay attention to the effects of '?' and '*' in the day-of-week and + * day-of-month fields! + *

+ * + *

+ * NOTES: + *

    + *
  • Support for specifying both a day-of-week and a day-of-month value is + * not complete (you'll need to use the '?' character in on of these fields). + *
  • + *
  • Be careful when setting fire times between mid-night and 1:00 AM - + * "daylight savings" can cause a skip or a repeat depending on whether the + * time moves back or jumps forward.
  • + *
+ *

+ * + * @see Trigger + * @see SimpleTrigger + * @see TriggerUtils + * + * @author Sharada Jambula, James House + * @author Contributions from Mads Henderson + */ +public class CronTrigger extends Trigger { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Instructs the {@link Scheduler} that upon a mis-fire + * situation, the {@link CronTrigger} wants to be fired now + * by Scheduler. + *

+ */ + public static final int MISFIRE_INSTRUCTION_FIRE_ONCE_NOW = 1; + + /** + *

+ * Instructs the {@link Scheduler} that upon a mis-fire + * situation, the {@link CronTrigger} wants to have it's + * next-fire-time updated to the next time in the schedule after the + * current time (taking into account any associated {@link Calendar}, + * but it does not want to be fired now. + *

+ */ + public static final int MISFIRE_INSTRUCTION_DO_NOTHING = 2; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private CronExpression cronEx = null; + private Date startTime = null; + private Date endTime = null; + private Date nextFireTime = null; + private Date previousFireTime = null; + private transient TimeZone timeZone = null; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a CronTrigger with no settings. + *

+ * + *

+ * The start-time will also be set to the current time, and the time zone + * will be set the the system's default time zone. + *

+ */ + public CronTrigger() { + super(); + setStartTime(new Date()); + setTimeZone(TimeZone.getDefault()); + } + + /** + *

+ * Create a CronTrigger with the given name and group. + *

+ * + *

+ * The start-time will also be set to the current time, and the time zone + * will be set the the system's default time zone. + *

+ */ + public CronTrigger(String name, String group) { + super(name, group); + setStartTime(new Date()); + setTimeZone(TimeZone.getDefault()); + } + + /** + *

+ * Create a CronTrigger with the given name, group and + * expression. + *

+ * + *

+ * The start-time will also be set to the current time, and the time zone + * will be set the the system's default time zone. + *

+ */ + public CronTrigger(String name, String group, String cronExpression) + throws ParseException { + super(name, group); + + setCronExpression(cronExpression); + + setStartTime(new Date()); + setTimeZone(TimeZone.getDefault()); + } + + /** + *

+ * Create a CronTrigger with the given name and group, and + * associated with the identified {@link org.quartz.JobDetail}. + *

+ * + *

+ * The start-time will also be set to the current time, and the time zone + * will be set the the system's default time zone. + *

+ */ + public CronTrigger(String name, String group, String jobName, + String jobGroup) { + super(name, group, jobName, jobGroup); + setStartTime(new Date()); + setTimeZone(TimeZone.getDefault()); + } + + /** + *

+ * Create a CronTrigger with the given name and group, + * associated with the identified {@link org.quartz.JobDetail}, + * and with the given "cron" expression. + *

+ * + *

+ * The start-time will also be set to the current time, and the time zone + * will be set the the system's default time zone. + *

+ */ + public CronTrigger(String name, String group, String jobName, + String jobGroup, String cronExpression) throws ParseException { + this(name, group, jobName, jobGroup, null, null, cronExpression, + TimeZone.getDefault()); + } + + /** + *

+ * Create a CronTrigger with the given name and group, + * associated with the identified {@link org.quartz.JobDetail}, + * and with the given "cron" expression resolved with respect to the TimeZone. + *

+ */ + public CronTrigger(String name, String group, String jobName, + String jobGroup, String cronExpression, TimeZone timeZone) + throws ParseException { + this(name, group, jobName, jobGroup, null, null, cronExpression, + timeZone); + } + + /** + *

+ * Create a CronTrigger that will occur at the given time, + * until the given end time. + *

+ * + *

+ * If null, the start-time will also be set to the current time, the time + * zone will be set the the system's default. + *

+ * + * @param startTime + * A Date set to the time for the Trigger + * to fire. + * @param endTime + * A Date set to the time for the Trigger + * to quit repeat firing. + */ + public CronTrigger(String name, String group, String jobName, + String jobGroup, Date startTime, Date endTime, String cronExpression) + throws ParseException { + super(name, group, jobName, jobGroup); + + setCronExpression(cronExpression); + + if (startTime == null) startTime = new Date(); + setStartTime(startTime); + if (endTime != null) setEndTime(endTime); + setTimeZone(TimeZone.getDefault()); + + } + + /** + *

+ * Create a CronTrigger with fire time dictated by the + * cronExpression resolved with respect to the specified + * timeZone occuring from the startTime until + * the given endTime. + *

+ * + *

+ * If null, the start-time will also be set to the current time. If null, + * the time zone will be set to the system's default. + *

+ * + * @param name + * of the Trigger + * @param group + * of the Trigger + * @param jobName, + * name of the {@link org.quartz.JobDetail} + * executed on firetime + * @param jobGroup, + * group of the {@link org.quartz.JobDetail} + * executed on firetime + * @param startTime + * A Date set to the earliest time for the Trigger + * to start firing. + * @param endTime + * A Date set to the time for the Trigger + * to quit repeat firing. + * @param cronExpression, + * A cron expression dictating the firing sequence of the Trigger + * @param timeZone, + * Specifies for which time zone the cronExpression + * should be interprted, i.e. the expression 0 0 10 * * ?, is + * resolved to 10:00 am in this time zone. + * @throws ParseException + * if the cronExpression is invalid. + */ + public CronTrigger(String name, String group, String jobName, + String jobGroup, Date startTime, Date endTime, + String cronExpression, TimeZone timeZone) throws ParseException { + super(name, group, jobName, jobGroup); + + setCronExpression(cronExpression); + + if (startTime == null) startTime = new Date(); + setStartTime(startTime); + if (endTime != null) setEndTime(endTime); + if (timeZone == null) { + setTimeZone(TimeZone.getDefault()); + } else { + setTimeZone(timeZone); + } + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public Object clone() { + CronTrigger copy = (CronTrigger) super.clone(); + copy.setCronExpression((CronExpression)cronEx.clone()); + return copy; + } + + public void setCronExpression(String cronExpression) throws ParseException { + this.cronEx = new CronExpression(cronExpression); + this.cronEx.setTimeZone(getTimeZone()); + } + + public String getCronExpression() { + return cronEx == null ? null : cronEx.getCronExpression(); + } + + public void setCronExpression(CronExpression cronExpression) { + this.cronEx = cronExpression; + this.timeZone = cronExpression.getTimeZone(); + } + + /** + *

+ * Get the time at which the CronTrigger should occur. + *

+ */ + public Date getStartTime() { + return this.startTime; + } + + public void setStartTime(Date startTime) { + if (startTime == null) + throw new IllegalArgumentException("Start time cannot be null"); + + Date eTime = getEndTime(); + if (eTime != null && startTime != null && eTime.before(startTime)) + throw new IllegalArgumentException( + "End time cannot be before start time"); + + // round off millisecond... + // Note timeZone is not needed here as parameter for + // Calendar.getInstance(), + // since time zone is implicit when using a Date in the setTime method. + Calendar cl = Calendar.getInstance(); + cl.setTime(startTime); + cl.set(Calendar.MILLISECOND, 0); + + this.startTime = cl.getTime(); + } + + /** + *

+ * Get the time at which the CronTrigger should quit + * repeating - even if repeastCount isn't yet satisfied. + *

+ * + * @see #getFinalFireTime() + */ + public Date getEndTime() { + return this.endTime; + } + + public void setEndTime(Date endTime) { + Date sTime = getStartTime(); + if (sTime != null && endTime != null && sTime.after(endTime)) + throw new IllegalArgumentException( + "End time cannot be before start time"); + + this.endTime = endTime; + } + + /** + *

+ * Returns the next time at which the CronTrigger will fire. + * If the trigger will not fire again, null will be + * returned. The value returned is not guaranteed to be valid until after + * the Trigger has been added to the scheduler. + *

+ */ + public Date getNextFireTime() { + return this.nextFireTime; + } + + /** + *

+ * Returns the previous time at which the CronTrigger will + * fire. If the trigger has not yet fired, null will be + * returned. + */ + public Date getPreviousFireTime() { + return this.previousFireTime; + } + + /** + *

+ * Sets the next time at which the CronTrigger will fire. + * This method should not be invoked by client code. + *

+ */ + public void setNextFireTime(Date nextFireTime) { + this.nextFireTime = nextFireTime; + } + + /** + *

+ * Set the previous time at which the SimpleTrigger fired. + *

+ * + *

+ * This method should not be invoked by client code. + *

+ */ + public void setPreviousFireTime(Date previousFireTime) { + this.previousFireTime = previousFireTime; + } + + /** + *

+ * Returns the time zone for which the cronExpression of + * this CronTrigger will be resolved. + *

+ */ + public TimeZone getTimeZone() { + + if(cronEx != null) return cronEx.getTimeZone(); + + if (timeZone == null) timeZone = TimeZone.getDefault(); + return timeZone; + } + + /** + *

+ * Sets the time zone for which the cronExpression of this + * CronTrigger will be resolved. + *

+ */ + public void setTimeZone(TimeZone timeZone) { + if(cronEx != null) cronEx.setTimeZone(timeZone); + this.timeZone = timeZone; + } + + /** + *

+ * Returns the next time at which the CronTrigger will fire, + * after the given time. If the trigger will not fire after the given time, + * null will be returned. + *

+ * + *

+ * Note that the date returned is NOT validated against the related + * org.quartz.Calendar (if any) + *

+ */ + public Date getFireTimeAfter(Date afterTime) { + if (afterTime == null) afterTime = new Date(); + + if (startTime.after(afterTime)) + afterTime = new Date(startTime.getTime() - 1000l); + + Date pot = getTimeAfter(afterTime); + if (endTime != null && pot != null && pot.after(endTime)) return null; + + return pot; + } + + /** + *

+ * Returns the final time at which the CronTrigger will + * fire. + *

+ * + *

+ * Note that the return time *may* be in the past. and the date returned is + * not validated against org.quartz.calendar + *

+ */ + public Date getFinalFireTime() { + if (this.endTime != null) return getTimeBefore(this.endTime); + else + return null; + } + + /** + *

+ * Determines whether or not the CronTrigger will occur + * again. + *

+ */ + public boolean mayFireAgain() { + return (getNextFireTime() != null); + } + + protected boolean validateMisfireInstruction(int misfireInstruction) { + if (misfireInstruction < MISFIRE_INSTRUCTION_SMART_POLICY) + return false; + + if (misfireInstruction > MISFIRE_INSTRUCTION_DO_NOTHING) return false; + + return true; + } + + /** + *

+ * Updates the CronTrigger's state based on the + * MISFIRE_INSTRUCTION_XXX that was selected when the SimpleTrigger + * was created. + *

+ * + *

+ * If the misfire instruction is set to MISFIRE_INSTRUCTION_SMART_POLICY, + * then the following scheme will be used:
+ *

    + *
  • The instruction will be interpreted as MISFIRE_INSTRUCTION_FIRE_ONCE_NOW + *
+ *

+ */ + public void updateAfterMisfire(org.quartz.Calendar cal) { + int instr = getMisfireInstruction(); + + if (instr == MISFIRE_INSTRUCTION_SMART_POLICY) + instr = MISFIRE_INSTRUCTION_FIRE_ONCE_NOW; + + if (instr == MISFIRE_INSTRUCTION_DO_NOTHING) { + Date newFireTime = getFireTimeAfter(new Date()); + while (newFireTime != null && cal != null + && !cal.isTimeIncluded(newFireTime.getTime())) { + newFireTime = getFireTimeAfter(newFireTime); + } + setNextFireTime(newFireTime); + } else if (instr == MISFIRE_INSTRUCTION_FIRE_ONCE_NOW) { + setNextFireTime(new Date()); + } + } + + /** + *

+ * Determines whether the date and (optionally) time of the given Calendar + * instance falls on a scheduled fire-time of this trigger. + *

+ * + *

+ * Equivalent to calling willFireOn(cal, false). + *

+ * + * @param test the date to compare + * + * @see #willFireOn(Calendar, boolean) + */ + public boolean willFireOn(Calendar test) { + return willFireOn(test, false); + } + + /** + *

+ * Determines whether the date and (optionally) time of the given Calendar + * instance falls on a scheduled fire-time of this trigger. + *

+ * + *

+ * Note that the value returned is NOT validated against the related + * org.quartz.Calendar (if any) + *

+ * + * @param test the date to compare + * @param dayOnly if set to true, the method will only determine if the + * trigger will fire during the day represented by the given Calendar + * (hours, minutes and seconds will be ignored). + * @see #willFireOn(Calendar) + */ + public boolean willFireOn(Calendar test, boolean dayOnly) { + + test = (Calendar) test.clone(); + + test.set(Calendar.MILLISECOND, 0); // don't compare millis. + + if(dayOnly) { + test.set(Calendar.HOUR, 0); + test.set(Calendar.MINUTE, 0); + test.set(Calendar.SECOND, 0); + } + + Date testTime = test.getTime(); + + Date fta = getFireTimeAfter(new Date(test.getTime().getTime() - 1000)); + + Calendar p = Calendar.getInstance(test.getTimeZone()); + p.setTime(fta); + + int year = p.get(Calendar.YEAR); + int month = p.get(Calendar.MONTH); + int day = p.get(Calendar.DATE); + + if(dayOnly) { + return (year == test.get(Calendar.YEAR) + && month == test.get(Calendar.MONTH) + && day == test.get(Calendar.DATE)); + } + + while(fta.before(testTime)) { + fta = getFireTimeAfter(fta); + } + + if(fta.equals(testTime)) + return true; + + return false; + } + + /** + *

+ * Called after the {@link Scheduler} has executed the + * {@link org.quartz.JobDetail} associated with the Trigger + * in order to get the final instruction code from the trigger. + *

+ * + * @param context + * is the JobExecutionContext that was used by the + * Job'sexecute(xx) method. + * @param result + * is the JobExecutionException thrown by the + * Job, if any (may be null). + * @return one of the Trigger.INSTRUCTION_XXX constants. + * + * @see #INSTRUCTION_NOOP + * @see #INSTRUCTION_RE_EXECUTE_JOB + * @see #INSTRUCTION_DELETE_TRIGGER + * @see #INSTRUCTION_SET_TRIGGER_COMPLETE + * @see #triggered(Calendar) + */ + public int executionComplete(JobExecutionContext context, + JobExecutionException result) { + if (result != null && result.refireImmediately()) + return INSTRUCTION_RE_EXECUTE_JOB; + + if (result != null && result.unscheduleFiringTrigger()) + return INSTRUCTION_SET_TRIGGER_COMPLETE; + + if (result != null && result.unscheduleAllTriggers()) + return INSTRUCTION_SET_ALL_JOB_TRIGGERS_COMPLETE; + + if (!mayFireAgain()) return INSTRUCTION_DELETE_TRIGGER; + + return INSTRUCTION_NOOP; + } + + /** + *

+ * Called when the {@link Scheduler} has decided to 'fire' + * the trigger (execute the associated Job), in order to + * give the Trigger a chance to update itself for its next + * triggering (if any). + *

+ * + * @see #executionComplete(JobExecutionContext, JobExecutionException) + */ + public void triggered(org.quartz.Calendar calendar) { + previousFireTime = nextFireTime; + nextFireTime = getFireTimeAfter(nextFireTime); + + while (nextFireTime != null && calendar != null + && !calendar.isTimeIncluded(nextFireTime.getTime())) { + nextFireTime = getFireTimeAfter(nextFireTime); + } + } + + /** + * + * @see org.quartz.Trigger#updateWithNewCalendar(org.quartz.Calendar, long) + */ + public void updateWithNewCalendar(org.quartz.Calendar calendar, long misfireThreshold) + { + nextFireTime = getFireTimeAfter(previousFireTime); + + Date now = new Date(); + do { + while (nextFireTime != null && calendar != null + && !calendar.isTimeIncluded(nextFireTime.getTime())) { + nextFireTime = getFireTimeAfter(nextFireTime); + } + + if(nextFireTime != null && nextFireTime.before(now)) { + long diff = now.getTime() - nextFireTime.getTime(); + if(diff >= misfireThreshold) { + nextFireTime = getFireTimeAfter(nextFireTime); + continue; + } + } + }while(false); + } + + /** + *

+ * Called by the scheduler at the time a Trigger is first + * added to the scheduler, in order to have the Trigger + * compute its first fire time, based on any associated calendar. + *

+ * + *

+ * After this method has been called, getNextFireTime() + * should return a valid answer. + *

+ * + * @return the first time at which the Trigger will be fired + * by the scheduler, which is also the same value getNextFireTime() + * will return (until after the first firing of the Trigger). + *

+ */ + public Date computeFirstFireTime(org.quartz.Calendar calendar) { + nextFireTime = getFireTimeAfter(new Date(startTime.getTime() - 1000l)); + + while (nextFireTime != null && calendar != null + && !calendar.isTimeIncluded(nextFireTime.getTime())) { + nextFireTime = getFireTimeAfter(nextFireTime); + } + + return nextFireTime; + } + + public String getExpressionSummary() { + return cronEx == null ? null : cronEx.getExpressionSummary(); + } + + //////////////////////////////////////////////////////////////////////////// + // + // Computation Functions + // + //////////////////////////////////////////////////////////////////////////// + + protected Date getTimeAfter(Date afterTime) { + return cronEx.getTimeAfter(afterTime); + } + + protected Date getTimeBefore(Date endTime) + { + return null; + } + + public static void main(String[] args) // TODO: remove method after good + // unit testing + throws Exception { + + String expr = "15 10 0/4 * * ?"; + if(args != null && args.length > 0 && args[0] != null) + expr = args[0]; + + CronTrigger ct = new CronTrigger("t", "g", "j", "g", new Date(), null, expr); + ct.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); + System.err.println(ct.getExpressionSummary()); + System.err.println("tz=" + ct.getTimeZone().getID()); + System.err.println(); + + java.util.List times = TriggerUtils.computeFireTimes(ct, null, 25); + + for (int i = 0; i < times.size(); i++) { + System.err.println("firetime = " + times.get(i)); + } + + Calendar tt = Calendar.getInstance(); + tt.set(Calendar.DATE, 17); + tt.set(Calendar.MONTH, 5 - 1); + tt.set(Calendar.HOUR, 11); + tt.set(Calendar.MINUTE, 0); + tt.set(Calendar.SECOND, 7); + + System.err.println("\nWill fire on: " + tt.getTime() + " -- " + ct.willFireOn(tt, false)); + + +// CRON Expression: 0 0 9 * * ? +// +// TimeZone.getDefault().getDisplayName() = Central African Time +// TimeZone.getDefault().getID() = Africa/Harare + // +//// System.err.println(); +//// System.err.println(); +//// System.err.println(); +//// System.err.println("Daylight test:"); +//// +//// CronTrigger trigger = new CronTrigger(); +//// +//// TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); +//// // TimeZone timeZone = TimeZone.getDefault(); +//// +//// trigger.setTimeZone(timeZone); +//// trigger.setCronExpression("0 0 1 ? 4 *"); +//// +//// Date start = new Date(1056319200000L); +//// Date end = new Date(1087682399000L); +//// +//// trigger.setStartTime(start); +//// trigger.setEndTime(end); +//// +//// Date next = new Date(1056232800000L); +//// while (next != null) { +//// next = trigger.getFireTimeAfter(next); +//// if (next != null) { +//// Calendar cal = Calendar.getInstance(); +//// cal.setTimeZone(timeZone); +//// cal.setTime(next); +//// System.err.println(cal.get(Calendar.MONTH) + "/" +//// + cal.get(Calendar.DATE) + "/" + cal.get(Calendar.YEAR) +//// + " - " + cal.get(Calendar.HOUR_OF_DAY) + ":" +//// + cal.get(Calendar.MINUTE)); +//// } +//// } +//// +//// System.err.println(); +//// System.err.println(); +//// System.err.println(); +//// System.err.println("Midnight test:"); +//// +//// trigger = new CronTrigger(); +//// +//// timeZone = TimeZone.getTimeZone("Asia/Jerusalem"); +//// // timeZone = TimeZone.getTimeZone("America/Los_Angeles"); +//// // TimeZone timeZone = TimeZone.getDefault(); +//// +//// trigger.setTimeZone(timeZone); +//// trigger.setCronExpression("0 /15 * ? 4 *"); +//// +//// start = new Date(1056319200000L); +//// end = new Date(1087682399000L); +//// +//// trigger.setStartTime(start); +//// trigger.setEndTime(end); +//// +//// next = new Date(1056232800000L); +//// while (next != null) { +//// next = trigger.getFireTimeAfter(next); +//// if (next != null) { +//// Calendar cal = Calendar.getInstance(); +//// cal.setTimeZone(timeZone); +//// cal.setTime(next); +//// System.err.println(cal.get(Calendar.MONTH) + "/" +//// + cal.get(Calendar.DATE) + "/" + cal.get(Calendar.YEAR) +//// + " - " + cal.get(Calendar.HOUR_OF_DAY) + ":" +//// + cal.get(Calendar.MINUTE)); +//// } +//// } + + } +} + Index: 3rdParty_sources/quartz/org/quartz/InterruptableJob.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/InterruptableJob.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/InterruptableJob.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,93 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +/** + *

+ * The interface to be implemented by {@link Job}s that provide a + * mechanism for having their execution interrupted. It is NOT a requirment + * for jobs to implement this interface - in fact, for most people, none of + * their jobs will. + *

+ * + *

+ * The means of actually interrupting the Job must be implemented within the + * Job itself (the interrupt() method of this + * interface is simply a means for the scheduler to inform the Job + * that a request has been made for it to be interrupted). The mechanism that + * your jobs use to interrupt themselves might vary between implementations. + * However the principle idea in any implementation should be to have the + * body of the job's execute(..) periodically check some flag to + * see if an interruption has been requested, and if the flag is set, somehow + * abort the performance of the rest of the job's work. An example of + * interrupting a job can be found in the java source for the class + * org.quartz.examples.DumbInterruptableJob. It is legal to use + * some combination of wait() and notify() + * synchronization within interrupt() and execute(..) + * in order to have the interrupt() method block until the + * execute(..) signals that it has noticed the set flag. + *

+ * + *

+ * If the Job performs some form of blocking I/O or similar functions, you may + * want to consider having the Job.execute(..) method store a + * reference to the calling Thread as a member variable. Then the + * impplementation of this interfaces interrupt() method can call + * interrupt() on that Thread. Before attempting this, make + * sure that you fully understand what java.lang.Thread.interrupt() + * does and doesn't do. Also make sure that you clear the Job's member + * reference to the Thread when the execute(..) method exits (preferrably in a + * finally block. + *

+ * + * @see Job + * @see StatefulJob + * @see Scheduler#interrupt(String, String) + * @see org.quartz.examples.example7.DumbInterruptableJob + * + * @author James House + */ +public interface InterruptableJob extends Job { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Called by the {@link Scheduler} when a user + * interrupts the Job. + *

+ * + * @return void (nothing) if job interrupt is successful. + * @throws UnableToInterruptJobException + * if there is an exception while interrupting the job. + */ + public void interrupt() + throws UnableToInterruptJobException; + + +} Index: 3rdParty_sources/quartz/org/quartz/Job.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/Job.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/Job.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,80 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +/** + *

+ * The interface to be implemented by classes which represent a 'job' to be + * performed. + *

+ * + *

+ * Instances of Job must have a public + * no-argument constructor. + *

+ * + *

+ * JobDataMap provides a mechanism for 'instance member data' + * that may be required by some implementations of this interface. + *

+ * + * @see JobDetail + * @see StatefulJob + * @see Trigger + * @see Scheduler + * + * @author James House + */ +public interface Job { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * fires that is associated with the Job. + *

+ * + *

+ * The implementation may wish to set a + * {@link JobExecutionContext#setResult(Object) result} object on the + * {@link JobExecutionContext} before this method exits. The result itself + * is meaningless to Quartz, but may be informative to + * {@link JobListener}s or + * {@link TriggerListener}s that are watching the job's + * execution. + *

+ * + * @return void (nothing) if job is successful. + * @throws JobExecutionException + * if there is an exception while executing the job. + */ + public void execute(JobExecutionContext context) + throws JobExecutionException; + +} Index: 3rdParty_sources/quartz/org/quartz/JobDataMap.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/JobDataMap.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/JobDataMap.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,806 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import java.io.Serializable; +import java.util.Iterator; +import java.util.Map; + +import org.quartz.utils.DirtyFlagMap; + +/** + *

+ * Holds state information for Job instances. + *

+ * + *

+ * JobDataMap instances are stored once when the Job + * is added to a scheduler. They are also re-persisted after every execution of + * StatefulJob instances. + *

+ * + *

+ * JobDataMap instances can also be stored with a + * Trigger. This can be useful in the case where you have a Job + * that is stored in the scheduler for regular/repeated use by multiple + * Triggers, yet with each independent triggering, you want to supply the + * Job with different data inputs. + *

+ * + *

+ * The JobExecutionContext passed to a Job at execution time + * also contains a convenience JobDataMap that is the result + * of merging the contents of the trigger's JobDataMap (if any) over the + * Job's JobDataMap (if any). + *

+ * + * @see Job + * @see StatefulJob + * @see Trigger + * @see JobExecutionContext + * + * @author James House + */ +public class JobDataMap extends DirtyFlagMap implements Serializable { + + private static final long serialVersionUID = -6939901990106713909L; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private boolean allowsTransientData = false; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create an empty JobDataMap. + *

+ */ + public JobDataMap() { + super(15); + } + + /** + *

+ * Create a JobDataMap with the given data. + *

+ */ + public JobDataMap(Map map) { + this(); + + putAll(map); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Tell the JobDataMap that it should allow non- Serializable + * data. + *

+ * + *

+ * If the JobDataMap does contain non- Serializable + * objects, and it belongs to a non-volatile Job that is + * stored in a JobStore that supports persistence, then + * those elements will be nulled-out during persistence. + *

+ */ + public void setAllowsTransientData(boolean allowsTransientData) { + + if (containsTransientData() && !allowsTransientData) + throw new IllegalStateException( + "Cannot set property 'allowsTransientData' to 'false' " + + "when data map contains non-serializable objects."); + + this.allowsTransientData = allowsTransientData; + } + + public boolean getAllowsTransientData() { + return allowsTransientData; + } + + public boolean containsTransientData() { + + if (!getAllowsTransientData()) // short circuit... + return false; + + String[] keys = getKeys(); + + for (int i = 0; i < keys.length; i++) { + Object o = super.get(keys[i]); + if (!(o instanceof Serializable)) return true; + } + + return false; + } + + /** + *

+ * Nulls-out any data values that are non-Serializable. + *

+ */ + public void removeTransientData() { + + if (!getAllowsTransientData()) // short circuit... + return; + + String[] keys = getKeys(); + + for (int i = 0; i < keys.length; i++) { + Object o = super.get(keys[i]); + if (!(o instanceof Serializable)) remove(keys[i]); + } + + } + + /** + *

+ * Adds the name-value pairs in the given Map to the JobDataMap. + *

+ * + *

+ * All keys must be Strings, and all values must be Serializable. + *

+ */ + public void putAll(Map map) { + Iterator itr = map.keySet().iterator(); + while (itr.hasNext()) { + Object key = itr.next(); + Object val = map.get(key); + + put(key, val); + // will throw IllegalArgumentException if value not serilizable + } + } + + /** + *

+ * Adds the given int value to the Job's + * data map. + *

+ */ + public void put(String key, int value) { + super.put(key, new Integer(value)); + } + + /** + *

+ * Adds the given long value to the Job's + * data map. + *

+ */ + public void put(String key, long value) { + super.put(key, new Long(value)); + } + + /** + *

+ * Adds the given float value to the Job's + * data map. + *

+ */ + public void put(String key, float value) { + super.put(key, new Float(value)); + } + + /** + *

+ * Adds the given double value to the Job's + * data map. + *

+ */ + public void put(String key, double value) { + super.put(key, new Double(value)); + } + + /** + *

+ * Adds the given boolean value to the Job's + * data map. + *

+ */ + public void put(String key, boolean value) { + super.put(key, new Boolean(value)); + } + + /** + *

+ * Adds the given char value to the Job's + * data map. + *

+ */ + public void put(String key, char value) { + super.put(key, new Character(value)); + } + + /** + *

+ * Adds the given String value to the Job's + * data map. + *

+ */ + public void put(String key, String value) { + super.put(key, value); + } + + /** + *

+ * Adds the given boolean value as a string version to the + * Job's data map. + *

+ */ + public void putAsString(String key, boolean value) { + String strValue = new Boolean(value).toString(); + + super.put(key, strValue); + } + + /** + *

+ * Adds the given Boolean value as a string version to the + * Job's data map. + *

+ */ + public void putAsString(String key, Boolean value) { + String strValue = value.toString(); + + super.put(key, strValue); + } + + /** + *

+ * Adds the given char value as a string version to the + * Job's data map. + *

+ */ + public void putAsString(String key, char value) { + String strValue = new Character(value).toString(); + + super.put(key, strValue); + } + + /** + *

+ * Adds the given Character value as a string version to the + * Job's data map. + *

+ */ + public void putAsString(String key, Character value) { + String strValue = value.toString(); + + super.put(key, strValue); + } + + /** + *

+ * Adds the given double value as a string version to the + * Job's data map. + *

+ */ + public void putAsString(String key, double value) { + String strValue = new Double(value).toString(); + + super.put(key, strValue); + } + + /** + *

+ * Adds the given Double value as a string version to the + * Job's data map. + *

+ */ + public void putAsString(String key, Double value) { + String strValue = value.toString(); + + super.put(key, strValue); + } + + /** + *

+ * Adds the given float value as a string version to the + * Job's data map. + *

+ */ + public void putAsString(String key, float value) { + String strValue = new Float(value).toString(); + + super.put(key, strValue); + } + + /** + *

+ * Adds the given Float value as a string version to the + * Job's data map. + *

+ */ + public void putAsString(String key, Float value) { + String strValue = value.toString(); + + super.put(key, strValue); + } + + /** + *

+ * Adds the given int value as a string version to the + * Job's data map. + *

+ */ + public void putAsString(String key, int value) { + String strValue = new Integer(value).toString(); + + super.put(key, strValue); + } + + /** + *

+ * Adds the given Integer value as a string version to the + * Job's data map. + *

+ */ + public void putAsString(String key, Integer value) { + String strValue = value.toString(); + + super.put(key, strValue); + } + + /** + *

+ * Adds the given long value as a string version to the + * Job's data map. + *

+ */ + public void putAsString(String key, long value) { + String strValue = new Long(value).toString(); + + super.put(key, strValue); + } + + /** + *

+ * Adds the given Long value as a string version to the + * Job's data map. + *

+ */ + public void putAsString(String key, Long value) { + String strValue = value.toString(); + + super.put(key, strValue); + } + + /** + *

+ * Adds the given Serializable object value to the JobDataMap. + *

+ */ + public Object put(Object key, Object value) { + if (!(key instanceof String)) + throw new IllegalArgumentException( + "Keys in map must be Strings."); + + return super.put(key, value); + } + + /** + *

+ * Retrieve the identified int value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not an Integer. + */ + public int getInt(String key) { + Object obj = get(key); + + try { + return ((Integer) obj).intValue(); + } catch (Exception e) { + throw new ClassCastException("Identified object is not an Integer."); + } + } + + /** + *

+ * Retrieve the identified long value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a Long. + */ + public long getLong(String key) { + Object obj = get(key); + + try { + return ((Long) obj).longValue(); + } catch (Exception e) { + throw new ClassCastException("Identified object is not a Long."); + } + } + + /** + *

+ * Retrieve the identified float value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a Float. + */ + public float getFloat(String key) { + Object obj = get(key); + + try { + return ((Float) obj).floatValue(); + } catch (Exception e) { + throw new ClassCastException("Identified object is not a Float."); + } + } + + /** + *

+ * Retrieve the identified double value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a Double. + */ + public double getDouble(String key) { + Object obj = get(key); + + try { + return ((Double) obj).doubleValue(); + } catch (Exception e) { + throw new ClassCastException("Identified object is not a Double."); + } + } + + /** + *

+ * Retrieve the identified boolean value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a Boolean. + */ + public boolean getBoolean(String key) { + Object obj = get(key); + + try { + return ((Boolean) obj).booleanValue(); + } catch (Exception e) { + throw new ClassCastException("Identified object is not a Boolean."); + } + } + + /** + *

+ * Retrieve the identified char value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a Character. + */ + public char getChar(String key) { + Object obj = get(key); + + try { + return ((Character) obj).charValue(); + } catch (Exception e) { + throw new ClassCastException( + "Identified object is not a Character."); + } + } + + /** + *

+ * Retrieve the identified String value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public String getString(String key) { + Object obj = get(key); + + try { + return (String) obj; + } catch (Exception e) { + throw new ClassCastException("Identified object is not a String."); + } + } + + /** + *

+ * Retrieve the identified int value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public int getIntFromString(String key) { + Object obj = get(key); + + return new Integer((String) obj).intValue(); + } + + /** + *

+ * Retrieve the identified int value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String or Integeger. + */ + public long getIntValue(String key) { + Object obj = get(key); + + if(obj instanceof String) + return getIntFromString(key); + else + return getInt(key); + } + + /** + *

+ * Retrieve the identified int value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public Integer getIntegerFromString(String key) { + Object obj = get(key); + + return new Integer((String) obj); + } + + /** + *

+ * Retrieve the identified boolean value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public boolean getBooleanValueFromString(String key) { + Object obj = get(key); + + return new Boolean((String) obj).booleanValue(); + } + + /** + *

+ * Retrieve the identified boolean value from the + * JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String or Boolean. + */ + public boolean getBooleanValue(String key) { + Object obj = get(key); + + if(obj instanceof String) + return getBooleanValueFromString(key); + else + return getBoolean(key); + } + + /** + *

+ * Retrieve the identified Boolean value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public Boolean getBooleanFromString(String key) { + Object obj = get(key); + + return new Boolean((String) obj); + } + + /** + *

+ * Retrieve the identified char value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public char getCharFromString(String key) { + Object obj = get(key); + + return ((String) obj).charAt(0); + } + + /** + *

+ * Retrieve the identified Character value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public Character getCharacterFromString(String key) { + Object obj = get(key); + + return new Character(((String) obj).charAt(0)); + } + + /** + *

+ * Retrieve the identified double value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public double getDoubleValueFromString(String key) { + Object obj = get(key); + + return new Double((String) obj).doubleValue(); + } + + /** + *

+ * Retrieve the identified double value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String or Double. + */ + public double getDoubleValue(String key) { + Object obj = get(key); + + if(obj instanceof String) + return getDoubleValueFromString(key); + else + return getDouble(key); + } + + /** + *

+ * Retrieve the identified Double value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public Double getDoubleFromString(String key) { + Object obj = get(key); + + return new Double((String) obj); + } + + /** + *

+ * Retrieve the identified float value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public float getFloatValueFromString(String key) { + Object obj = get(key); + + return new Float((String) obj).floatValue(); + } + + /** + *

+ * Retrieve the identified float value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String or Float. + */ + public float getFloatValue(String key) { + Object obj = get(key); + + if(obj instanceof String) + return getFloatValueFromString(key); + else + return getFloat(key); + } + + /** + *

+ * Retrieve the identified Float value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public Float getFloatFromString(String key) { + Object obj = get(key); + + return new Float((String) obj); + } + + /** + *

+ * Retrieve the identified long value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public long getLongValueFromString(String key) { + Object obj = get(key); + + return new Long((String) obj).longValue(); + } + + /** + *

+ * Retrieve the identified long value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String or Long. + */ + public long getLongValue(String key) { + Object obj = get(key); + + if(obj instanceof String) + return getLongValueFromString(key); + else + return getLong(key); + } + + /** + *

+ * Retrieve the identified Long value from the JobDataMap. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public Long getLongFromString(String key) { + Object obj = get(key); + + return new Long((String) obj); + } + + public String[] getKeys() { + return (String[]) keySet().toArray(new String[size()]); + } + +} Index: 3rdParty_sources/quartz/org/quartz/JobDetail.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/JobDetail.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/JobDetail.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,482 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import java.util.ArrayList; + +/** + *

+ * Conveys the detail properties of a given Job instance. + *

+ * + *

+ * Quartz does not store an actual instance of a Job class, but + * instead allows you to define an instance of one, through the use of a JobDetail. + *

+ * + *

+ * Job s have a name and group associated with them, which + * should uniquely identify them within a single {@link Scheduler}. + *

+ * + *

+ * Trigger s are the 'mechanism' by which Job s + * are scheduled. Many Trigger s can point to the same Job, + * but a single Trigger can only point to one Job. + *

+ * + * @see Job + * @see StatefulJob + * @see JobDataMap + * @see Trigger + * + * @author James House + * @author Sharada Jambula + */ +public class JobDetail implements Cloneable, java.io.Serializable { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private String name; + + private String group = Scheduler.DEFAULT_GROUP; + + private String description; + + private Class jobClass; + + private JobDataMap jobDataMap; + + private boolean volatility = false; + + private boolean durability = false; + + private boolean shouldRecover = false; + + private ArrayList jobListeners = new ArrayList(2); + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a JobDetail with no specified name or group, and + * the default settings of all the other properties. + *

+ * + *

+ * Note that the {@link #setName(String)},{@link #setGroup(String)}and + * {@link #setJobClass(Class)}methods must be called before the job can be + * placed into a {@link Scheduler} + *

+ */ + public JobDetail() { + // do nothing... + } + + /** + *

+ * Create a JobDetail with the given name, and group, and + * the default settings of all the other properties. + *

+ * + * @param group if null, Scheduler.DEFAULT_GROUP will be used. + * + * @exception IllegalArgumentException + * if nameis null or empty, or the group is an empty string. + */ + public JobDetail(String name, String group, Class jobClass) { + setName(name); + setGroup(group); + setJobClass(jobClass); + } + + /** + *

+ * Create a JobDetail with the given name, and group, and + * the given settings of all the other properties. + *

+ * + * @param group if null, Scheduler.DEFAULT_GROUP will be used. + * + * @exception IllegalArgumentException + * if nameis null or empty, or the group is an empty string. + */ + public JobDetail(String name, String group, Class jobClass, + boolean volatility, boolean durability, boolean recover) { + setName(name); + setGroup(group); + setJobClass(jobClass); + setVolatility(volatility); + setDurability(durability); + setRequestsRecovery(recover); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Get the name of this Job. + *

+ */ + public String getName() { + return name; + } + + /** + *

+ * Set the name of this Job. + *

+ * + * @exception IllegalArgumentException + * if name is null or empty. + */ + public void setName(String name) { + if (name == null || name.trim().length() == 0) + throw new IllegalArgumentException("Job name cannot be empty."); + + this.name = name; + } + + /** + *

+ * Get the group of this Job. + *

+ */ + public String getGroup() { + return group; + } + + /** + *

+ * Set the group of this Job. + *

+ * + * @param group if null, Scheduler.DEFAULT_GROUP will be used. + * + * @exception IllegalArgumentException + * if the group is an empty string. + */ + public void setGroup(String group) { + if (group != null && group.trim().length() == 0) + throw new IllegalArgumentException( + "Group name cannot be empty."); + + if(group == null) + group = Scheduler.DEFAULT_GROUP; + + this.group = group; + } + + /** + *

+ * Returns the 'full name' of the Trigger in the format + * "group.name". + *

+ */ + public String getFullName() { + return group + "." + name; + } + + /** + *

+ * Return the description given to the Job instance by its + * creator (if any). + *

+ * + * @return null if no description was set. + */ + public String getDescription() { + return description; + } + + /** + *

+ * Set a description for the Job instance - may be useful + * for remembering/displaying the purpose of the job, though the + * description has no meaning to Quartz. + *

+ */ + public void setDescription(String description) { + this.description = description; + } + + /** + *

+ * Get the instance of Job that will be executed. + *

+ */ + public Class getJobClass() { + return jobClass; + } + + /** + *

+ * Set the instance of Job that will be executed. + *

+ * + * @exception IllegalArgumentException + * if jobClass is null or the class is not a Job. + */ + public void setJobClass(Class jobClass) { + if (jobClass == null) + throw new IllegalArgumentException("Job class cannot be null."); + + if (!Job.class.isAssignableFrom(jobClass)) + throw new IllegalArgumentException( + "Job class must implement the Job interface."); + + this.jobClass = jobClass; + } + + /** + *

+ * Get the JobDataMap that is associated with the Job. + *

+ */ + public JobDataMap getJobDataMap() { + if (jobDataMap == null) jobDataMap = new JobDataMap(); + return jobDataMap; + } + + /** + *

+ * Set the JobDataMap to be associated with the Job. + *

+ */ + public void setJobDataMap(JobDataMap jobDataMap) { + this.jobDataMap = jobDataMap; + } + + /** + *

+ * Validates whether the properties of the JobDetail are + * valid for submission into a Scheduler. + * + * @throws IllegalStateException + * if a required property (such as Name, Group, Class) is not + * set. + */ + public void validate() throws SchedulerException { + if (name == null) + throw new SchedulerException("Job's name cannot be null", + SchedulerException.ERR_CLIENT_ERROR); + + if (group == null) + throw new SchedulerException("Job's group cannot be null", + SchedulerException.ERR_CLIENT_ERROR); + + if (jobClass == null) + throw new SchedulerException("Job's class cannot be null", + SchedulerException.ERR_CLIENT_ERROR); + } + + /** + *

+ * Set whether or not the Job should be persisted in the + * {@link org.quartz.spi.JobStore} for re-use after program + * restarts. + *

+ * + *

+ * If not explicitly set, the default value is false. + *

+ */ + public void setVolatility(boolean volatility) { + this.volatility = volatility; + } + + /** + *

+ * Set whether or not the Job should remain stored after it + * is orphaned (no {@link Trigger}s point to it). + *

+ * + *

+ * If not explicitly set, the default value is false. + *

+ */ + public void setDurability(boolean durability) { + this.durability = durability; + } + + /** + *

+ * Set whether or not the the Scheduler should re-execute + * the Job if a 'recovery' or 'fail-over' situation is + * encountered. + *

+ * + *

+ * If not explicitly set, the default value is false. + *

+ * + * @see JobExecutionContext#isRecovering() + * @see JobExecutionContext#isFailedOver() + */ + public void setRequestsRecovery(boolean shouldRecover) { + this.shouldRecover = shouldRecover; + } + + /** + *

+ * Whether or not the Job should not be persisted in the + * {@link org.quartz.spi.JobStore} for re-use after program + * restarts. + *

+ * + *

+ * If not explicitly set, the default value is false. + *

+ * + * @return true if the Job should be garbage + * collected along with the {@link Scheduler}. + */ + public boolean isVolatile() { + return volatility; + } + + /** + *

+ * Whether or not the Job should remain stored after it is + * orphaned (no {@link Trigger}s point to it). + *

+ * + *

+ * If not explicitly set, the default value is false. + *

+ * + * @return true if the Job should remain persisted after + * being orphaned. + */ + public boolean isDurable() { + return durability; + } + + /** + *

+ * Whether or not the Job implements the interface {@link StatefulJob}. + *

+ */ + public boolean isStateful() { + if (jobClass == null) + return false; + + return (StatefulJob.class.isAssignableFrom(jobClass)); + } + + /** + *

+ * Instructs the Scheduler whether or not the Job + * should be re-executed if a 'recovery' or 'fail-over' situation is + * encountered. + *

+ * + *

+ * If not explicitly set, the default value is false. + *

+ * + * @see JobExecutionContext#isRecovering() + * @see JobExecutionContext#isFailedOver() + */ + public boolean requestsRecovery() { + return shouldRecover; + } + + /** + *

+ * Add the specified name of a {@link JobListener} to the + * end of the Job's list of listeners. + *

+ */ + public void addJobListener(String name) { + jobListeners.add(name); + } + + /** + *

+ * Remove the specified name of a {@link JobListener} from + * the Job's list of listeners. + *

+ * + * @return true if the given name was found in the list, and removed + */ + public boolean removeJobListener(String name) { + return jobListeners.remove(name); + } + + /** + *

+ * Returns an array of String s containing the names of all + * {@link JobListener} s assigned to the Job, + * in the order in which they should be notified. + *

+ */ + public String[] getJobListenerNames() { + return (String[]) jobListeners.toArray(new String[jobListeners.size()]); + } + + /** + *

+ * Return a simple string representation of this object. + *

+ */ + public String toString() { + return "JobDetail '" + getFullName() + "': jobClass: '" + + ((getJobClass() == null) ? null : getJobClass().getName()) + + " isStateful: " + isStateful() + " isVolatile: " + + isVolatile() + " isDurable: " + isDurable() + + " requestsRecovers: " + requestsRecovery(); + } + + public Object clone() { + JobDetail copy; + try { + copy = (JobDetail) super.clone(); + copy.jobListeners = (ArrayList) jobListeners.clone(); + if (jobDataMap != null) + copy.jobDataMap = (JobDataMap) jobDataMap.clone(); + } catch (CloneNotSupportedException ex) { + throw new IncompatibleClassChangeError("Not Cloneable."); + } + + return copy; + } + +} Index: 3rdParty_sources/quartz/org/quartz/JobExecutionContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/JobExecutionContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/JobExecutionContext.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,373 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import java.util.Date; +import java.util.HashMap; + +import org.quartz.spi.TriggerFiredBundle; + +/** + *

+ * A context bundle containing handles to various environment information, that + * is given to a {@link org.quartz.JobDetail} instance as it is + * executed, and to a {@link Trigger} instance after the + * execution completes. + *

+ * + *

+ * The JobDataMap found on this object (via the + * getMergedJobDataMap() method) serves as a convenience - + * it is a merge of the JobDataMap found on the + * JobDetail and the one found on the Trigger, with + * the value in the latter overriding any same-named values in the former. + * It is thus considered a 'best practice' that the execute code of a Job + * retrieve data from the JobDataMap found on this object NOTE: Do not + * expect value 'set' into this JobDataMap to somehow be set back onto a + * StatefulJob's own JobDataMap. + *

+ * + *

+ * JobExecutionContext s are also returned from the + * Scheduler.getCurrentlyExecutingJobs() + * method. These are the same instances as those past into the jobs that are + * currently executing within the scheduler. The exception to this is when your + * application is using Quartz remotely (i.e. via RMI) - in which case you get + * a clone of the JobExecutionContexts, and their references to + * the Scheduler and Job instances have been lost (a + * clone of the JobDetail is still available - just not a handle + * to the job instance that is running). + *

+ * + * @see #getJobDetail() + * @see #getScheduler() + * @see #getMergedJobDataMap() + * + * @see Job + * @see Trigger + * @see JobDataMap + * + * @author James House + */ +public class JobExecutionContext implements java.io.Serializable { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private transient Scheduler scheduler; + + private Trigger trigger; + + private JobDetail jobDetail; + + private JobDataMap jobDataMap; + + private transient Job job; + + private Calendar calendar; + + private boolean recovering = false; + + private int numRefires = 0; + + private Date fireTime; + + private Date scheduledFireTime; + + private Date prevFireTime; + + private Date nextFireTime; + + private long jobRunTime = -1; + + private Object result; + + private HashMap data = new HashMap(); + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a JobExcecutionContext with the given context data. + *

+ */ + public JobExecutionContext(Scheduler scheduler, + TriggerFiredBundle firedBundle, Job job) { + this.scheduler = scheduler; + this.trigger = firedBundle.getTrigger(); + this.calendar = firedBundle.getCalendar(); + this.jobDetail = firedBundle.getJobDetail(); + this.job = job; + this.recovering = firedBundle.isRecovering(); + this.fireTime = firedBundle.getFireTime(); + this.scheduledFireTime = firedBundle.getScheduledFireTime(); + this.prevFireTime = firedBundle.getPrevFireTime(); + this.nextFireTime = firedBundle.getNextFireTime(); + + this.jobDataMap = new JobDataMap(); + this.jobDataMap.putAll(jobDetail.getJobDataMap()); + this.jobDataMap.putAll(trigger.getJobDataMap()); + + this.jobDataMap.setMutable(false); + this.trigger.getJobDataMap().setMutable(false); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Get a handle to the Scheduler instance that fired the + * Job. + *

+ */ + public Scheduler getScheduler() { + return scheduler; + } + + /** + *

+ * Get a handle to the Trigger instance that fired the + * Job. + *

+ */ + public Trigger getTrigger() { + return trigger; + } + + /** + *

+ * Get a handle to the Calendar referenced by the Trigger + * instance that fired the Job. + *

+ */ + public Calendar getCalendar() { + return calendar; + } + + /** + *

+ * If the Job is being re-executed because of a 'recovery' + * situation, this method will return true. + *

+ */ + public boolean isRecovering() { + return recovering; + } + + public void incrementRefireCount() { + numRefires++; + } + + public int getRefireCount() { + return numRefires; + } + + /** + *

+ * Get the convenience JobDataMap of this execution context. + *

+ * + *

+ * The JobDataMap found on this object serves as a convenience - + * it is a merge of the JobDataMap found on the + * JobDetail and the one found on the Trigger, with + * the value in the latter overriding any same-named values in the former. + * It is thus considered a 'best practice' that the execute code of a Job + * retrieve data from the JobDataMap found on this object + *

+ * + *

NOTE: Do not + * expect value 'set' into this JobDataMap to somehow be set back onto a + * StatefulJob's own JobDataMap. + *

+ * + *

+ * Attempts to change the contents of this map typically result in an + * IllegalStateException. + *

+ * + */ + public JobDataMap getMergedJobDataMap() { + return jobDataMap; + } + + /** + *

+ * Get the JobDetail associated with the Job. + *

+ */ + public JobDetail getJobDetail() { + return jobDetail; + } + + /** + *

+ * Get the instance of the Job that was created for this + * execution. + *

+ * + *

+ * Note: The Job instance is not available through remote scheduler + * interfaces. + *

+ */ + public Job getJobInstance() { + return job; + } + + /** + * The actual time the trigger fired. For instance the scheduled time may + * have been 10:00:00 but the actual fire time may have been 10:00:03 if + * the scheduler was too busy. + * + * @return Returns the fireTime. + * @see #getScheduledFireTime() + */ + public Date getFireTime() { + return fireTime; + } + + /** + * The scheduled time the trigger fired for. For instance the scheduled + * time may have been 10:00:00 but the actual fire time may have been + * 10:00:03 if the scheduler was too busy. + * + * @return Returns the scheduledFireTime. + * @see #getFireTime() + */ + public Date getScheduledFireTime() { + return scheduledFireTime; + } + + public Date getPreviousFireTime() { + return prevFireTime; + } + + public Date getNextFireTime() { + return nextFireTime; + } + + public String toString() { + return "JobExecutionContext:" + " trigger: '" + + getTrigger().getFullName() + " job: " + + getJobDetail().getFullName() + " fireTime: '" + getFireTime() + + " scheduledFireTime: " + getScheduledFireTime() + + " previousFireTime: '" + getPreviousFireTime() + + " nextFireTime: " + getNextFireTime() + " isRecovering: " + + isRecovering() + " refireCount: " + getRefireCount(); + } + + /** + * Returns the result (if any) that the Job set before its + * execution completed (the type of object set as the result is entirely up + * to the particular job). + * + *

+ * The result itself is meaningless to Quartz, but may be informative + * to {@link JobListener}s or + * {@link TriggerListener}s that are watching the job's + * execution. + *

+ * + * @return Returns the result. + */ + public Object getResult() { + return result; + } + + /** + * Set the result (if any) of the Job's execution (the type of + * object set as the result is entirely up to the particular job). + * + *

+ * The result itself is meaningless to Quartz, but may be informative + * to {@link JobListener}s or + * {@link TriggerListener}s that are watching the job's + * execution. + *

+ * + * @return Returns the result. + */ + public void setResult(Object result) { + this.result = result; + } + + /** + * The amount of time the job ran for (in milliseconds). The returned + * value will be -1 until the job has actually completed (or thrown an + * exception), and is therefore generally only useful to + * JobListeners and TriggerListeners. + * + * @return Returns the jobRunTime. + */ + public long getJobRunTime() { + return jobRunTime; + } + + /** + * @param jobRunTime The jobRunTime to set. + */ + public void setJobRunTime(long jobRunTime) { + this.jobRunTime = jobRunTime; + } + + /** + * Put the specified value into the context's data map with the given key. + * Possibly useful for sharing data between listeners and jobs. + * + *

NOTE: this data is volatile - it is lost after the job execution + * completes, and all TriggerListeners and JobListeners have been + * notified.

+ * + * @param key + * @param value + */ + public void put(Object key, Object value) { + data.put(key, value); + } + + /** + * Get the value with the given key from the context's data map. + * + * @param key + */ + public Object get(Object key) { + return data.get(key); + } +} Index: 3rdParty_sources/quartz/org/quartz/JobExecutionException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/JobExecutionException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/JobExecutionException.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,158 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +/** + *

+ * An exception that can be thrown by a {@link org.quartz.Job} + * to indicate to the Quartz {@link Scheduler} that an error + * occured while executing, and whether or not the Job requests + * to be re-fired immediately (using the same {@link JobExecutionContext}, + * or whether it wants to be unscheduled. + *

+ * + *

+ * Note that if the flag for 'refire immediately' is set, the flags for + * unscheduling the Job are ignored. + *

+ * + * @see Job + * @see JobExecutionContext + * @see SchedulerException + * + * @author James House + */ +public class JobExecutionException extends SchedulerException { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private boolean refire = false; + + private boolean unscheduleTrigg = false; + + private boolean unscheduleAllTriggs = false; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a JobExcecutionException, with the 're-fire immediately' flag set + * to false. + *

+ */ + public JobExecutionException() { + } + + /** + *

+ * Create a JobExcecutionException, with the given cause. + *

+ */ + public JobExecutionException(Exception cause) { + super(cause); + } + + /** + *

+ * Create a JobExcecutionException, with the given message. + *

+ */ + public JobExecutionException(String msg) { + super(msg); + } + + /** + *

+ * Create a JobExcecutionException with the 're-fire immediately' flag set + * to the given value. + *

+ */ + public JobExecutionException(boolean refireImmediately) { + refire = refireImmediately; + } + + /** + *

+ * Create a JobExcecutionException with the given underlying exception, and + * the 're-fire immediately' flag set to the given value. + *

+ */ + public JobExecutionException(Exception cause, boolean refireImmediately) { + super(cause); + + refire = refireImmediately; + } + + /** + *

+ * Create a JobExcecutionException with the given message, and underlying + * exception, and the 're-fire immediately' flag set to the given value. + *

+ */ + public JobExecutionException(String msg, Exception cause, + boolean refireImmediately) { + super(msg, cause); + + refire = refireImmediately; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public boolean refireImmediately() { + return refire; + } + + public void setUnscheduleFiringTrigger(boolean unscheduleTrigg) { + this.unscheduleTrigg = unscheduleTrigg; + } + + public boolean unscheduleFiringTrigger() { + return unscheduleTrigg; + } + + public void setUnscheduleAllTriggers(boolean unscheduleAllTriggs) { + this.unscheduleAllTriggs = unscheduleAllTriggs; + } + + public boolean unscheduleAllTriggers() { + return unscheduleAllTriggs; + } + +} Index: 3rdParty_sources/quartz/org/quartz/JobListener.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/JobListener.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/JobListener.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,96 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +/** + *

+ * The interface to be implemented by classes that want to be informed when a + * {@link org.quartz.JobDetail} executes. In general, + * applications that use a Scheduler will not have use for this + * mechanism. + *

+ * + * @see Scheduler + * @see Job + * @see JobExecutionContext + * @see JobExecutionException + * @see TriggerListener + * + * @author James House + */ +public interface JobListener { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Get the name of the JobListener. + *

+ */ + public String getName(); + + /** + *

+ * Called by the {@link Scheduler} when a {@link org.quartz.JobDetail} + * is about to be executed (an associated {@link Trigger} + * has occured). + *

+ * + *

+ * This method will not be invoked if the execution of the Job was vetoed + * by a {@link TriggerListener}. + *

+ * + * @see #jobExecutionVetoed(JobExecutionContext) + */ + public void jobToBeExecuted(JobExecutionContext context); + + /** + *

+ * Called by the {@link Scheduler} when a {@link org.quartz.JobDetail} + * was about to be executed (an associated {@link Trigger} + * has occured), but a {@link TriggerListener} vetoed it's + * execution. + *

+ * + * @see #jobToBeExecuted(JobExecutionContext) + */ + public void jobExecutionVetoed(JobExecutionContext context); + + + /** + *

+ * Called by the {@link Scheduler} after a {@link org.quartz.JobDetail} + * has been executed, and be for the associated Trigger's + * triggered(xx) method has been called. + *

+ */ + public void jobWasExecuted(JobExecutionContext context, + JobExecutionException jobException); + +} Index: 3rdParty_sources/quartz/org/quartz/JobPersistenceException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/JobPersistenceException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/JobPersistenceException.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,83 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +/** + *

+ * An exception that is thrown to indicate that there has been a failure in the + * scheduler's underlying persistence mechanism. + *

+ * + * @author James House + */ +public class JobPersistenceException extends SchedulerException { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a JobPersistenceException with the given message. + *

+ */ + public JobPersistenceException(String msg) { + super(msg); + setErrorCode(ERR_PERSISTENCE); + } + + /** + *

+ * Create a JobPersistenceException with the given message + * and error code. + *

+ */ + public JobPersistenceException(String msg, int errCode) { + super(msg, errCode); + } + + /** + *

+ * Create a JobPersistenceException with the given message + * and cause. + *

+ */ + public JobPersistenceException(String msg, Exception cause) { + super(msg, cause); + setErrorCode(ERR_PERSISTENCE); + } + + /** + *

+ * Create a JobPersistenceException with the given message, + * cause and error code. + *

+ */ + public JobPersistenceException(String msg, Exception cause, int errorCode) { + super(msg, cause, errorCode); + } + +} Index: 3rdParty_sources/quartz/org/quartz/NthIncludedDayTrigger.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/NthIncludedDayTrigger.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/NthIncludedDayTrigger.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,939 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +package org.quartz; + +import java.util.Date; + +import org.quartz.Calendar; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.quartz.Trigger; + +/** + * A trigger which fires on the Nth day of every interval type + * ({@link #INTERVAL_TYPE_WEEKLY}, {@link #INTERVAL_TYPE_MONTHLY} or + * {@link #INTERVAL_TYPE_YEARLY}) that is not excluded by the associated + * calendar. When determining what the Nth day of the month or year + * is, NthIncludedDayTrigger will skip excluded days on the + * associated calendar. This would commonly be used in an Nth + * business day situation, in which the user wishes to fire a particular job on + * the Nth business day (i.e. the 5th business day of + * every month). Each NthIncludedDayTrigger also has an associated + * fireAtTime which indicates at what time of day the trigger is + * to fire. + *

+ * All NthIncludedDayTriggers default to a monthly interval type + * (fires on the Nth day of every month) with N = 1 (first + * non-excluded day) and fireAtTime set to 12:00 PM (noon). These + * values can be changed using the {@link #setN}, {@link #setIntervalType}, and + * {@link #setFireAtTime} methods. Users may also want to note the + * {@link #setNextFireCutoffInterval} and {@link #getNextFireCutoffInterval} + * methods. + *

+ * Take, for example, the following calendar: + *

+ *

+ *        July                  August                September
+ * Su Mo Tu We Th Fr Sa   Su Mo Tu We Th Fr Sa   Su Mo Tu We Th Fr Sa
+ *                 1  W       1  2  3  4  5  W                1  2  W
+ *  W  H  5  6  7  8  W    W  8  9 10 11 12  W    W  H  6  7  8  9  W
+ *  W 11 12 13 14 15  W    W 15 16 17 18 19  W    W 12 13 14 15 16  W
+ *  W 18 19 20 21 22  W    W 22 23 24 25 26  W    W 19 20 21 22 23  W
+ *  W 25 26 27 28 29  W    W 29 30 31             W 26 27 28 29 30
+ *  W
+ * 
+ *

+ * Where W's represent weekend days, and H's represent holidays, all of which + * are excluded on a calendar associated with an + * NthIncludedDayTrigger with n=5 and + * intervalType=INTERVAL_TYPE_MONTHLY. In this case, the trigger + * would fire on the 8th of July (because of the July 4 holiday), + * the 5th of August, and the 8th of September (because + * of Labor Day). + * + * @author Aaron Craven + */ +public class NthIncludedDayTrigger extends Trigger { + + /** + * Instructs the Scheduler that upon a mis-fire situation, the + * NthIncludedDayTrigger wants to be fired now by the + * Scheduler + */ + public static final int MISFIRE_INSTRUCTION_FIRE_ONCE_NOW = 1; + + /** + * Instructs the Scheduler that upon a mis-fire situation, the + * NthIncludedDayTrigger wants to have + * nextFireTime updated to the next time in the schedule after + * the current time, but it does not want to be fired now. + */ + public static final int MISFIRE_INSTRUCTION_DO_NOTHING = 2; + + /** + * indicates a monthly trigger type (fires on the Nth included + * day of every month). + */ + public static final int INTERVAL_TYPE_MONTHLY = 1; + + /** + * indicates a yearly trigger type (fires on the Nth included + * day of every year). + */ + public static final int INTERVAL_TYPE_YEARLY = 2; + + /** + * indicates a weekly trigger type (fires on the Nth included + * day of every week). When using this interval type, care must be taken + * not to think of the value of n as an analog to + * java.util.Calendar.DAY_OF_WEEK. Such a comparison can only + * be drawn when there are no calendars associated with the trigger. To + * illustrate, consider an NthIncludedDayTrigger with + * n = 3 which is associated with a Calendar excluding + * non-weekdays. The trigger would fire on the 3rd + * included day of the week, which would be 4th + * actual day of the week. + */ + public static final int INTERVAL_TYPE_WEEKLY = 3; + + private Date startTime = new Date(); + private Date endTime; + private Date previousFireTime; + private Date nextFireTime; + private Calendar calendar; + + private int n = 1; + private int intervalType = INTERVAL_TYPE_MONTHLY; + private int fireAtHour = 12; + private int fireAtMinute = 0; + private int nextFireCutoffInterval = 12; + + /** + * Create an NthIncludedDayTrigger with no specified name, + * group, or JobDetail. This will result initially in a + * default monthly trigger that fires on the first day of every month at + * 12:00 PM (n=1, + * intervalType={@link #INTERVAL_TYPE_MONTHLY}, + * fireAtTime="12:00"). + *

+ * Note that setName(), setGroup(), + * setJobName(), and setJobGroup(), must be + * called before the NthIncludedDayTrigger can be placed into + * a Scheduler. + */ + public NthIncludedDayTrigger() { + super(); + } + + /** + * Create an NthIncludedDayTrigger with the given name and + * group but no specified JobDetail. This will result + * initially in a default monthly trigger that fires on the first day of + * every month at 12:00 PM (n=1, + * intervalType={@link #INTERVAL_TYPE_MONTHLY}, + * fireAtTime="12:00"). + *

+ * Note that setJobName() and setJobGroup() must + * be called before the NthIncludedDayTrigger can be placed + * into a Scheduler. + * + * @param name the name for the NthIncludedDayTrigger + * @param group the group for the NthIncludedDayTrigger + */ + public NthIncludedDayTrigger(String name, String group) { + super(name, group); + } + + /** + * Create an NthIncludedDayTrigger with the given name and + * group and the specified JobDetail. This will result + * initially in a default monthly trigger that fires on the first day of + * every month at 12:00 PM (n=1, + * intervalType={@link #INTERVAL_TYPE_MONTHLY}, + * fireAtTime="12:00"). + * + * @param name the name for the NthIncludedDayTrigger + * @param group the group for the NthIncludedDayTrigger + * @param jobName the name of the job to associate with the + * NthIncludedDayTrigger + * @param jobGroup the group containing the job to associate with the + * NthIncludedDayTrigger + */ + public NthIncludedDayTrigger(String name, String group, String jobName, + String jobGroup) { + super(name, group, jobName, jobGroup); + } + + /** + * Sets the day of the interval on which the + * NthIncludedDayTrigger should fire. If the Nth + * day of the interval does not exist (i.e. the 32nd of a + * month), the trigger simply will never fire. N may not be less than 1. + * + * @param n the day of the interval on which the trigger should fire. + * @throws java.lang.IllegalArgumentException + * the value entered for N was not valid (probably less than or + * equal to zero). + * @see #getN() + */ + public void setN(int n) { + if (n > 0) { + this.n = n; + } else { + throw new IllegalArgumentException("N must be greater than 0."); + } + } + + /** + * Returns the day of the interval on which the + * NthIncludedDayTrigger should fire. + * + * @return the value of n + * @see #setN(int) + */ + public int getN() { + return this.n; + } + + /** + * Sets the interval type for the NthIncludedDayTrigger. If + * {@link #INTERVAL_TYPE_MONTHLY}, the trigger will fire on the + * Nth included day of every month. If + * {@link #INTERVAL_TYPE_YEARLY}, the trigger will fire on the + * Nth included day of every year. If + * {@link #INTERVAL_TYPE_WEEKLY}, the trigger will fire on the + * Nth included day of every week. + * + * @param intervalType the interval type for the trigger + * @throws java.lang.IllegalArgumentException + * the value of intervalType is not valid. Valid + * values are represented by the INTERVAL_TYPE_WEEKLY, + * INTERVAL_TYPE_MONTHLY and INTERVAL_TYPE_YEARLY constants. + * @see #getIntervalType() + * @see #INTERVAL_TYPE_WEEKLY + * @see #INTERVAL_TYPE_MONTHLY + * @see #INTERVAL_TYPE_YEARLY + */ + public void setIntervalType(int intervalType) { + switch (intervalType) { + case INTERVAL_TYPE_WEEKLY: + this.intervalType = intervalType; + break; + case INTERVAL_TYPE_MONTHLY: + this.intervalType = intervalType; + break; + case INTERVAL_TYPE_YEARLY: + this.intervalType = intervalType; + break; + default: + throw new IllegalArgumentException("Invalid Interval Type:" + + intervalType); + } + } + + /** + * Returns the interval type for the NthIncludedDayTrigger. + * + * @return the trigger's interval type + * @see #setIntervalType(int) + * @see #INTERVAL_TYPE_WEEKLY + * @see #INTERVAL_TYPE_MONTHLY + * @see #INTERVAL_TYPE_YEARLY + */ + public int getIntervalType() { + return this.intervalType; + } + + /** + * Sets the fire time for the NthIncludedDayTrigger, which + * should be represented as a string with the format "HH:MM", + * with HH representing the 24-hour clock hour of the fire time. Hours can + * be represented as either a one-digit or two-digit number. + * + * @param fireAtTime the time at which the trigger should fire + * @throws java.lang.IllegalArgumentException + * the specified value for fireAtTime could not be + * successfully parsed into a valid time of day. + * @see #getFireAtTime() + */ + public void setFireAtTime(String fireAtTime) { + int fireHour = 12; + int fireMinute = 0; + String[] components; + + try { + int i = fireAtTime.indexOf(":"); + fireHour = Integer.parseInt(fireAtTime.substring(0, i)); + fireMinute = Integer.parseInt(fireAtTime.substring(i+1)); + } catch (Exception e) { + fireHour = 12; + fireMinute = 0; + throw new + IllegalArgumentException("Could not parse time expression: " + + e.getMessage()); + } finally { + this.fireAtHour = fireHour; + this.fireAtMinute = fireMinute; + } + } + + /** + * Returns the fire time for the NthIncludedDayTrigger as a + * string with the format "HH:MM", with HH representing the + * 24-hour clock hour of the fire time. + * + * @return the fire time for the trigger + * @see #setFireAtTime(String) + */ + public String getFireAtTime() { + return this.fireAtHour + ":" + this.fireAtMinute; + } + + /** + * Sets the nextFireCutoffInterval for the + * NthIncludedDayTrigger. + *

+ * Because of the conceptual design of NthIncludedDayTrigger, + * it is not always possible to decide with certainty that the trigger + * will never fire again. Therefore, it will search for the next + * fire time up to a given cutoff. These cutoffs can be changed by using the + * {@link #setNextFireCutoffInterval(int)} and + * {@link #getNextFireCutoffInterval()} methods. The default cutoff is 12 + * of the intervals specified by {@link #getIntervalType() + * intervalType}. + *

+ * In most cases, the default value of this setting (12) is sufficient (it + * is highly unlikely, for example, that you will need to look at more than + * 12 months of dates to ensure that your trigger will never fire again). + * However, this setting is included to allow for the rare exceptions where + * this might not be true. + *

+ * For example, if your trigger is associated with a calendar that excludes + * a great many dates in the next 12 months, and hardly any following that, + * it is possible (if n is large enough) that you could run + * into this situation. + * + * @param nextFireCutoffInterval the desired cutoff interval + * @see #getNextFireCutoffInterval() + * @see #getNextFireTime() + */ + public void setNextFireCutoffInterval(int nextFireCutoffInterval) { + this.nextFireCutoffInterval = nextFireCutoffInterval; + } + + /** + * Returns the nextFireCutoffInterval for the + * NthIncludedDayTrigger. + *

+ * Because of the conceptual design of NthIncludedDayTrigger, + * it is not always possible to decide with certainty that the trigger + * will never fire again. Therefore, it will search for the next + * fire time up to a given cutoff. These cutoffs can be changed by using the + * {@link #setNextFireCutoffInterval(int)} and + * {@link #getNextFireCutoffInterval()} methods. The default cutoff is 12 + * of the intervals specified by {@link #getIntervalType() + * intervalType}. + * + * @return the chosen cutoff interval + * @see #setNextFireCutoffInterval(int) + * @see #getNextFireTime() + */ + public int getNextFireCutoffInterval() { + return this.nextFireCutoffInterval; + } + + /** + * Sets the date/time on which the trigger may begin firing. This defines + * the initial boundary for trigger firings — the trigger will not + * fire prior to this date and time. Defaults to the current date and time + * when the NthIncludedDayTrigger is created. + * + * @param startTime the initial boundary for trigger firings + * @throws java.lang.IllegalArgumentException + * the specified start time is after the current end time or is + * null + * @see #getStartTime() + */ + public void setStartTime(Date startTime) { + if (startTime == null) { + throw new IllegalArgumentException("Start time may not be null"); + } + if ((this.endTime != null) && endTime.before(startTime)) { + throw new IllegalArgumentException("Start time must be before end time."); + } + this.startTime = startTime; + } + + /** + * Returns the date/time on which the trigger may begin firing. This + * defines the initial boundary for trigger firings — the trigger + * will not fire prior to this date and time. + * + * @return the initial date/time on which the trigger may begin firing + * @see #setStartTime(Date) + */ + public Date getStartTime() { + return this.startTime; + } + + /** + * Sets the date/time on which the trigger must stop firing. This defines + * the final boundary for trigger firings — the trigger will not + * fire after to this date and time. If this value is null, no end time + * boundary is assumed, and the trigger can continue indefinitely. + * + * @param endTime the final boundary for trigger firings + * @throws java.lang.IllegalArgumentException + * the specified end time is before the current start time + * @see #getEndTime() + */ + public void setEndTime(Date endTime) { + if ((endTime != null) && endTime.before(startTime)) { + throw new IllegalArgumentException("End time must be after start time."); + } + this.endTime = endTime; + } + + /** + * Returns the date/time on which the trigger must stop firing. This + * defines the final boundary for trigger firings — the trigger will + * not fire after to this date and time. If this value is null, no end time + * boundary is assumed, and the trigger can continue indefinitely. + * + * @return the date/time on which the trigger must stop firing + * @see #setEndTime(Date) + */ + public Date getEndTime() { + return this.endTime; + } + + /** + * Returns the next time at which the NthIncludedDayTrigger + * will fire. If the trigger will not fire again, null will be + * returned. + *

+ * Because of the conceptual design of NthIncludedDayTrigger, + * it is not always possible to decide with certainty that the trigger + * will never fire again. Therefore, it will search for the next + * fire time up to a given cutoff. These cutoffs can be changed by using the + * {@link #setNextFireCutoffInterval(int)} and + * {@link #getNextFireCutoffInterval()} methods. The default cutoff is 12 + * of the intervals specified by {@link #getIntervalType() + * intervalType}. + *

+ * The returned value is not guaranteed to be valid until after + * the trigger has been added to the scheduler. + * + * @return the next fire time for the trigger + * @see #getNextFireCutoffInterval() + * @see #setNextFireCutoffInterval(int) + * @see #getFireTimeAfter(Date) + */ + public Date getNextFireTime() { + return this.nextFireTime; + } + + /** + * Returns the previous time at which the + * NthIncludedDayTrigger fired. If the trigger has not yet + * fired, null will be returned. + * + * @return the previous fire time for the trigger + */ + public Date getPreviousFireTime() { + return this.previousFireTime; + } + + /** + * Returns the first time the NthIncludedDayTrigger will fire + * after the specified date. + *

+ * Because of the conceptual design of NthIncludedDayTrigger, + * it is not always possible to decide with certainty that the trigger + * will never fire again. Therefore, it will search for the next + * fire time up to a given cutoff. These cutoffs can be changed by using the + * {@link #setNextFireCutoffInterval(int)} and + * {@link #getNextFireCutoffInterval()} methods. The default cutoff is 12 + * of the intervals specified by {@link #getIntervalType() + * intervalType}. + *

+ * Therefore, for triggers with intervalType = + * {@link NthIncludedDayTrigger#INTERVAL_TYPE_WEEKLY + * INTERVAL_TYPE_WEEKLY}, if the trigger will not fire within 12 + * weeks after the given date/time, null will be returned. For + * triggers with intervalType = + * {@link NthIncludedDayTrigger#INTERVAL_TYPE_MONTHLY + * INTERVAL_TYPE_MONTHLY}, if the trigger will not fire within 12 + * months after the given date/time, null will be returned. + * For triggers with intervalType = + * {@link NthIncludedDayTrigger#INTERVAL_TYPE_YEARLY + * INTERVAL_TYPE_YEARLY}, if the trigger will not fire within 12 + * years after the given date/time, null will be returned. In + * all cases, if the trigger will not fire before endTime, + * null will be returned. + * + * @param afterTime The time after which to find the nearest fire time. + * This argument is treated as exclusive — that is, + * if afterTime is a valid fire time for the trigger, it + * will not be returned as the next fire time. + * @return the first time the trigger will fire following the specified + * date + */ + public Date getFireTimeAfter(Date afterTime) { + if (afterTime == null) { + afterTime = new Date(); + } + + if (afterTime.before(this.startTime)) { + afterTime = new Date(startTime.getTime() - 1000l); + } + + if (this.intervalType == INTERVAL_TYPE_WEEKLY) { + return getWeeklyFireTimeAfter(afterTime); + } else if (this.intervalType == INTERVAL_TYPE_MONTHLY) { + return getMonthlyFireTimeAfter(afterTime); + } else if (this.intervalType == INTERVAL_TYPE_YEARLY) { + return getYearlyFireTimeAfter(afterTime); + } else { + return null; + } + } + + /** + * Returns the last time the NthIncludedDayTrigger will fire. + * If the trigger will not fire at any point between startTime + * and endTime, null will be returned. + * + * @return the last time the trigger will fire. + */ + public Date getFinalFireTime() { + Date finalTime = null; + java.util.Calendar currCal = java.util.Calendar.getInstance(); + currCal.setTime(this.endTime); + + while ((finalTime == null) + && (this.startTime.before(currCal.getTime()))) { + currCal.add(java.util.Calendar.DATE, -1); + + finalTime = getFireTimeAfter(currCal.getTime()); + } + + return finalTime; + } + + /** + * Called when the Scheduler has decided to 'fire' the trigger + * (execute the associated Job), in order to give the + * Trigger a chance to update itself for its next triggering + * (if any). + */ + public void triggered(Calendar calendar) { + this.calendar = calendar; + this.previousFireTime = this.nextFireTime; + this.nextFireTime = getFireTimeAfter(this.nextFireTime); + } + + /** + * Called by the scheduler at the time a Trigger is first + * added to the scheduler, in order to have the Trigger + * compute its first fire time, based on any associated calendar. + *

+ * After this method has been called, getNextFireTime() + * should return a valid answer. + *

+ * + * @return the first time at which the Trigger will be fired + * by the scheduler, which is also the same value + * {@link #getNextFireTime()} will return (until after the first + * firing of the Trigger). + */ + public Date computeFirstFireTime(Calendar calendar) { + this.calendar = calendar; + this.nextFireTime = + getFireTimeAfter(new Date(this.startTime.getTime() - 1000l)); + + return this.nextFireTime; + } + + /** + * Called after the Scheduler has executed the + * JobDetail associated with the Trigger in order + * to get the final instruction code from the trigger. + * + * @param jobCtx the JobExecutionContext that was used by the + * Job's execute() method. + * @param result the JobExecutionException thrown by the + * Job, if any (may be null) + * @return one of the Trigger.INSTRUCTION_XXX constants. + */ + public int executionComplete(JobExecutionContext jobCtx, + JobExecutionException result) { + if (result != null && result.refireImmediately()) + return INSTRUCTION_RE_EXECUTE_JOB; + + if (result != null && result.unscheduleFiringTrigger()) + return INSTRUCTION_SET_TRIGGER_COMPLETE; + + if (result != null && result.unscheduleAllTriggers()) + return INSTRUCTION_SET_ALL_JOB_TRIGGERS_COMPLETE; + + if (!mayFireAgain()) return INSTRUCTION_DELETE_TRIGGER; + + return INSTRUCTION_NOOP; + } + + /** + * Used by the Scheduler to determine whether or not it is + * possible for this Trigger to fire again. + *

+ * If the returned value is false then the + * Scheduler may remove the Trigger from the + * JobStore + * + * @return a boolean indicator of whether the trigger could potentially fire + * again + */ + public boolean mayFireAgain() { + return (getNextFireTime() == null); + } + + /** + * Indicates whether misfireInstruction is a valid misfire + * instruction for this Trigger. + * + * @return whether misfireInstruction is valid. + */ + protected boolean validateMisfireInstruction(int misfireInstruction) { + if ((misfireInstruction == MISFIRE_INSTRUCTION_SMART_POLICY) || + (misfireInstruction == MISFIRE_INSTRUCTION_DO_NOTHING) || + (misfireInstruction == MISFIRE_INSTRUCTION_FIRE_ONCE_NOW)) { + return true; + } else { + return false; + } + } + + /** + * Updates the NthIncludedDayTrigger's state based on the + * MISFIRE_INSTRUCTION_XXX that was selected when the + * NthIncludedDayTrigger was created + *

+ * If the misfire instruction is set to MISFIRE_INSTRUCTION_SMART_POLICY, + * then the instruction will be interpreted as + * {@link #MISFIRE_INSTRUCTION_FIRE_ONCE_NOW}. + * + * @param calendar a new or updated calendar to use for the trigger + */ + public void updateAfterMisfire(Calendar calendar) { + int instruction = getMisfireInstruction(); + + this.calendar = calendar; + + if (instruction == MISFIRE_INSTRUCTION_SMART_POLICY) { + instruction = MISFIRE_INSTRUCTION_FIRE_ONCE_NOW; + } + + if (instruction == MISFIRE_INSTRUCTION_DO_NOTHING) { + this.nextFireTime = getFireTimeAfter(new Date()); + } else if (instruction == MISFIRE_INSTRUCTION_FIRE_ONCE_NOW) { + this.nextFireTime = new Date(); + } + } + + /** + * Updates the NthIncludedDayTrigger's state based on the + * given new version of the associated Calendar. + * + * @param calendar a new or updated calendar to use for the trigger + * @param misfireThreshold the amount of time (in milliseconds) that must + * be between "now" and the time the next + * firing of the trigger is supposed to occur. + */ + public void updateWithNewCalendar(Calendar calendar, + long misfireThreshold) { + Date now = new Date(); + long diff; + + this.calendar = calendar; + this.nextFireTime = getFireTimeAfter(this.previousFireTime); + + if ((this.nextFireTime != null) && (this.nextFireTime.before(now))) { + diff = now.getTime() - this.nextFireTime.getTime(); + if (diff >= misfireThreshold) { + this.nextFireTime = getFireTimeAfter(this.nextFireTime); + } + } + } + + /** + * Calculates the first time an NthIncludedDayTrigger with + * intervalType = {@link #INTERVAL_TYPE_WEEKLY} will fire + * after the specified date. See {@link #getNextFireTime} for more + * information. + * + * @param afterDate The time after which to find the nearest fire time. + * This argument is treated as exclusive — that is, + * if afterTime is a valid fire time for the trigger, it + * will not be returned as the next fire time. + * @return the first time the trigger will fire following the specified + * date + */ + private Date getWeeklyFireTimeAfter(Date afterDate) { + int currN = 0; + java.util.Calendar afterCal; + java.util.Calendar currCal; + int currWeek; + int weekCount = 0; + boolean gotOne = false; + + afterCal = java.util.Calendar.getInstance(); + afterCal.setTime(afterDate); + + currCal = java.util.Calendar.getInstance(); + currCal.set(afterCal.get(java.util.Calendar.YEAR), + afterCal.get(java.util.Calendar.MONTH), + afterCal.get(java.util.Calendar.DAY_OF_MONTH)); + + //move to the first day of the week (SUNDAY) + currCal.add(java.util.Calendar.DAY_OF_MONTH, + (afterCal.get(java.util.Calendar.DAY_OF_WEEK) - 1) * -1); + + currCal.set(java.util.Calendar.HOUR_OF_DAY, this.fireAtHour); + currCal.set(java.util.Calendar.MINUTE, this.fireAtMinute); + currCal.set(java.util.Calendar.SECOND, 0); + currCal.set(java.util.Calendar.MILLISECOND, 0); + + currWeek = currCal.get(java.util.Calendar.WEEK_OF_YEAR); + + while ((!gotOne) && (weekCount < this.nextFireCutoffInterval)) { + while ((currN != this.n) && (weekCount < 12)) { + //if we move into a new month, reset the current "n" counter + if (currCal.get(java.util.Calendar.WEEK_OF_YEAR) != currWeek) { + currN = 0; + weekCount++; + currWeek = currCal.get(java.util.Calendar.WEEK_OF_YEAR); + } + + //treating a null calendar as an all-inclusive calendar, + // increment currN if the current date being tested is included + // on the calendar + if ((calendar == null) + || (calendar.isTimeIncluded(currCal.getTime().getTime()))) { + currN++; + } + + if (currN != this.n) { + currCal.add(java.util.Calendar.DATE, 1); + } + + //if we pass endTime, drop out and return null. + if ((this.endTime != null) + && (currCal.getTime().after(this.endTime))) { + return null; + } + } + + //We found an "n" or we've checked the requisite number of weeks. + // If we've found an "n", is it the right one? -- that is, we could + // be looking at an nth day PRIOR to afterDate + if (currN == this.n) { + if (afterDate.before(currCal.getTime())) { + gotOne = true; + } else { //resume checking on the first day of the next week + currCal.add(java.util.Calendar.DAY_OF_MONTH, -1 * (currN - 1)); + currCal.add(java.util.Calendar.DAY_OF_MONTH, 7); + currN = 0; + } + } + } + + if (weekCount < this.nextFireCutoffInterval) { + return currCal.getTime(); + } else { + return null; + } + } + + /** + * Calculates the first time an NthIncludedDayTrigger with + * intervalType = {@link #INTERVAL_TYPE_MONTHLY} will fire + * after the specified date. See {@link #getNextFireTime} for more + * information. + * + * @param afterDate The time after which to find the nearest fire time. + * This argument is treated as exclusive — that is, + * if afterTime is a valid fire time for the trigger, it + * will not be returned as the next fire time. + * @return the first time the trigger will fire following the specified + * date + */ + private Date getMonthlyFireTimeAfter(Date afterDate) { + int currN = 0; + java.util.Calendar afterCal; + java.util.Calendar currCal; + int currMonth; + int monthCount = 0; + boolean gotOne = false; + + afterCal = java.util.Calendar.getInstance(); + afterCal.setTime(afterDate); + + currCal = java.util.Calendar.getInstance(); + currCal.set(afterCal.get(java.util.Calendar.YEAR), + afterCal.get(java.util.Calendar.MONTH), 1); + currCal.set(java.util.Calendar.HOUR_OF_DAY, this.fireAtHour); + currCal.set(java.util.Calendar.MINUTE, this.fireAtMinute); + currCal.set(java.util.Calendar.SECOND, 0); + currCal.set(java.util.Calendar.MILLISECOND, 0); + + currMonth = currCal.get(java.util.Calendar.MONTH); + + while ((!gotOne) && (monthCount < this.nextFireCutoffInterval)) { + while ((currN != this.n) && (monthCount < 12)) { + //if we move into a new month, reset the current "n" counter + if (currCal.get(java.util.Calendar.MONTH) != currMonth) { + currN = 0; + monthCount++; + currMonth = currCal.get(java.util.Calendar.MONTH); + } + + //treating a null calendar as an all-inclusive calendar, + // increment currN if the current date being tested is included + // on the calendar + if ((calendar == null) + || (calendar.isTimeIncluded(currCal.getTime().getTime()))) { + currN++; + } + + if (currN != this.n) { + currCal.add(java.util.Calendar.DATE, 1); + } + + //if we pass endTime, drop out and return null. + if ((this.endTime != null) + && (currCal.getTime().after(this.endTime))) { + return null; + } + } + + //We found an "n" or we've checked the requisite number of months. + // If we've found an "n", is it the right one? -- that is, we could + // be looking at an nth day PRIOR to afterDate + if (currN == this.n) { + if (afterDate.before(currCal.getTime())) { + gotOne = true; + } else { //resume checking on the first day of the next month + currCal.set(java.util.Calendar.DAY_OF_MONTH, 1); + currCal.add(java.util.Calendar.MONTH, 1); + currN = 0; + } + } + } + + if (monthCount < this.nextFireCutoffInterval) { + return currCal.getTime(); + } else { + return null; + } + } + + /** + * Calculates the first time an NthIncludedDayTrigger with + * intervalType = {@link #INTERVAL_TYPE_YEARLY} will fire + * after the specified date. See {@link #getNextFireTime} for more + * information. + * + * @param afterDate The time after which to find the nearest fire time. + * This argument is treated as exclusive — that is, + * if afterTime is a valid fire time for the trigger, it + * will not be returned as the next fire time. + * @return the first time the trigger will fire following the specified + * date + */ + private Date getYearlyFireTimeAfter(Date afterDate) { + int currN = 0; + java.util.Calendar afterCal; + java.util.Calendar currCal; + int currYear; + int yearCount = 0; + boolean gotOne = false; + + afterCal = java.util.Calendar.getInstance(); + afterCal.setTime(afterDate); + + currCal = java.util.Calendar.getInstance(); + currCal.set(afterCal.get(java.util.Calendar.YEAR), + java.util.Calendar.JANUARY, 1); + currCal.set(java.util.Calendar.HOUR_OF_DAY, this.fireAtHour); + currCal.set(java.util.Calendar.MINUTE, this.fireAtMinute); + currCal.set(java.util.Calendar.SECOND, 0); + currCal.set(java.util.Calendar.MILLISECOND, 0); + + currYear = currCal.get(java.util.Calendar.YEAR); + + while ((!gotOne) && (yearCount < this.nextFireCutoffInterval)) { + while ((currN != this.n) && (yearCount < 5)) { + //if we move into a new year, reset the current "n" counter + if (currCal.get(java.util.Calendar.YEAR) != currYear) { + currN = 0; + yearCount++; + currYear = currCal.get(java.util.Calendar.YEAR); + } + + //treating a null calendar as an all-inclusive calendar, + // increment currN if the current date being tested is included + // on the calendar + if ((calendar == null) + || (calendar.isTimeIncluded(currCal.getTime().getTime()))) { + currN++; + } + + if (currN != this.n) { + currCal.add(java.util.Calendar.DATE, 1); + } + + //if we pass endTime, drop out and return null. + if ((this.endTime != null) + && (currCal.getTime().after(this.endTime))) { + return null; + } + } + + //We found an "n" or we've checked the requisite number of years. + // If we've found an "n", is it the right one? -- that is, we + // could be looking at an nth day PRIOR to afterDate + if (currN == this.n) { + if (afterDate.before(currCal.getTime())) { + gotOne = true; + } else { //resume checking on the first day of the next year + currCal.set(java.util.Calendar.DAY_OF_MONTH, 1); + currCal.set(java.util.Calendar.MONTH, + java.util.Calendar.JANUARY); + currCal.add(java.util.Calendar.YEAR, 1); + currN = 0; + } + } + } + + if (yearCount < this.nextFireCutoffInterval) { + return currCal.getTime(); + } else { + return null; + } + } +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/ObjectAlreadyExistsException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/ObjectAlreadyExistsException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/ObjectAlreadyExistsException.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,89 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +/** + *

+ * An exception that is thrown to indicate that an attempt to store a new + * object (i.e. {@link org.quartz.JobDetail},{@link Trigger} + * or {@link Calendar}) in a {@link Scheduler} + * failed, because one with the same name & group already exists. + *

+ * + * @author James House + */ +public class ObjectAlreadyExistsException extends JobPersistenceException { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a ObjectAlreadyExistsException with the given + * message. + *

+ */ + public ObjectAlreadyExistsException(String msg) { + super(msg); + } + + /** + *

+ * Create a ObjectAlreadyExistsException and auto-generate a + * message using the name/group from the given JobDetail. + *

+ * + *

+ * The message will read:
"Unable to store Job with name: '__' and + * group: '__', because one already exists with this identification." + *

+ */ + public ObjectAlreadyExistsException(JobDetail offendingJob) { + super("Unable to store Job with name: '" + offendingJob.getName() + + "' and group: '" + offendingJob.getGroup() + + "', because one already exists with this identification."); + } + + /** + *

+ * Create a ObjectAlreadyExistsException and auto-generate a + * message using the name/group from the given Trigger. + *

+ * + *

+ * The message will read:
"Unable to store Trigger with name: '__' and + * group: '__', because one already exists with this identification." + *

+ */ + public ObjectAlreadyExistsException(Trigger offendingTrigger) { + super("Unable to store Trigger with name: '" + + offendingTrigger.getName() + "' and group: '" + + offendingTrigger.getGroup() + + "', because one already exists with this identification."); + } + +} Index: 3rdParty_sources/quartz/org/quartz/Scheduler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/Scheduler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/Scheduler.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,977 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import java.util.Date; +import java.util.List; +import java.util.Set; + +import org.quartz.spi.JobFactory; + +/** + *

+ * This is the main interface of a Quartz Scheduler. + *

+ * + *

+ * A Scheduler maintains a registery of {@link org.quartz.JobDetail} + * s and {@link Trigger}s. Once registered, the Scheduler + * is responible for executing Job s when their associated + * Trigger s fire (when their scheduled time arrives). + *

+ * + *

+ * Scheduler instances are produced by a {@link SchedulerFactory}. + * A scheduler that has already been created/initialized can be found and used + * through the same factory that produced it. After a Scheduler + * has been created, it is in "stand-by" mode, and must have its + * start() method called before it will fire any Jobs. + *

+ * + *

+ * Job s are to be created by the 'client program', by defining + * a class that implements the {@link org.quartz.Job} + * interface. {@link JobDetail} objects are then created (also + * by the client) to define a individual instances of the Job. + * JobDetail instances can then be registered with the Scheduler + * via the scheduleJob(JobDetail, Trigger) or addJob(JobDetail, boolean) + * method. + *

+ * + *

+ * Trigger s can then be defined to fire individual Job + * instances based on given schedules. SimpleTrigger s are most + * useful for one-time firings, or firing at an exact moment in time, with N + * repeats with a given delay between them. CronTrigger s allow + * scheduling based on time of day, day of week, day of month, and month of + * year. + *

+ * + *

+ * Job s and Trigger s have a name and group + * associated with them, which should uniquely identify them within a single + * {@link Scheduler}. The 'group' feature may be useful for + * creating logical groupings or categorizations of Jobs s and + * Triggerss. If you don't have need for assigning a group to a + * given Jobs of Triggers, then you can use the + * DEFAULT_GROUP constant defined on this interface. + *

+ * + *

+ * Stored Job s can also be 'manually' triggered through the use + * of the triggerJob(String jobName, String jobGroup) function. + *

+ * + *

+ * Client programs may also be interested in the 'listener' interfaces that are + * available from Quartz. The {@link JobListener} interface + * provides notifications of Job executions. The {@link TriggerListener} + * interface provides notifications of Trigger firings. The + * {@link SchedulerListener} interface provides notifications of + * Scheduler events and errors. + *

+ * + *

+ * The setup/configuration of a Scheduler instance is very + * customizable. Please consult the documentation distributed with Quartz. + *

+ * + * @see Job + * @see JobDetail + * @see Trigger + * @see JobListener + * @see TriggerListener + * @see SchedulerListener + * + * @author James House + * @author Sharada Jambula + */ +public interface Scheduler { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * A (possibly) usefull constant that can be used for specifying the group + * that Job and Trigger instances belong to. + *

+ */ + public static final String DEFAULT_GROUP = "DEFAULT"; + + /** + *

+ * A constant Trigger group name used internally by the + * scheduler - clients should not use the value of this constant + * ("MANUAL_TRIGGER") for thename of a Trigger's group. + *

+ */ + public static final String DEFAULT_MANUAL_TRIGGERS = "MANUAL_TRIGGER"; + + /** + *

+ * A constant Trigger group name used internally by the + * scheduler - clients should not use the value of this constant + * ("RECOVERING_JOBS") for thename of a Trigger's group. + *

+ */ + public static final String DEFAULT_RECOVERY_GROUP = "RECOVERING_JOBS"; + + /** + *

+ * A constant Trigger group name used internally by the + * scheduler - clients should not use the value of this constant + * ("FAILED_OVER_JOBS") for thename of a Trigger's group. + *

+ */ + public static final String DEFAULT_FAIL_OVER_GROUP = "FAILED_OVER_JOBS"; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Returns the name of the Scheduler. + *

+ */ + public String getSchedulerName() throws SchedulerException; + + /** + *

+ * Returns the instance Id of the Scheduler. + *

+ */ + public String getSchedulerInstanceId() throws SchedulerException; + + /** + *

+ * Returns the SchedulerContext of the Scheduler. + *

+ */ + public SchedulerContext getContext() throws SchedulerException; + + /////////////////////////////////////////////////////////////////////////// + /// + /// Schedululer State Management Methods + /// + /////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Starts the Scheduler's threads that fire {@link Trigger}s. + * When a scheduler is first created it is in "stand-by" mode, and will not + * fire triggers. The scheduler can also be put into stand-by mode by + * calling the standby() method. + *

+ * + *

+ * The misfire/recovery process will be started, if it is the initial call + * to this method on this scheduler instance. + *

+ * + * @throws SchedulerException + * if shutdown() has been called, or there is an + * error within the Scheduler. + * + * @see #standby + * @see #shutdown + */ + public void start() throws SchedulerException; + + /** + *

+ * Temporarily halts the Scheduler's firing of {@link Trigger}s. + *

+ * + *

+ * When start() is called (to bring the scheduler out of + * stand-by mode), trigger misfire instructions will NOT be applied + * during the execution of the start() method - any misfires + * will be detected immediately afterward (by the JobStore's + * normal process). + *

+ * + *

+ * The scheduler is not destroyed, and can be re-started at any time. + *

+ * + * @see #start() + * @see #pauseAll() + */ + public void standby() throws SchedulerException; + + /** + * @deprecated replaced by better-named standby() method. + * @see #standby() + */ + public void pause() throws SchedulerException; + + /** + *

+ * Reports whether the Scheduler is in stand-by mode. + *

+ * + * @see #standby() + * @see #start() + */ + public boolean isInStandbyMode() throws SchedulerException; + + /** + * @deprecated + * @see #isInStandbyMode() + */ + public boolean isPaused() throws SchedulerException; + + /** + *

+ * Halts the Scheduler's firing of {@link Trigger}s, + * and cleans up all resources associated with the Scheduler. Equivalent to + * shutdown(false). + *

+ * + *

+ * The scheduler cannot be re-started. + *

+ * + * @see #shutdown(boolean) + */ + public void shutdown() throws SchedulerException; + + /** + *

+ * Halts the Scheduler's firing of {@link Trigger}s, + * and cleans up all resources associated with the Scheduler. + *

+ * + *

+ * The scheduler cannot be re-started. + *

+ * + * @param waitForJobsToComplete + * if true the scheduler will not allow this method + * to return until all currently executing jobs have completed. + * + * @see #shutdown + */ + public void shutdown(boolean waitForJobsToComplete) + throws SchedulerException; + + /** + *

+ * Reports whether the Scheduler has been shutdown. + *

+ */ + public boolean isShutdown() throws SchedulerException; + + /** + *

+ * Get a SchedulerMetaData object describiing the settings + * and capabilities of the scheduler instance. + *

+ * + *

+ * Note that the data returned is an 'instantaneous' snap-shot, and that as + * soon as it's returned, the meta data values may be different. + *

+ */ + public SchedulerMetaData getMetaData() throws SchedulerException; + + /** + *

+ * Return a list of JobExecutionContext objects that + * represent all currently executing Jobs. + *

+ * + *

+ * Note that the list returned is an 'instantaneous' snap-shot, and that as + * soon as it's returned, the true list of executing jobs may be different. + * Also please read the doc associated with JobExecutionContext- + * especially if you're using RMI. + *

+ * + * @see JobExecutionContext + */ + public List getCurrentlyExecutingJobs() throws SchedulerException; + + /** + *

+ * Set the JobFactory that will be responsible for producing + * instances of Job classes. + *

+ * + *

+ * JobFactories may be of use to those wishing to have their application + * produce Job instances via some special mechanism, such as to + * give the opertunity for dependency injection. + *

+ * + * @see org.quart.spi.JobFactory + * @throws SchedulerException + */ + public void setJobFactory(JobFactory factory) throws SchedulerException; + + /////////////////////////////////////////////////////////////////////////// + /// + /// Scheduling-related Methods + /// + /////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Add the given {@link org.quartz.JobDetail} to the + * Scheduler, and associate the given {@link Trigger} with + * it. + *

+ * + *

+ * If the given Trigger does not reference any Job, then it + * will be set to reference the Job passed with it into this method. + *

+ * + * @throws SchedulerException + * if the Job or Trigger cannot be added to the Scheduler, or + * there is an internal Scheduler error. + */ + public Date scheduleJob(JobDetail jobDetail, Trigger trigger) + throws SchedulerException; + + /** + *

+ * Schedule the given {@link org.quartz.Trigger} with the + * Job identified by the Trigger's settings. + *

+ * + * @throws SchedulerException + * if the indicated Job does not exist, or the Trigger cannot be + * added to the Scheduler, or there is an internal Scheduler + * error. + */ + public Date scheduleJob(Trigger trigger) throws SchedulerException; + + /** + *

+ * Remove the indicated {@link Trigger} from the scheduler. + *

+ */ + public boolean unscheduleJob(String triggerName, String groupName) + throws SchedulerException; + + /** + *

+ * Remove (delete) the {@link org.quartz.Trigger} with the + * given name, and store the new given one - which must be associated + * with the same job (the new trigger must have the job name & group specified) + * - however, the new trigger need not have the same name as the old trigger. + *

+ * + * @param triggerName + * The name of the Trigger to be replaced. + * @param groupName + * The group name of the Trigger to be replaced. + * @param newTrigger + * The new Trigger to be stored. + * @return null if a Trigger with the given + * name & group was not found and removed from the store, otherwise + * the first fire time of the newly scheduled trigger. + */ + public Date rescheduleJob(String triggerName, + String groupName, Trigger newTrigger) throws SchedulerException; + + + /** + *

+ * Add the given Job to the Scheduler - with no associated + * Trigger. The Job will be 'dormant' until + * it is scheduled with a Trigger, or Scheduler.triggerJob() + * is called for it. + *

+ * + *

+ * The Job must by definition be 'durable', if it is not, + * SchedulerException will be thrown. + *

+ * + * @throws SchedulerException + * if there is an internal Scheduler error, or if the Job is not + * durable, or a Job with the same name already exists, and + * replace is false. + */ + public void addJob(JobDetail jobDetail, boolean replace) + throws SchedulerException; + + /** + *

+ * Delete the identified Job from the Scheduler - and any + * associated Triggers. + *

+ * + * @return true if the Job was found and deleted. + * @throws SchedulerException + * if there is an internal Scheduler error. + */ + public boolean deleteJob(String jobName, String groupName) + throws SchedulerException; + + /** + *

+ * Trigger the identified {@link org.quartz.JobDetail} + * (execute it now) - the generated trigger will be non-volatile. + *

+ */ + public void triggerJob(String jobName, String groupName) + throws SchedulerException; + + /** + *

+ * Trigger the identified {@link org.quartz.JobDetail} + * (execute it now) - the generated trigger will be volatile. + *

+ */ + public void triggerJobWithVolatileTrigger(String jobName, String groupName) + throws SchedulerException; + + /** + *

+ * Trigger the identified {@link org.quartz.JobDetail} + * (execute it now) - the generated trigger will be non-volatile. + *

+ * + * @param jobName the name of the Job to trigger + * @param groupName the group name of the Job to trigger + * @param data the (possibly null) JobDataMap to be + * associated with the trigger that fires the job immediately. + */ + public void triggerJob(String jobName, String groupName, JobDataMap data) + throws SchedulerException; + + /** + *

+ * Trigger the identified {@link org.quartz.JobDetail} + * (execute it now) - the generated trigger will be volatile. + *

+ * + * @param jobName the name of the Job to trigger + * @param groupName the group name of the Job to trigger + * @param data the (possibly null) JobDataMap to be + * associated with the trigger that fires the job immediately. + */ + public void triggerJobWithVolatileTrigger(String jobName, String groupName, JobDataMap data) + throws SchedulerException; + + /** + *

+ * Pause the {@link org.quartz.JobDetail} with the given + * name - by pausing all of its current Triggers. + *

+ * + * @see #resumeJob(String, String) + */ + public void pauseJob(String jobName, String groupName) + throws SchedulerException; + + /** + *

+ * Pause all of the {@link org.quartz.JobDetail}s in the + * given group - by pausing all of their Triggers. + *

+ * + *

+ * The Scheduler will "remember" that the group is paused, and impose the + * pause on any new jobs that are added to the group while the group is + * paused. + *

+ * + * @see #resumeJobGroup(String) + */ + public void pauseJobGroup(String groupName) throws SchedulerException; + + /** + *

+ * Pause the {@link Trigger} with the given name. + *

+ * + * @see #resumeTrigger(String, String) + */ + public void pauseTrigger(String triggerName, String groupName) + throws SchedulerException; + + /** + *

+ * Pause all of the {@link Trigger}s in the given group. + *

+ * + *

+ * The Scheduler will "remember" that the group is paused, and impose the + * pause on any new triggers that are added to the group while the group is + * paused. + *

+ * + * @see #resumeTriggerGroup(String) + */ + public void pauseTriggerGroup(String groupName) throws SchedulerException; + + /** + *

+ * Resume (un-pause) the {@link org.quartz.JobDetail} with + * the given name. + *

+ * + *

+ * If any of the Job'sTrigger s missed one + * or more fire-times, then the Trigger's misfire + * instruction will be applied. + *

+ * + * @see #pauseJob(String, String) + */ + public void resumeJob(String jobName, String groupName) + throws SchedulerException; + + /** + *

+ * Resume (un-pause) all of the {@link org.quartz.JobDetail}s + * in the given group. + *

+ * + *

+ * If any of the Job s had Trigger s that + * missed one or more fire-times, then the Trigger's + * misfire instruction will be applied. + *

+ * + * @see #pauseJobGroup(String) + */ + public void resumeJobGroup(String groupName) throws SchedulerException; + + /** + *

+ * Resume (un-pause) the {@link Trigger} with the given + * name. + *

+ * + *

+ * If the Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseTrigger(String, String) + */ + public void resumeTrigger(String triggerName, String groupName) + throws SchedulerException; + + /** + *

+ * Resume (un-pause) all of the {@link Trigger}s in the + * given group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseTriggerGroup(String) + */ + public void resumeTriggerGroup(String groupName) throws SchedulerException; + + /** + *

+ * Pause all triggers - similar to calling pauseTriggerGroup(group) + * on every group, however, after using this method resumeAll() + * must be called to clear the scheduler's state of 'remembering' that all + * new triggers will be paused as they are added. + *

+ * + *

+ * When resumeAll() is called (to un-pause), trigger misfire + * instructions WILL be applied. + *

+ * + * @see #resumeAll() + * @see #pauseTriggerGroup(String) + * @see #standby() + */ + public void pauseAll() throws SchedulerException; + + /** + *

+ * Resume (un-pause) all triggers - similar to calling + * resumeTriggerGroup(group) on every group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseAll() + */ + public void resumeAll() throws SchedulerException; + + /** + *

+ * Get the names of all known {@link org.quartz.JobDetail} + * groups. + *

+ */ + public String[] getJobGroupNames() throws SchedulerException; + + /** + *

+ * Get the names of all the {@link org.quartz.JobDetail}s + * in the given group. + *

+ */ + public String[] getJobNames(String groupName) throws SchedulerException; + + /** + *

+ * Get all {@link Trigger} s that are associated with the + * identified {@link org.quartz.JobDetail}. + *

+ */ + public Trigger[] getTriggersOfJob(String jobName, String groupName) + throws SchedulerException; + + /** + *

+ * Get the names of all known {@link Trigger} groups. + *

+ */ + public String[] getTriggerGroupNames() throws SchedulerException; + + /** + *

+ * Get the names of all the {@link Trigger}s in the given + * group. + *

+ */ + public String[] getTriggerNames(String groupName) throws SchedulerException; + + /** + *

+ * Get the names of all {@link Trigger} groups that are paused. + *

+ * + * @return + * @throws SchedulerException + */ + public Set getPausedTriggerGroups() throws SchedulerException; + + /** + *

+ * Get the {@link JobDetail} for the Job + * instance with the given name and group. + *

+ */ + public JobDetail getJobDetail(String jobName, String jobGroup) + throws SchedulerException; + + /** + *

+ * Get the {@link Trigger} instance with the given name and + * group. + *

+ */ + public Trigger getTrigger(String triggerName, String triggerGroup) + throws SchedulerException; + + /** + *

+ * Get the current state of the identified {@link Trigger}. + *

+ * + * @see Trigger#STATE_NORMAL + * @see Trigger#STATE_PAUSED + * @see Trigger#STATE_COMPLETE + * @see Trigger#STATE_ERROR + * @see Trigger#STATE_BLOCKED + * @see Trigger#STATE_NONE + */ + public int getTriggerState(String triggerName, String triggerGroup) + throws SchedulerException; + + /** + *

+ * Add (register) the given Calendar to the Scheduler. + *

+ * + * @param updateTriggers whether or not to update existing triggers that + * referenced the already existing calendar so that they are 'correct' + * based on the new trigger. + * + * + * @throws SchedulerException + * if there is an internal Scheduler error, or a Calendar with + * the same name already exists, and replace is + * false. + */ + public void addCalendar(String calName, Calendar calendar, boolean replace, boolean updateTriggers) + throws SchedulerException; + + /** + *

+ * Delete the identified Calendar from the Scheduler. + *

+ * + * @return true if the Calendar was found and deleted. + * @throws SchedulerException + * if there is an internal Scheduler error. + */ + public boolean deleteCalendar(String calName) throws SchedulerException; + + /** + *

+ * Get the {@link Calendar} instance with the given name. + *

+ */ + public Calendar getCalendar(String calName) throws SchedulerException; + + /** + *

+ * Get the names of all registered {@link Calendar}s. + *

+ */ + public String[] getCalendarNames() throws SchedulerException; + + /** + *

+ * Request the interruption of all currently executing instances of the + * identified Job, which must be an implementor of the + * InterruptableJob interface. + *

+ * + *

+ * If more than one instance of the identified job is currently executing, + * the InterruptableJob#interrupt() method will be called on + * each instance. However, there is a limitation that in the case that + * interrupt() on one instances throws an exception, all + * remaining instances (that have not yet been interrupted) will not have + * their interrupt() method called. + *

+ * + *

+ * If you wish to interrupt a specific instance of a job (when more than + * one is executing) you can do so by calling + * {@link #getCurrentlyExecutingJobs()} to obtain a handle + * to the job instance, and then invoke interrupt() on it + * yourself. + *

+ * + * @param jobName + * @param groupName + * @return true is at least one instance of the identified job was found + * and interrupted. + * @throws UnableToInterruptJobException if the job does not implement + * InterruptableJob, or there is an exception while + * interrupting the job. + * @see InterruptableJob#interrupt() + * @see #getCurrentlyExecutingJobs() + */ + public boolean interrupt(String jobName, String groupName) throws UnableToInterruptJobException; + + /////////////////////////////////////////////////////////////////////////// + /// + /// Listener-related Methods + /// + /////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Add the given {@link JobListener} to the Scheduler's + * global list. + *

+ * + *

+ * Listeners in the 'global' list receive notification of execution events + * for ALL {@link org.quartz.JobDetail}s. + *

+ */ + public void addGlobalJobListener(JobListener jobListener) + throws SchedulerException; + + /** + *

+ * Add the given {@link JobListener} to the Scheduler's + * list, of registered JobListeners. + */ + public void addJobListener(JobListener jobListener) + throws SchedulerException; + + /** + *

+ * Remove the given {@link JobListener} from the Scheduler's + * list of global listeners. + *

+ * + * @return true if the identifed listener was found in the list, and + * removed. + */ + public boolean removeGlobalJobListener(JobListener jobListener) + throws SchedulerException; + + /** + *

+ * Remove the identifed {@link JobListener} from the Scheduler's + * list of registered listeners. + *

+ * + * @return true if the identifed listener was found in the list, and + * removed. + */ + public boolean removeJobListener(String name) throws SchedulerException; + + /** + *

+ * Get a List containing all of the {@link JobListener} s in + * the Scheduler'sglobal list. + *

+ */ + public List getGlobalJobListeners() throws SchedulerException; + + /** + *

+ * Get a Set containing the names of all the non-global{@link JobListener} + * s registered with the Scheduler. + *

+ */ + public Set getJobListenerNames() throws SchedulerException; + + /** + *

+ * Get the non-global{@link JobListener} that has + * the given name. + *

+ */ + public JobListener getJobListener(String name) throws SchedulerException; + + /** + *

+ * Add the given {@link TriggerListener} to the Scheduler's + * global list. + *

+ * + *

+ * Listeners in the 'global' list receive notification of execution events + * for ALL {@link Trigger}s. + *

+ */ + public void addGlobalTriggerListener(TriggerListener triggerListener) + throws SchedulerException; + + /** + *

+ * Add the given {@link TriggerListener} to the Scheduler's + * list, of registered TriggerListeners. + */ + public void addTriggerListener(TriggerListener triggerListener) + throws SchedulerException; + + /** + *

+ * Remove the given {@link TriggerListener} from the Scheduler's + * list of global listeners. + *

+ * + * @return true if the identifed listener was found in the list, and + * removed. + */ + public boolean removeGlobalTriggerListener(TriggerListener triggerListener) + throws SchedulerException; + + /** + *

+ * Remove the identifed {@link TriggerListener} from the + * Scheduler's list of registered listeners. + *

+ * + * @return true if the identifed listener was found in the list, and + * removed. + */ + public boolean removeTriggerListener(String name) throws SchedulerException; + + /** + *

+ * Get a List containing all of the {@link TriggerListener} + * s in the Scheduler'sglobal list. + *

+ */ + public List getGlobalTriggerListeners() throws SchedulerException; + + /** + *

+ * Get a Set containing the names of all the non-global{@link TriggerListener} + * s registered with the Scheduler. + *

+ */ + public Set getTriggerListenerNames() throws SchedulerException; + + /** + *

+ * Get the non-global{@link TriggerListener} that + * has the given name. + *

+ */ + public TriggerListener getTriggerListener(String name) + throws SchedulerException; + + /** + *

+ * Register the given {@link SchedulerListener} with the + * Scheduler. + *

+ */ + public void addSchedulerListener(SchedulerListener schedulerListener) + throws SchedulerException; + + /** + *

+ * Remove the given {@link SchedulerListener} from the + * Scheduler. + *

+ * + * @return true if the identifed listener was found in the list, and + * removed. + */ + public boolean removeSchedulerListener(SchedulerListener schedulerListener) + throws SchedulerException; + + /** + *

+ * Get a List containing all of the {@link SchedulerListener} + * s registered with the Scheduler. + *

+ */ + public List getSchedulerListeners() throws SchedulerException; + + +} Index: 3rdParty_sources/quartz/org/quartz/SchedulerConfigException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/SchedulerConfigException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/SchedulerConfigException.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,63 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +/** + *

+ * An exception that is thrown to indicate that there is a misconfiguration of + * the SchedulerFactory- or one of the components it + * configures. + *

+ * + * @author James House + */ +public class SchedulerConfigException extends SchedulerException { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a JobPersistenceException with the given message. + *

+ */ + public SchedulerConfigException(String msg) { + super(msg, ERR_BAD_CONFIGURATION); + } + + /** + *

+ * Create a JobPersistenceException with the given message + * and cause. + *

+ */ + public SchedulerConfigException(String msg, Exception cause) { + super(msg, cause); + setErrorCode(ERR_BAD_CONFIGURATION); + } + +} Index: 3rdParty_sources/quartz/org/quartz/SchedulerContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/SchedulerContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/SchedulerContext.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,376 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import java.io.Serializable; +import java.util.Iterator; +import java.util.Map; + +import org.quartz.utils.DirtyFlagMap; + +/** + *

+ * Holds context/environment data that can be made available to Jobs as they + * are executed. This feature is much like the ServletContext feature when + * working with J2EE servlets. + *

+ * + * @see Scheduler#getContext + * + * @author James House + */ +public class SchedulerContext extends DirtyFlagMap implements Serializable { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private boolean allowsTransientData = false; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create an empty JobDataMap. + *

+ */ + public SchedulerContext() { + super(15); + } + + /** + *

+ * Create a JobDataMap with the given data. + *

+ */ + public SchedulerContext(Map map) { + this(); + + putAll(map); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Tell the SchedulerContext that it should allow non- + * Serializable data. + *

+ * + *

+ * Future versions of Quartz may make distinctions on how it propogates + * data in the SchedulerContext between instances of proxies to a single + * scheduler instance - i.e. if Quartz is being used via RMI. + *

+ */ + public void setAllowsTransientData(boolean allowsTransientData) { + + if (containsTransientData() && !allowsTransientData) + throw new IllegalStateException( + "Cannot set property 'allowsTransientData' to 'false' " + + "when data map contains non-serializable objects."); + + this.allowsTransientData = allowsTransientData; + } + + public boolean getAllowsTransientData() { + return allowsTransientData; + } + + public boolean containsTransientData() { + + if (!getAllowsTransientData()) // short circuit... + return false; + + String[] keys = getKeys(); + + for (int i = 0; i < keys.length; i++) { + Object o = super.get(keys[i]); + if (!(o instanceof Serializable)) return true; + } + + return false; + } + + /** + *

+ * Nulls-out any data values that are non-Serializable. + *

+ */ + public void removeTransientData() { + + if (!getAllowsTransientData()) // short circuit... + return; + + String[] keys = getKeys(); + + for (int i = 0; i < keys.length; i++) { + Object o = super.get(keys[i]); + if (!(o instanceof Serializable)) remove(keys[i]); + } + + } + + /** + *

+ * Adds the name-value pairs in the given Map to the SchedulerContext. + *

+ * + *

+ * All keys must be Strings. + *

+ */ + public void putAll(Map map) { + Iterator itr = map.keySet().iterator(); + while (itr.hasNext()) { + Object key = itr.next(); + Object val = map.get(key); + + put(key, val); + // will throw IllegalArgumentException if value not serilizable + } + } + + /** + *

+ * Adds the given int value to the SchedulerContext. + *

+ */ + public void put(String key, int value) { + super.put(key, new Integer(value)); + } + + /** + *

+ * Adds the given long value to the SchedulerContext. + *

+ */ + public void put(String key, long value) { + super.put(key, new Long(value)); + } + + /** + *

+ * Adds the given float value to the SchedulerContext. + *

+ */ + public void put(String key, float value) { + super.put(key, new Float(value)); + } + + /** + *

+ * Adds the given double value to the SchedulerContext. + *

+ */ + public void put(String key, double value) { + super.put(key, new Double(value)); + } + + /** + *

+ * Adds the given boolean value to the SchedulerContext. + *

+ */ + public void put(String key, boolean value) { + super.put(key, new Boolean(value)); + } + + /** + *

+ * Adds the given char value to the SchedulerContext. + *

+ */ + public void put(String key, char value) { + super.put(key, new Character(value)); + } + + /** + *

+ * Adds the given String value to the SchedulerContext. + *

+ */ + public void put(String key, String value) { + super.put(key, value); + } + + /** + *

+ * Adds the given Object value to the SchedulerContext. + *

+ */ + public Object put(Object key, Object value) { + if (!(key instanceof String)) + throw new IllegalArgumentException( + "Keys in map must be Strings."); + + return super.put(key, value); + } + + /** + *

+ * Retrieve the identified int value from the SchedulerContext. + *

+ * + * @throws ClassCastException + * if the identified object is not an Integer. + */ + public int getInt(String key) { + Object obj = get(key); + + try { + return ((Integer) obj).intValue(); + } catch (Exception e) { + throw new ClassCastException("Identified object is not an Integer."); + } + } + + /** + *

+ * Retrieve the identified long value from the SchedulerContext. + *

+ * + * @throws ClassCastException + * if the identified object is not a Long. + */ + public long getLong(String key) { + Object obj = get(key); + + try { + return ((Long) obj).longValue(); + } catch (Exception e) { + throw new ClassCastException("Identified object is not a Long."); + } + } + + /** + *

+ * Retrieve the identified float value from the SchedulerContext. + *

+ * + * @throws ClassCastException + * if the identified object is not a Float. + */ + public float getFloat(String key) { + Object obj = get(key); + + try { + return ((Float) obj).floatValue(); + } catch (Exception e) { + throw new ClassCastException("Identified object is not a Float."); + } + } + + /** + *

+ * Retrieve the identified double value from the SchedulerContext. + *

+ * + * @throws ClassCastException + * if the identified object is not a Double. + */ + public double getDouble(String key) { + Object obj = get(key); + + try { + return ((Double) obj).doubleValue(); + } catch (Exception e) { + throw new ClassCastException("Identified object is not a Double."); + } + } + + /** + *

+ * Retrieve the identified boolean value from the SchedulerContext. + *

+ * + * @throws ClassCastException + * if the identified object is not a Boolean. + */ + public boolean getBoolean(String key) { + Object obj = get(key); + + try { + return ((Boolean) obj).booleanValue(); + } catch (Exception e) { + throw new ClassCastException("Identified object is not a Boolean."); + } + } + + /** + *

+ * Retrieve the identified char value from the SchedulerContext. + *

+ * + * @throws ClassCastException + * if the identified object is not a Character. + */ + public char getChar(String key) { + Object obj = get(key); + + try { + return ((Character) obj).charValue(); + } catch (Exception e) { + throw new ClassCastException( + "Identified object is not a Character."); + } + } + + /** + *

+ * Retrieve the identified String value from the SchedulerContext. + *

+ * + * @throws ClassCastException + * if the identified object is not a String. + */ + public String getString(String key) { + Object obj = get(key); + + try { + return (String) obj; + } catch (Exception e) { + throw new ClassCastException("Identified object is not a String."); + } + } + + public String[] getKeys() { + return (String[]) keySet().toArray(new String[size()]); + } + +} Index: 3rdParty_sources/quartz/org/quartz/SchedulerException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/SchedulerException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/SchedulerException.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,322 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import java.io.PrintStream; +import java.io.PrintWriter; + +/** + *

+ * Base class for exceptions thrown by the Quartz {@link Scheduler}. + *

+ * + *

+ * SchedulerException s may contain a reference to another + * Exception, which was the underlying cause of the SchedulerException. + *

+ * + * @author James House + */ +public class SchedulerException extends Exception { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static final int ERR_UNSPECIFIED = 0; + + public static final int ERR_BAD_CONFIGURATION = 50; + + public static final int ERR_TIME_BROKER_FAILURE = 70; + + public static final int ERR_CLIENT_ERROR = 100; + + public static final int ERR_COMMUNICATION_FAILURE = 200; + + public static final int ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION = 210; + + public static final int ERR_PERSISTENCE = 400; + + public static final int ERR_PERSISTENCE_JOB_DOES_NOT_EXIST = 410; + + public static final int ERR_PERSISTENCE_CALENDAR_DOES_NOT_EXIST = 420; + + public static final int ERR_PERSISTENCE_TRIGGER_DOES_NOT_EXIST = 430; + + public static final int ERR_PERSISTENCE_CRITICAL_FAILURE = 499; + + public static final int ERR_THREAD_POOL = 500; + + public static final int ERR_THREAD_POOL_EXHAUSTED = 510; + + public static final int ERR_THREAD_POOL_CRITICAL_FAILURE = 599; + + public static final int ERR_JOB_LISTENER = 600; + + public static final int ERR_JOB_LISTENER_NOT_FOUND = 610; + + public static final int ERR_TRIGGER_LISTENER = 700; + + public static final int ERR_TRIGGER_LISTENER_NOT_FOUND = 710; + + public static final int ERR_JOB_EXECUTION_THREW_EXCEPTION = 800; + + public static final int ERR_TRIGGER_THREW_EXCEPTION = 850; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private Exception cause; + + private int errorCode = ERR_UNSPECIFIED; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public SchedulerException() { + super(); + } + + public SchedulerException(String msg) { + super(msg); + } + + public SchedulerException(String msg, int errorCode) { + super(msg); + setErrorCode(errorCode); + } + + public SchedulerException(Exception cause) { + super(cause.toString()); + this.cause = cause; + } + + public SchedulerException(String msg, Exception cause) { + super(msg); + this.cause = cause; + } + + public SchedulerException(String msg, Exception cause, int errorCode) { + super(msg); + this.cause = cause; + setErrorCode(errorCode); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Return the exception that is the underlying cause of this exception. + *

+ * + *

+ * This may be used to find more detail about the cause of the error. + *

+ * + * @return the underlying exception, or null if there is not + * one. + */ + public Throwable getUnderlyingException() { + return cause; + } + + /** + *

+ * Get the error code associated with this exception. + *

+ * + *

+ * This may be used to find more detail about the cause of the error. + *

+ * + * @return one of the ERR_XXX constants defined in this class. + */ + public int getErrorCode() { + return errorCode; + } + + /** + *

+ * Get the error code associated with this exception. + *

+ * + *

+ * This may be used to provide more detail about the cause of the error. + *

+ * + * @param errorCode + * one of the ERR_XXX constants defined in this class. + */ + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + /** + *

+ * Determine if the specified error code is in the 'ERR_PERSISTENCE' + * category of errors. + *

+ */ + public boolean isPersistenceError() { + return (errorCode >= ERR_PERSISTENCE && errorCode <= ERR_PERSISTENCE + 99); + } + + /** + *

+ * Determine if the specified error code is in the 'ERR_THREAD_POOL' + * category of errors. + *

+ */ + public boolean isThreadPoolError() { + return (errorCode >= ERR_THREAD_POOL && errorCode <= ERR_THREAD_POOL + 99); + } + + /** + *

+ * Determine if the specified error code is in the 'ERR_JOB_LISTENER' + * category of errors. + *

+ */ + public boolean isJobListenerError() { + return (errorCode >= ERR_JOB_LISTENER && errorCode <= ERR_JOB_LISTENER + 99); + } + + /** + *

+ * Determine if the specified error code is in the 'ERR_TRIGGER_LISTENER' + * category of errors. + *

+ */ + public boolean isTriggerListenerError() { + return (errorCode >= ERR_TRIGGER_LISTENER && errorCode <= ERR_TRIGGER_LISTENER + 99); + } + + /** + *

+ * Determine if the specified error code is in the 'ERR_CLIENT_ERROR' + * category of errors. + *

+ */ + public boolean isClientError() { + return (errorCode >= ERR_CLIENT_ERROR && errorCode <= ERR_CLIENT_ERROR + 99); + } + + /** + *

+ * Determine if the specified error code is in the 'ERR_CLIENT_ERROR' + * category of errors. + *

+ */ + public boolean isConfigurationError() { + return (errorCode >= ERR_BAD_CONFIGURATION && errorCode <= ERR_BAD_CONFIGURATION + 49); + } + + public String toString() { + if (cause == null) return super.toString(); + else + return super.toString() + " [See nested exception: " + + cause.toString() + "]"; + } + + /** + *

+ * Print a stack trace to the standard error stream. + *

+ * + *

+ * This overridden version will print the nested stack trace if available, + * otherwise it prints only this exception's stack. + *

+ */ + public void printStackTrace() { + printStackTrace(System.err); + } + + /** + *

+ * Print a stack trace to the specified stream. + *

+ * + *

+ * This overridden version will print the nested stack trace if available, + * otherwise it prints only this exception's stack. + *

+ * + * @param out + * the stream to which the stack traces will be printed. + */ + public void printStackTrace(PrintStream out) { + super.printStackTrace(out); + if ((cause != null)) { + synchronized (out) { + out + .println("* Nested Exception (Underlying Cause) ---------------"); + cause.printStackTrace(out); + } + } + } + + /** + *

+ * Print a stack trace to the specified writer. + *

+ * + *

+ * This overridden version will print the nested stack trace if available, + * otherwise it prints this exception's stack. + *

+ * + * @param out + * the writer to which the stack traces will be printed. + */ + public void printStackTrace(PrintWriter out) { + super.printStackTrace(out); + if ((cause != null)) { + synchronized (out) { + out + .println("* Nested Exception (Underlying Cause) ---------------"); + cause.printStackTrace(out); + } + } + } + +} Index: 3rdParty_sources/quartz/org/quartz/SchedulerFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/SchedulerFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/SchedulerFactory.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,72 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import java.util.Collection; + +/** + *

+ * Provides a mechanism for obtaining client-usable handles to Scheduler + * instances. + *

+ * + * @see Scheduler + * @see org.quartz.impl.StdSchedulerFactory + * + * @author James House + */ +public interface SchedulerFactory { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Returns a client-usable handle to a Scheduler. + *

+ * + * @throws SchedulerException + * if there is a problem with the underlying Scheduler. + */ + public Scheduler getScheduler() throws SchedulerException; + + /** + *

+ * Returns a handle to the Scheduler with the given name, if it exists. + *

+ */ + public Scheduler getScheduler(String schedName) throws SchedulerException; + + /** + *

+ * Returns handles to all known Schedulers (made by any SchedulerFactory + * within this jvm.). + *

+ */ + public Collection getAllSchedulers() throws SchedulerException; + +} Index: 3rdParty_sources/quartz/org/quartz/SchedulerListener.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/SchedulerListener.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/SchedulerListener.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,148 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +/** + *

+ * The interface to be implemented by classes that want to be informed of major + * {@link Scheduler} events. + *

+ * + * @see Scheduler + * @see JobListener + * @see TriggerListener + * + * @author James House + */ +public interface SchedulerListener { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Called by the {@link Scheduler} when a {@link org.quartz.JobDetail} + * is scheduled. + *

+ */ + public void jobScheduled(Trigger trigger); + + /** + *

+ * Called by the {@link Scheduler} when a {@link org.quartz.JobDetail} + * is unscheduled. + *

+ */ + public void jobUnscheduled(String triggerName, String triggerGroup); + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * has reached the condition in which it will never fire again. + *

+ */ + public void triggerFinalized(Trigger trigger); + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * or group of {@link Trigger}s has been paused. + *

+ * + *

+ * If a group was paused, then the triggerName parameter + * will be null. + *

+ */ + public void triggersPaused(String triggerName, String triggerGroup); + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * or group of {@link Trigger}s has been un-paused. + *

+ * + *

+ * If a group was resumed, then the triggerName parameter + * will be null. + *

+ */ + public void triggersResumed(String triggerName, String triggerGroup); + + /** + *

+ * Called by the {@link Scheduler} when a {@link org.quartz.JobDetail} + * or group of {@link org.quartz.JobDetail}s has been + * paused. + *

+ * + *

+ * If a group was paused, then the jobName parameter will be + * null. If all jobs were paused, then both parameters will be null. + *

+ */ + public void jobsPaused(String jobName, String jobGroup); + + /** + *

+ * Called by the {@link Scheduler} when a {@link org.quartz.JobDetail} + * or group of {@link org.quartz.JobDetail}s has been + * un-paused. + *

+ * + *

+ * If a group was resumed, then the jobName parameter will + * be null. If all jobs were paused, then both parameters will be null. + *

+ */ + public void jobsResumed(String jobName, String jobGroup); + + /** + *

+ * Called by the {@link Scheduler} when a serious error has + * occured within the scheduler - such as repeated failures in the JobStore, + * or the inability to instantiate a Job instance when its + * Trigger has fired. + *

+ * + *

+ * The getErrorCode() method of the given SchedulerException + * can be used to determine more specific information about the type of + * error that was encountered. + *

+ */ + public void schedulerError(String msg, SchedulerException cause); + + /** + *

+ * Called by the {@link Scheduler} to inform the listener + * that it has shutdown. + *

+ */ + public void schedulerShutdown(); + +} Index: 3rdParty_sources/quartz/org/quartz/SchedulerMetaData.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/SchedulerMetaData.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/SchedulerMetaData.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,339 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import java.util.Date; + +/** + *

+ * Describes the settings and capabilities of a given {@link Scheduler} + * instance. + *

+ * + * @author James House + */ +public class SchedulerMetaData implements java.io.Serializable { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private String schedName; + + private String schedInst; + + private Class schedClass; + + private boolean isRemote; + + private boolean started; + + private boolean paused; + + private boolean shutdown; + + private Date startTime; + + private int numJobsExec; + + private Class jsClass; + + private boolean jsPersistent; + + private Class tpClass; + + private int tpSize; + + private String version; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public SchedulerMetaData(String schedName, String schedInst, + Class schedClass, boolean isRemote, boolean started, + boolean paused, boolean shutdown, Date startTime, int numJobsExec, + Class jsClass, boolean jsPersistent, Class tpClass, int tpSize, + String version) { + this.schedName = schedName; + this.schedInst = schedInst; + this.schedClass = schedClass; + this.isRemote = isRemote; + this.started = started; + this.paused = paused; + this.shutdown = shutdown; + this.startTime = startTime; + this.numJobsExec = numJobsExec; + this.jsClass = jsClass; + this.jsPersistent = jsPersistent; + this.tpClass = tpClass; + this.tpSize = tpSize; + this.version = version; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Returns the name of the Scheduler. + *

+ */ + public String getSchedulerName() { + return schedName; + } + + /** + *

+ * Returns the instance Id of the Scheduler. + *

+ */ + public String getSchedulerInstanceId() { + return schedInst; + } + + /** + *

+ * Returns the class-name of the Scheduler instance. + *

+ */ + public Class getSchedulerClass() { + return schedClass; + } + + /** + *

+ * Returns the Date at which the Scheduler started running. + *

+ * + * @return null if the scheduler has not been started. + */ + public Date runningSince() { + return startTime; + } + + /** + *

+ * Returns the number of jobs executed since the Scheduler + * started.. + *

+ */ + public int numJobsExecuted() { + return numJobsExec; + } + + /** + *

+ * Returns whether the Scheduler is being used remotely (via + * RMI). + *

+ */ + public boolean isSchedulerRemote() { + return isRemote; + } + + /** + *

+ * Returns whether the scheduler has been started. + *

+ * + *

+ * Note: isStarted() may return true even if + * isPaused() returns true. + *

+ */ + public boolean isStarted() { + return started; + } + + /** + *

+ * Reports whether the Scheduler is paused. + *

+ * + *

+ * Note: isStarted() may return true even if + * isPaused() returns true. + *

+ */ + public boolean isPaused() { + return paused; + } + + /** + *

+ * Reports whether the Scheduler has been shutdown. + *

+ */ + public boolean isShutdown() { + return shutdown; + } + + /** + *

+ * Returns the class-name of the JobStore instance that is + * being used by the Scheduler. + *

+ */ + public Class getJobStoreClass() { + return jsClass; + } + + /** + *

+ * Returns whether or not the Scheduler'sJobStore + * instance supports persistence. + *

+ */ + public boolean jobStoreSupportsPersistence() { + return jsPersistent; + } + + /** + *

+ * Returns the class-name of the ThreadPool instance that is + * being used by the Scheduler. + *

+ */ + public Class getThreadPoolClass() { + return tpClass; + } + + /** + *

+ * Returns the number of threads currently in the Scheduler's + * ThreadPool. + *

+ */ + public int getThreadPoolSize() { + return tpSize; + } + + /** + *

+ * Returns the version of Quartz that is running. + *

+ */ + public String getVersion() { + return version; + } + + /** + *

+ * Return a simple string representation of this object. + *

+ */ + public String toString() { + try { + return getSummary(); + } catch (SchedulerException se) { + return "SchedulerMetaData: undeterminable."; + } + } + + /** + *

+ * Returns a formatted (human readable) String describing all the Scheduler's + * meta-data values. + *

+ * + *

+ * The format of the String looks something like this: + * + *

+     * 
+     * 
+     *  Quartz Scheduler 'SchedulerName' with instanceId 'SchedulerInstanceId' Scheduler class: 'org.quartz.impl.StdScheduler' - running locally. Running since: '11:33am on Jul 19, 2002' Not currently paused. Number of Triggers fired: '123' Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with '8' threads Using job-store 'org.quartz.impl.JDBCJobStore' - which supports persistence.
+     * 
+ * + *

+ */ + public String getSummary() throws SchedulerException { + StringBuffer str = new StringBuffer("Quartz Scheduler (v"); + str.append(getVersion()); + str.append(") '"); + + str.append(getSchedulerName()); + str.append("' with instanceId '"); + str.append(getSchedulerInstanceId()); + str.append("'\n"); + + str.append(" Scheduler class: '"); + str.append(getSchedulerClass().getName()); + str.append("'"); + if (isSchedulerRemote()) str.append(" - access via RMI."); + else + str.append(" - running locally."); + str.append("\n"); + + if (!isShutdown()) { + if (runningSince() != null) { + str.append(" Running since: "); + str.append(runningSince()); + } else + str.append("NOT STARTED."); + str.append("\n"); + + if (isPaused()) str.append(" Currently PAUSED."); + else + str.append(" Not currently paused."); + } else { + str.append(" Scheduler has been SHUTDOWN."); + } + str.append("\n"); + + str.append(" Number of jobs executed: "); + str.append(numJobsExecuted()); + str.append("\n"); + + str.append(" Using thread pool '"); + str.append(getThreadPoolClass().getName()); + str.append("' - with "); + str.append(getThreadPoolSize()); + str.append(" threads."); + str.append("\n"); + + str.append(" Using job-store '"); + str.append(getJobStoreClass().getName()); + str.append("' - which "); + if (jobStoreSupportsPersistence()) str.append("supports persistence."); + else + str.append("does not support persistence."); + str.append("\n"); + + return str.toString(); + } + +} Index: 3rdParty_sources/quartz/org/quartz/SimpleTrigger.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/SimpleTrigger.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/SimpleTrigger.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,840 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import java.util.Date; + + +/** + *

+ * A concrete {@link Trigger} that is used to fire a {@link org.quartz.JobDetail} + * at a given moment in time, and optionally repeated at a specified interval. + *

+ * + * @see Trigger + * @see CronTrigger + * @see TriggerUtils + * + * @author James House + * @author contributions by Lieven Govaerts of Ebitec Nv, Belgium. + */ +public class SimpleTrigger extends Trigger { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Instructs the {@link Scheduler} that upon a mis-fire + * situation, the {@link SimpleTrigger} wants to be fired + * now by Scheduler. + *

+ * + *

+ * NOTE: This instruction should typically only be used for + * 'one-shot' (non-repeating) Triggers. If it is used on a trigger with a + * repeat count > 0 then it is equivalent to the instruction {@link #MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT} + * . + *

+ */ + public static final int MISFIRE_INSTRUCTION_FIRE_NOW = 1; + + /** + *

+ * Instructs the {@link Scheduler} that upon a mis-fire + * situation, the {@link SimpleTrigger} wants to be + * re-scheduled to 'now' (even if the associated {@link Calendar} + * excludes 'now') with the repeat count left as-is. + *

+ * + *

+ * NOTE: Use of this instruction causes the trigger to 'forget' + * the start-time and repeat-count that it was originally setup with (this + * is only an issue if you for some reason wanted to be able to tell what + * the original values were at some later time). + *

+ * + *

+ * NOTE: This instruction could cause the Trigger + * to go to the 'COMPLETE' state after firing 'now', if all the + * repeat-fire-times where missed. + *

+ */ + public static final int MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT = 2; + + /** + *

+ * Instructs the {@link Scheduler} that upon a mis-fire + * situation, the {@link SimpleTrigger} wants to be + * re-scheduled to 'now' (even if the associated {@link Calendar} + * excludes 'now') with the repeat count set to what it would be, if it had + * not missed any firings. + *

+ * + *

+ * NOTE: Use of this instruction causes the trigger to 'forget' + * the start-time and repeat-count that it was originally setup with (this + * is only an issue if you for some reason wanted to be able to tell what + * the original values were at some later time). + *

+ * + *

+ * NOTE: This instruction could cause the Trigger + * to go to the 'COMPLETE' state after firing 'now', if all the + * repeat-fire-times where missed. + *

+ */ + public static final int MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT = 3; + + /** + *

+ * Instructs the {@link Scheduler} that upon a mis-fire + * situation, the {@link SimpleTrigger} wants to be + * re-scheduled to the next scheduled time after 'now' - taking into + * account any associated {@link Calendar}, and with the + * repeat count set to what it would be, if it had not missed any firings. + *

+ * + *

+ * NOTE/WARNING: This instruction could cause the Trigger + * to go directly to the 'COMPLETE' state if all fire-times where missed. + *

+ */ + public static final int MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT = 4; + + /** + *

+ * Instructs the {@link Scheduler} that upon a mis-fire + * situation, the {@link SimpleTrigger} wants to be + * re-scheduled to the next scheduled time after 'now' - taking into + * account any associated {@link Calendar}, and with the + * repeat count left unchanged. + *

+ * + *

+ * NOTE: Use of this instruction causes the trigger to 'forget' + * the repeat-count that it was originally setup with (this is only an + * issue if you for some reason wanted to be able to tell what the original + * values were at some later time). + *

+ * + *

+ * NOTE/WARNING: This instruction could cause the Trigger + * to go directly to the 'COMPLETE' state if all fire-times where missed. + *

+ */ + public static final int MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT = 5; + + /** + *

+ * Used to indicate the 'repeat count' of the trigger is indefinite. Or in + * other words, the trigger should repeat continually until the trigger's + * ending timestamp. + *

+ */ + public static int REPEAT_INDEFINITELY = -1; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private Date startTime = null; + + private Date endTime = null; + + private Date nextFireTime = null; + + private Date previousFireTime = null; + + private int repeatCount = 0; + + private long repeatInterval = 0; + + private int timesTriggered = 0; + + private boolean complete = false; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a SimpleTrigger with no settings. + *

+ */ + public SimpleTrigger() { + super(); + } + + /** + *

+ * Create a SimpleTrigger that will occur immediately, and + * not repeat. + *

+ */ + public SimpleTrigger(String name, String group) { + this(name, group, new Date(), null, 0, 0); + } + + /** + *

+ * Create a SimpleTrigger that will occur immediately, and + * repeat at the the given interval the given number of times. + *

+ */ + public SimpleTrigger(String name, String group, int repeatCount, + long repeatInterval) { + this(name, group, new Date(), null, repeatCount, repeatInterval); + } + + /** + *

+ * Create a SimpleTrigger that will occur at the given time, + * and not repeat. + *

+ */ + public SimpleTrigger(String name, String group, Date startTime) { + this(name, group, startTime, null, 0, 0); + } + + /** + *

+ * Create a SimpleTrigger that will occur at the given time, + * and repeat at the the given interval the given number of times, or until + * the given end time. + *

+ * + * @param startTime + * A Date set to the time for the Trigger + * to fire. + * @param endTime + * A Date set to the time for the Trigger + * to quit repeat firing. + * @param repeatCount + * The number of times for the Trigger to repeat + * firing, use {@link #REPEAT_INDEFINITELY}for unlimitted times. + * @param repeatInterval + * The number of milliseconds to pause between the repeat firing. + */ + public SimpleTrigger(String name, String group, Date startTime, + Date endTime, int repeatCount, long repeatInterval) { + super(name, group); + + setStartTime(startTime); + setEndTime(endTime); + setRepeatCount(repeatCount); + setRepeatInterval(repeatInterval); + } + + /** + *

+ * Create a SimpleTrigger that will occur at the given time, + * fire the identified Job and repeat at the the given + * interval the given number of times, or until the given end time. + *

+ * + * @param startTime + * A Date set to the time for the Trigger + * to fire. + * @param endTime + * A Date set to the time for the Trigger + * to quit repeat firing. + * @param repeatCount + * The number of times for the Trigger to repeat + * firing, use {@link #REPEAT_INDEFINITELY}for unlimitted times. + * @param repeatInterval + * The number of milliseconds to pause between the repeat firing. + */ + public SimpleTrigger(String name, String group, String jobName, + String jobGroup, Date startTime, Date endTime, int repeatCount, + long repeatInterval) { + super(name, group, jobName, jobGroup); + + setStartTime(startTime); + setEndTime(endTime); + setRepeatCount(repeatCount); + setRepeatInterval(repeatInterval); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Get the time at which the SimpleTrigger should occur. + *

+ */ + public Date getStartTime() { + return startTime; + } + + /** + *

+ * Set the time at which the SimpleTrigger should occur. + *

+ * + * @exception IllegalArgumentException + * if startTime is null. + */ + public void setStartTime(Date startTime) { + if (startTime == null) + throw new IllegalArgumentException("Start time cannot be null"); + + Date eTime = getEndTime(); + if (eTime != null && startTime != null && eTime.before(startTime)) + throw new IllegalArgumentException( + "End time cannot be before start time"); + + this.startTime = startTime; + } + + /** + *

+ * Get the time at which the SimpleTrigger should quit + * repeating - even if repeastCount isn't yet satisfied. + *

+ * + * @see #getFinalFireTime() + */ + public Date getEndTime() { + return endTime; + } + + /** + *

+ * Set the time at which the SimpleTrigger should quit + * repeating (and be automatically deleted). + *

+ * + * @exception IllegalArgumentException + * if endTime is before start time. + */ + public void setEndTime(Date endTime) { + Date sTime = getStartTime(); + if (sTime != null && endTime != null && sTime.after(endTime)) + throw new IllegalArgumentException( + "End time cannot be before start time"); + + this.endTime = endTime; + } + + /** + *

+ * Get the the number of times the SimpleTrigger should + * repeat, after which it will be automatically deleted. + *

+ * + * @see #REPEAT_INDEFINITELY + */ + public int getRepeatCount() { + return repeatCount; + } + + /** + *

+ * Set the the number of time the SimpleTrigger should + * repeat, after which it will be automatically deleted. + *

+ * + * @see #REPEAT_INDEFINITELY + * @exception IllegalArgumentException + * if repeatCount is < 0 + */ + public void setRepeatCount(int repeatCount) { + if (repeatCount < 0 && repeatCount != REPEAT_INDEFINITELY) + throw new IllegalArgumentException( + "Repeat count must be >= 0, use the " + + "constant REPEAT_INDEFINITELY for infinite."); + + this.repeatCount = repeatCount; + } + + /** + *

+ * Get the the time interval (in milliseconds) at which the SimpleTrigger + * should repeat. + *

+ */ + public long getRepeatInterval() { + return repeatInterval; + } + + /** + *

+ * Set the the time interval (in milliseconds) at which the SimpleTrigger + * should repeat. + *

+ * + * @exception IllegalArgumentException + * if repeatInterval is <= 0 + */ + public void setRepeatInterval(long repeatInterval) { + if (repeatInterval < 0) + throw new IllegalArgumentException( + "Repeat interval must be >= 0"); + + this.repeatInterval = repeatInterval; + } + + /** + *

+ * Get the number of times the SimpleTrigger has already + * fired. + *

+ */ + public int getTimesTriggered() { + return timesTriggered; + } + + /** + *

+ * Set the number of times the SimpleTrigger has already + * fired. + *

+ */ + public void setTimesTriggered(int timesTriggered) { + this.timesTriggered = timesTriggered; + } + + protected boolean validateMisfireInstruction(int misfireInstruction) { + if (misfireInstruction < MISFIRE_INSTRUCTION_SMART_POLICY) + return false; + + if (misfireInstruction > MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT) + return false; + + return true; + } + + /** + *

+ * Updates the SimpleTrigger's state based on the + * MISFIRE_INSTRUCTION_XXX that was selected when the SimpleTrigger + * was created. + *

+ * + *

+ * If the misfire instruction is set to MISFIRE_INSTRUCTION_SMART_POLICY, + * then the following scheme will be used:
+ *

    + *
  • If the Repeat Count is 0, then the instruction will + * be interpreted as MISFIRE_INSTRUCTION_FIRE_NOW.
  • + *
  • If the Repeat Count is REPEAT_INDEFINITELY, then + * the instruction will be interpreted as MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT. + * WARNING: using MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT + * with a trigger that has a non-null end-time may cause the trigger to + * never fire again if the end-time arrived during the misfire time span. + *
  • + *
  • If the Repeat Count is > 0, then the instruction + * will be interpreted as MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT. + *
  • + *
+ *

+ */ + public void updateAfterMisfire(Calendar cal) { + int instr = getMisfireInstruction(); + if (instr == Trigger.MISFIRE_INSTRUCTION_SMART_POLICY) { + if (getRepeatCount() == 0) instr = MISFIRE_INSTRUCTION_FIRE_NOW; + else if (getRepeatCount() == REPEAT_INDEFINITELY) instr = MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT; + else + // if (getRepeatCount() > 0) + instr = MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT; + } else if (instr == MISFIRE_INSTRUCTION_FIRE_NOW + && getRepeatCount() != 0) + instr = MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT; + + if (instr == MISFIRE_INSTRUCTION_FIRE_NOW) { + setNextFireTime(new Date()); + } else if (instr == MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT) { + Date newFireTime = getFireTimeAfter(new Date()); + while (newFireTime != null && cal != null + && !cal.isTimeIncluded(newFireTime.getTime())) { + newFireTime = getFireTimeAfter(newFireTime); + } + setNextFireTime(newFireTime); + } else if (instr == MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT) { + Date newFireTime = getFireTimeAfter(new Date()); + while (newFireTime != null && cal != null + && !cal.isTimeIncluded(newFireTime.getTime())) { + newFireTime = getFireTimeAfter(newFireTime); + } + if (newFireTime != null) { + int timesMissed = computeNumTimesFiredBetween(nextFireTime, + newFireTime); + setTimesTriggered(getTimesTriggered() + timesMissed); + } + + setNextFireTime(newFireTime); + } else if (instr == MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT) { + Date newFireTime = new Date(); + if (repeatCount != 0 && repeatCount != REPEAT_INDEFINITELY) { + setRepeatCount(getRepeatCount() - getTimesTriggered()); + setTimesTriggered(0); + } + setStartTime(newFireTime); + setNextFireTime(newFireTime); + } else if (instr == MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT) { + Date newFireTime = new Date(); + + int timesMissed = computeNumTimesFiredBetween(nextFireTime, + newFireTime); + + if (repeatCount != 0 && repeatCount != REPEAT_INDEFINITELY) { + int remainingCount = getRepeatCount() + - (getTimesTriggered() + timesMissed); + if (remainingCount <= 0) { + remainingCount = 0; + } + setRepeatCount(remainingCount); + setTimesTriggered(0); + } + + if(getEndTime() != null && getEndTime().before(newFireTime)) + setEndTime(new Date(newFireTime.getTime() + 50)); + + setStartTime(newFireTime); + setNextFireTime(newFireTime); + } + + } + + /** + *

+ * Called when the {@link Scheduler} has decided to 'fire' + * the trigger (execute the associated Job), in order to + * give the Trigger a chance to update itself for its next + * triggering (if any). + *

+ * + * @see #executionComplete(JobExecutionContext, JobExecutionException) + */ + public void triggered(Calendar calendar) { + timesTriggered++; + previousFireTime = nextFireTime; + nextFireTime = getFireTimeAfter(nextFireTime); + + while (nextFireTime != null && calendar != null + && !calendar.isTimeIncluded(nextFireTime.getTime())) { + nextFireTime = getFireTimeAfter(nextFireTime); + } + } + + /** + * + * @see org.quartz.Trigger#updateWithNewCalendar(org.quartz.Calendar, long) + */ + public void updateWithNewCalendar(Calendar calendar, long misfireThreshold) + { + nextFireTime = getFireTimeAfter(previousFireTime); + + Date now = new Date(); + do { + while (nextFireTime != null && calendar != null + && !calendar.isTimeIncluded(nextFireTime.getTime())) { + nextFireTime = getFireTimeAfter(nextFireTime); + } + + if(nextFireTime != null && nextFireTime.before(now)) { + long diff = now.getTime() - nextFireTime.getTime(); + if(diff >= misfireThreshold) { + nextFireTime = getFireTimeAfter(nextFireTime); + continue; + } + } + }while(false); + } + + /** + *

+ * Called by the scheduler at the time a Trigger is first + * added to the scheduler, in order to have the Trigger + * compute its first fire time, based on any associated calendar. + *

+ * + *

+ * After this method has been called, getNextFireTime() + * should return a valid answer. + *

+ * + * @return the first time at which the Trigger will be fired + * by the scheduler, which is also the same value getNextFireTime() + * will return (until after the first firing of the Trigger). + *

+ */ + public Date computeFirstFireTime(Calendar calendar) { + nextFireTime = getStartTime(); + + while (nextFireTime != null && calendar != null + && !calendar.isTimeIncluded(nextFireTime.getTime())) { + nextFireTime = getFireTimeAfter(nextFireTime); + } + + return nextFireTime; + } + + /** + *

+ * Called after the {@link Scheduler} has executed the + * {@link org.quartz.JobDetail} associated with the Trigger + * in order to get the final instruction code from the trigger. + *

+ * + * @param context + * is the JobExecutionContext that was used by the + * Job'sexecute(xx) method. + * @param result + * is the JobExecutionException thrown by the + * Job, if any (may be null). + * @return one of the Trigger.INSTRUCTION_XXX constants. + * + * @see #INSTRUCTION_NOOP + * @see #INSTRUCTION_RE_EXECUTE_JOB + * @see #INSTRUCTION_DELETE_TRIGGER + * @see #INSTRUCTION_SET_TRIGGER_COMPLETE + * @see #triggered(Calendar) + */ + public int executionComplete(JobExecutionContext context, + JobExecutionException result) { + if (result != null && result.refireImmediately()) + return INSTRUCTION_RE_EXECUTE_JOB; + + if (result != null && result.unscheduleFiringTrigger()) + return INSTRUCTION_SET_TRIGGER_COMPLETE; + + if (result != null && result.unscheduleAllTriggers()) + return INSTRUCTION_SET_ALL_JOB_TRIGGERS_COMPLETE; + + if (!mayFireAgain()) return INSTRUCTION_DELETE_TRIGGER; + + return INSTRUCTION_NOOP; + } + + /** + *

+ * Returns the next time at which the SimpleTrigger will + * fire. If the trigger will not fire again, null will be + * returned. The value returned is not guaranteed to be valid until after + * the Trigger has been added to the scheduler. + *

+ */ + public Date getNextFireTime() { + return nextFireTime; + } + + /** + *

+ * Returns the previous time at which the SimpleTrigger will + * fire. If the trigger has not yet fired, null will be + * returned. + */ + public Date getPreviousFireTime() { + return previousFireTime; + } + + /** + *

+ * Set the next time at which the SimpleTrigger should fire. + *

+ * + *

+ * This method should not be invoked by client code. + *

+ */ + public void setNextFireTime(Date nextFireTime) { + this.nextFireTime = nextFireTime; + } + + /** + *

+ * Set the previous time at which the SimpleTrigger fired. + *

+ * + *

+ * This method should not be invoked by client code. + *

+ */ + public void setPreviousFireTime(Date previousFireTime) { + this.previousFireTime = previousFireTime; + } + + /** + *

+ * Returns the next time at which the SimpleTrigger will + * fire, after the given time. If the trigger will not fire after the given + * time, null will be returned. + *

+ */ + public Date getFireTimeAfter(Date afterTime) { + if (complete) return null; + + if ((timesTriggered > repeatCount) + && (repeatCount != REPEAT_INDEFINITELY)) return null; + + if (afterTime == null) afterTime = new Date(); + + if (repeatCount == 0 && afterTime.compareTo(getStartTime()) >= 0) + return null; + + long startMillis = getStartTime().getTime(); + long afterMillis = afterTime.getTime(); + long endMillis = (getEndTime() == null) ? Long.MAX_VALUE : getEndTime() + .getTime(); + + if (endMillis <= afterMillis) return null; + + if (startMillis < afterMillis && repeatCount == 0) return null; + + if (afterMillis < startMillis) return new Date(startMillis); + + long numberoftimesexecutedplusone = ((afterMillis - startMillis) / repeatInterval) + 1; + + if ((numberoftimesexecutedplusone > repeatCount) + && (repeatCount != REPEAT_INDEFINITELY)) return null; + + Date time = new Date((numberoftimesexecutedplusone * repeatInterval) + + startMillis); + + if (endMillis <= time.getTime()) return null; + + return time; + } + + /** + *

+ * Returns the last time at which the SimpleTrigger will + * fire, before the given time. If the trigger will not fire before the + * given time, null will be returned. + *

+ */ + public Date getFireTimeBefore(Date end) { + if (end.getTime() < getStartTime().getTime()) return null; + + int numFires = computeNumTimesFiredBetween(getStartTime(), end); + + return new Date(getStartTime().getTime() + (numFires * repeatInterval)); + } + + public int computeNumTimesFiredBetween(Date start, Date end) { + long time = end.getTime() - start.getTime(); + + return (int) (time / repeatInterval); + } + + /** + *

+ * Returns the final time at which the SimpleTrigger will + * fire, if repeatCount is REPEAT_INDEFINITELY, null will be returned. + *

+ * + *

+ * Note that the return time may be in the past. + *

+ */ + public Date getFinalFireTime() { + if (repeatCount == 0) return startTime; + + if (repeatCount == REPEAT_INDEFINITELY && getEndTime() == null) + return null; + + if (repeatCount == REPEAT_INDEFINITELY && getEndTime() == null) return null; + else if (repeatCount == REPEAT_INDEFINITELY) + return getFireTimeBefore(getEndTime()); + + long lastTrigger = startTime.getTime() + (repeatCount * repeatInterval); + + if ((getEndTime() == null) || (lastTrigger < getEndTime().getTime())) return new Date( + lastTrigger); + else + return getFireTimeBefore(getEndTime()); + } + + /** + *

+ * Determines whether or not the SimpleTrigger will occur + * again. + *

+ */ + public boolean mayFireAgain() { + return (getNextFireTime() != null); + } + + /** + *

+ * Validates whether the properties of the JobDetail are + * valid for submission into a Scheduler. + * + * @throws IllegalStateException + * if a required property (such as Name, Group, Class) is not + * set. + */ + public void validate() throws SchedulerException { + super.validate(); + + if (repeatCount != 0 && repeatInterval < 1) + throw new SchedulerException("Repeat Interval cannot be zero.", + SchedulerException.ERR_CLIENT_ERROR); + } + + public static void main(String[] args) // TODO: remove method after good + // unit testing + throws Exception { + + Date sdt = new Date(); + + Date edt = new Date(sdt.getTime() + 55000L); + + SimpleTrigger st = new SimpleTrigger("t", "g", "j", "g", sdt, edt, 10, + 10000L); + + System.err.println(); + + st.computeFirstFireTime(null); + + System.err.println("lastTime=" + st.getFinalFireTime()); + + java.util.List times = TriggerUtils.computeFireTimes(st, null, 50); + + for (int i = 0; i < times.size(); i++) { + System.err.println("firetime = " + times.get(i)); + } + } + +} Index: 3rdParty_sources/quartz/org/quartz/StatefulJob.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/StatefulJob.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/StatefulJob.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,57 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +/** + *

+ * A marker interface for {@link org.quartz.JobDetail} s that + * wish to have their state maintained between executions. + *

+ * + *

+ * StatefulJob instances follow slightly different rules from + * regular Job instances. The key difference is that their + * associated {@link JobDataMap} is re-persisted after every + * execution of the job, thus preserving state for the next execution. The + * other difference is that stateful jobs are not allowed to execute + * concurrently, which means new triggers that occur before the completion of + * the execute(xx) method will be delayed. + *

+ * + * @see Job + * @see JobDetail + * @see JobDataMap + * @see Scheduler + * + * @author James House + */ +public interface StatefulJob extends Job { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + +} Index: 3rdParty_sources/quartz/org/quartz/Trigger.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/Trigger.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/Trigger.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,931 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import java.util.Date; +import java.util.LinkedList; + + +/** + *

+ * The base abstract class to be extended by all Triggers. + *

+ * + *

+ * Triggers s have a name and group associated with them, which + * should uniquely identify them within a single {@link Scheduler}. + *

+ * + *

+ * Triggers are the 'mechanism' by which Job s + * are scheduled. Many Trigger s can point to the same Job, + * but a single Trigger can only point to one Job. + *

+ * + *

+ * Triggers can 'send' parameters/data to Jobs by placing contents + * into the JobDataMap on the Trigger. + *

+ * + * @see SimpleTrigger + * @see CronTrigger + * @see NthIncludedDayTrigger + * @see TriggerUtils + * @see JobDataMap + * @see JobExecutionContext + * + * @author James House + * @author Sharada Jambula + */ +public abstract class Trigger implements java.io.Serializable, Cloneable, + Comparable { + + private static final long serialVersionUID = -3904243490805975570L; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Instructs the {@link Scheduler} that the {@link Trigger} + * has no further instructions. + *

+ */ + public static final int INSTRUCTION_NOOP = 0; + + /** + *

+ * Instructs the {@link Scheduler} that the {@link Trigger} + * wants the {@link org.quartz.JobDetail} to re-execute + * immediately. If not in a 'RECOVERING' or 'FAILED_OVER' situation, the + * execution context will be re-used (giving the Job the + * abilitiy to 'see' anything placed in the context by its last execution). + *

+ */ + public static final int INSTRUCTION_RE_EXECUTE_JOB = 1; + + /** + *

+ * Instructs the {@link Scheduler} that the {@link Trigger} + * should be put in the COMPLETE state. + *

+ */ + public static final int INSTRUCTION_SET_TRIGGER_COMPLETE = 2; + + /** + *

+ * Instructs the {@link Scheduler} that the {@link Trigger} + * wants itself deleted. + *

+ */ + public static final int INSTRUCTION_DELETE_TRIGGER = 3; + + /** + *

+ * Instructs the {@link Scheduler} that all Trigger + * s referencing the same {@link org.quartz.JobDetail} as + * this one should be put in the COMPLETE state. + *

+ */ + public static final int INSTRUCTION_SET_ALL_JOB_TRIGGERS_COMPLETE = 4; + + /** + *

+ * Instructs the {@link Scheduler} that all Trigger + * s referencing the same {@link org.quartz.JobDetail} as + * this one should be put in the ERROR state. + *

+ */ + public static final int INSTRUCTION_SET_TRIGGER_ERROR = 5; + + /** + *

+ * Instructs the {@link Scheduler} that the Trigger + * should be put in the ERROR state. + *

+ */ + public static final int INSTRUCTION_SET_ALL_JOB_TRIGGERS_ERROR = 6; + + /** + *

+ * Instructs the {@link Scheduler} that upon a mis-fire + * situation, the updateAfterMisfire() method will be called + * on the Trigger to determine the mis-fire instruction. + *

+ * + *

+ * In order to see if this instruction fits your needs, you should look at + * the documentation for the getSmartMisfirePolicy() method + * on the particular Trigger implementation you are using. + *

+ */ + public static final int MISFIRE_INSTRUCTION_SMART_POLICY = 0; + + /** + *

+ * Indicates that the Trigger is in the "normal" state. + *

+ */ + public final static int STATE_NORMAL = 0; + + /** + *

+ * Indicates that the Trigger is in the "paused" state. + *

+ */ + public final static int STATE_PAUSED = 1; + + /** + *

+ * Indicates that the Trigger is in the "complete" state. + *

+ * + *

+ * "Complete" indicates that the trigger has not remaining fire-times in + * its schedule. + *

+ */ + public final static int STATE_COMPLETE = 2; + + /** + *

+ * Indicates that the Trigger is in the "error" state. + *

+ * + *

+ * A Trigger arrives at the error state when the scheduler + * attempts to fire it, but cannot due to an error creating and executing + * its related job. Often this is due to the Job's + * class not existing in the classpath. + *

+ * + *

+ * When the trigger is in the error state, the scheduler will make no + * attempts to fire it. + *

+ */ + public final static int STATE_ERROR = 3; + + + /** + *

+ * Indicates that the Trigger is in the "blocked" state. + *

+ * + *

+ * A Trigger arrives at the blocked state when the job that + * it is associated with is a StatefulJob and it is + * currently executing. + *

+ * + * @see StatefulJob + */ + public final static int STATE_BLOCKED = 4; + + /** + *

+ * Indicates that the Trigger does not exist. + *

+ */ + public final static int STATE_NONE = -1; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private String name; + + private String group = Scheduler.DEFAULT_GROUP; + + private String jobName; + + private String jobGroup = Scheduler.DEFAULT_GROUP; + + private String description; + + private JobDataMap jobDataMap; + + private boolean volatility = false; + + private String calendarName = null; + + private String fireInstanceId = null; + + private int misfireInstruction = MISFIRE_INSTRUCTION_SMART_POLICY; + + private LinkedList triggerListeners = new LinkedList(); + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a Trigger with no specified name, group, or {@link org.quartz.JobDetail}. + *

+ * + *

+ * Note that the {@link #setName(String)},{@link #setGroup(String)}and + * the {@link #setJobName(String)}and {@link #setJobGroup(String)}methods + * must be called before the Trigger can be placed into a + * {@link Scheduler}. + *

+ */ + public Trigger() { + // do nothing... + } + + /** + *

+ * Create a Trigger with the given name, and group. + *

+ * + *

+ * Note that the {@link #setJobName(String)}and + * {@link #setJobGroup(String)}methods must be called before the Trigger + * can be placed into a {@link Scheduler}. + *

+ * + * @param group if null, Scheduler.DEFAULT_GROUP will be used. + * + * @exception IllegalArgumentException + * if name is null or empty, or the group is an empty string. + */ + public Trigger(String name, String group) { + setName(name); + setGroup(group); + } + + /** + *

+ * Create a Trigger with the given name, and group. + *

+ * + * @param group if null, Scheduler.DEFAULT_GROUP will be used. + * + * @exception IllegalArgumentException + * if name is null or empty, or the group is an empty string. + */ + public Trigger(String name, String group, String jobName, String jobGroup) { + setName(name); + setGroup(group); + setJobName(jobName); + setJobGroup(jobGroup); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Get the name of this Trigger. + *

+ */ + public String getName() { + return name; + } + + /** + *

+ * Set the name of this Trigger. + *

+ * + * @exception IllegalArgumentException + * if name is null or empty. + */ + public void setName(String name) { + if (name == null || name.trim().length() == 0) + throw new IllegalArgumentException( + "Trigger name cannot be null or empty."); + + this.name = name; + } + + /** + *

+ * Get the group of this Trigger. + *

+ */ + public String getGroup() { + return group; + } + + /** + *

+ * Set the name of this Trigger. + *

+ * + * @param group if null, Scheduler.DEFAULT_GROUP will be used. + * + * @exception IllegalArgumentException + * if group is an empty string. + */ + public void setGroup(String group) { + if (group != null && group.trim().length() == 0) + throw new IllegalArgumentException( + "Group name cannot be an empty string."); + + if(group == null) + group = Scheduler.DEFAULT_GROUP; + + this.group = group; + } + + /** + *

+ * Get the name of the associated {@link org.quartz.JobDetail}. + *

+ */ + public String getJobName() { + return jobName; + } + + /** + *

+ * Set the name of the associated {@link org.quartz.JobDetail}. + *

+ * + * @exception IllegalArgumentException + * if jobName is null or empty. + */ + public void setJobName(String jobName) { + if (jobName == null || jobName.trim().length() == 0) + throw new IllegalArgumentException( + "Job name cannot be null or empty."); + + this.jobName = jobName; + } + + /** + *

+ * Get the name of the associated {@link org.quartz.JobDetail}'s + * group. + *

+ */ + public String getJobGroup() { + return jobGroup; + } + + /** + *

+ * Set the name of the associated {@link org.quartz.JobDetail}'s + * group. + *

+ * + * @param group if null, Scheduler.DEFAULT_GROUP will be used. + * + * @exception IllegalArgumentException + * if group is an empty string. + */ + public void setJobGroup(String jobGroup) { + if (jobGroup != null && jobGroup.trim().length() == 0) + throw new IllegalArgumentException( + "Group name cannot be null or empty."); + + if(jobGroup == null) + jobGroup = Scheduler.DEFAULT_GROUP; + + this.jobGroup = jobGroup; + } + + /** + *

+ * Returns the 'full name' of the Trigger in the format + * "group.name". + *

+ */ + public String getFullName() { + return group + "." + name; + } + + /** + *

+ * Returns the 'full name' of the Job that the Trigger + * points to, in the format "group.name". + *

+ */ + public String getFullJobName() { + return jobGroup + "." + jobName; + } + + /** + *

+ * Return the description given to the Trigger instance by + * its creator (if any). + *

+ * + * @return null if no description was set. + */ + public String getDescription() { + return description; + } + + /** + *

+ * Set a description for the Trigger instance - may be + * useful for remembering/displaying the purpose of the trigger, though the + * description has no meaning to Quartz. + *

+ */ + public void setDescription(String description) { + this.description = description; + } + + /** + *

+ * Set whether or not the Trigger should be persisted in the + * {@link org.quartz.spi.JobStore} for re-use after program + * restarts. + *

+ */ + public void setVolatility(boolean volatility) { + this.volatility = volatility; + } + + /** + *

+ * Associate the {@link Calendar} with the given name with + * this Trigger. + *

+ * + * @param calendarName + * use null to dis-associate a Calendar. + */ + public void setCalendarName(String calendarName) { + this.calendarName = calendarName; + } + + /** + *

+ * Get the name of the {@link Calendar} associated with this + * Trigger. + *

+ * + * @return null if there is no associated Calendar. + */ + public String getCalendarName() { + return calendarName; + } + + /** + *

+ * Get the JobDataMap that is associated with the + * Trigger. + *

+ * + *

+ * Changes made to this map during job execution are not re-persisted, and + * in fact typically result in an IllegalStateException. + *

+ */ + public JobDataMap getJobDataMap() { + if (jobDataMap == null) jobDataMap = new JobDataMap(); + return jobDataMap; + } + + + /** + *

+ * Set the JobDataMap to be associated with the + * Trigger. + *

+ */ + public void setJobDataMap(JobDataMap jobDataMap) { + this.jobDataMap = jobDataMap; + } + + /** + *

+ * Whether or not the Trigger should be persisted in the + * {@link org.quartz.spi.JobStore} for re-use after program + * restarts. + *

+ * + *

+ * If not explicitly set, the default value is false. + *

+ * + * @return true if the Trigger should be + * garbage collected along with the {@link Scheduler}. + */ + public boolean isVolatile() { + return volatility; + } + + /** + *

+ * Add the specified name of a {@link TriggerListener} to + * the end of the Trigger's list of listeners. + *

+ */ + public void addTriggerListener(String name) { + triggerListeners.add(name); + } + + /** + *

+ * Remove the specified name of a {@link TriggerListener} + * from the Trigger's list of listeners. + *

+ * + * @return true if the given name was found in the list, and removed + */ + public boolean removeTriggerListener(String name) { + return triggerListeners.remove(name); + } + + /** + *

+ * Returns an array of String s containing the names of all + * {@link TriggerListener} assigned to the Trigger, + * in the order in which they should be notified. + *

+ */ + public String[] getTriggerListenerNames() { + String[] outNames = new String[triggerListeners.size()]; + return (String[]) triggerListeners.toArray(outNames); + } + + /** + *

+ * This method should not be used by the Quartz client. + *

+ * + *

+ * Called when the {@link Scheduler} has decided to 'fire' + * the trigger (execute the associated Job), in order to + * give the Trigger a chance to update itself for its next + * triggering (if any). + *

+ * + * @see #executionComplete(JobExecutionContext, JobExecutionException) + */ + public abstract void triggered(Calendar calendar); + + /** + *

+ * This method should not be used by the Quartz client. + *

+ * + *

+ * Called by the scheduler at the time a Trigger is first + * added to the scheduler, in order to have the Trigger + * compute its first fire time, based on any associated calendar. + *

+ * + *

+ * After this method has been called, getNextFireTime() + * should return a valid answer. + *

+ * + * @return the first time at which the Trigger will be fired + * by the scheduler, which is also the same value getNextFireTime() + * will return (until after the first firing of the Trigger). + *

+ */ + public abstract Date computeFirstFireTime(Calendar calendar); + + /** + *

+ * This method should not be used by the Quartz client. + *

+ * + *

+ * Called after the {@link Scheduler} has executed the + * {@link org.quartz.JobDetail} associated with the Trigger + * in order to get the final instruction code from the trigger. + *

+ * + * @param context + * is the JobExecutionContext that was used by the + * Job'sexecute(xx) method. + * @param result + * is the JobExecutionException thrown by the + * Job, if any (may be null). + * @return one of the Trigger.INSTRUCTION_XXX constants. + * + * @see #INSTRUCTION_NOOP + * @see #INSTRUCTION_RE_EXECUTE_JOB + * @see #INSTRUCTION_DELETE_TRIGGER + * @see #INSTRUCTION_SET_TRIGGER_COMPLETE + * @see #triggered(Calendar) + */ + public abstract int executionComplete(JobExecutionContext context, + JobExecutionException result); + + /** + *

+ * Used by the {@link Scheduler} to determine whether or not + * it is possible for this Trigger to fire again. + *

+ * + *

+ * If the returned value is false then the Scheduler + * may remove the Trigger from the {@link org.quartz.spi.JobStore}. + *

+ */ + public abstract boolean mayFireAgain(); + + /** + *

+ * Get the time at which the Trigger should occur. + *

+ */ + public abstract Date getStartTime(); + + public abstract void setStartTime(Date startTime); + + public abstract void setEndTime(Date endTime); + + /** + *

+ * Get the time at which the Trigger should quit repeating - + * even if an assigned 'repeatCount' isn't yet satisfied. + *

+ * + * @see #getFinalFireTime() + */ + public abstract Date getEndTime(); + + /** + *

+ * Returns the next time at which the Trigger will fire. If + * the trigger will not fire again, null will be returned. + * The value returned is not guaranteed to be valid until after the Trigger + * has been added to the scheduler. + *

+ */ + public abstract Date getNextFireTime(); + + /** + *

+ * Returns the previous time at which the Trigger will fire. + * If the trigger has not yet fired, null will be returned. + */ + public abstract Date getPreviousFireTime(); + + /** + *

+ * Returns the next time at which the Trigger will fire, + * after the given time. If the trigger will not fire after the given time, + * null will be returned. + *

+ */ + public abstract Date getFireTimeAfter(Date afterTime); + + /** + *

+ * Returns the last time at which the Trigger will fire, if + * the Trigger will repeat indefinitely, null will be returned. + *

+ * + *

+ * Note that the return time *may* be in the past. + *

+ */ + public abstract Date getFinalFireTime(); + + /** + *

+ * Set the instruction the Scheduler should be given for + * handling misfire situations for this Trigger- the + * concrete Trigger type that you are using will have + * defined a set of additional MISFIRE_INSTRUCTION_XXX + * constants that may be passed to this method. + *

+ * + *

+ * If not explicitly set, the default value is MISFIRE_INSTRUCTION_SMART_POLICY. + *

+ * + * @see #MISFIRE_INSTRUCTION_SMART_POLICY + * @see #updateAfterMisfire(Calendar) + * @see SimpleTrigger + * @see CronTrigger + */ + public void setMisfireInstruction(int misfireInstruction) { + if (!validateMisfireInstruction(misfireInstruction)) + throw new IllegalArgumentException( + "The misfire instruction code is invalid for this type of trigger."); + this.misfireInstruction = misfireInstruction; + } + + protected abstract boolean validateMisfireInstruction(int misfireInstruction); + + /** + *

+ * Get the instruction the Scheduler should be given for + * handling misfire situations for this Trigger- the + * concrete Trigger type that you are using will have + * defined a set of additional MISFIRE_INSTRUCTION_XXX + * constants that may be passed to this method. + *

+ * + *

+ * If not explicitly set, the default value is MISFIRE_INSTRUCTION_SMART_POLICY. + *

+ * + * @see #MISFIRE_INSTRUCTION_SMART_POLICY + * @see #updateAfterMisfire(Calendar) + * @see SimpleTrigger + * @see CronTrigger + */ + public int getMisfireInstruction() { + return misfireInstruction; + } + + /** + *

+ * This method should not be used by the Quartz client. + *

+ * + *

+ * To be implemented by the concrete classes that extend this class. + *

+ * + *

+ * The implementation should update the Trigger's state + * based on the MISFIRE_INSTRUCTION_XXX that was selected when the Trigger + * was created. + *

+ */ + public abstract void updateAfterMisfire(Calendar cal); + + /** + *

+ * This method should not be used by the Quartz client. + *

+ * + *

+ * To be implemented by the concrete class. + *

+ * + *

+ * The implementation should update the Trigger's state + * based on the given new version of the associated Calendar + * (the state should be updated so that it's next fire time is appropriate + * given the Calendar's new settings). + *

+ * + * @param cal + */ + public abstract void updateWithNewCalendar(Calendar cal, long misfireThreshold); + + /** + *

+ * Validates whether the properties of the JobDetail are + * valid for submission into a Scheduler. + * + * @throws IllegalStateException + * if a required property (such as Name, Group, Class) is not + * set. + */ + public void validate() throws SchedulerException { + if (name == null) + throw new SchedulerException("Trigger's name cannot be null", + SchedulerException.ERR_CLIENT_ERROR); + + if (group == null) + throw new SchedulerException("Trigger's group cannot be null", + SchedulerException.ERR_CLIENT_ERROR); + + if (jobName == null) + throw new SchedulerException( + "Trigger's related Job's name cannot be null", + SchedulerException.ERR_CLIENT_ERROR); + + if (jobGroup == null) + throw new SchedulerException( + "Trigger's related Job's group cannot be null", + SchedulerException.ERR_CLIENT_ERROR); + } + + /** + *

+ * This method should not be used by the Quartz client. + *

+ * + *

+ * Usable by {@link org.quartz.spi.JobStore} + * implementations, in order to facilitate 'recognizing' instances of fired + * Trigger s as their jobs complete execution. + *

+ * + * + */ + public void setFireInstanceId(String id) { + this.fireInstanceId = id; + } + + /** + *

+ * This method should not be used by the Quartz client. + *

+ */ + public String getFireInstanceId() { + return fireInstanceId; + } + + /** + *

+ * Return a simple string representation of this object. + *

+ */ + public String toString() { + return "Trigger '" + getFullName() + "': triggerClass: '" + + getClass().getName() + " isVolatile: " + isVolatile() + + " calendar: '" + getCalendarName() + "' misfireInstruction: " + + getMisfireInstruction() + " nextFireTime: " + getNextFireTime(); + } + + /** + *

+ * Compare the next fire time of this Trigger to that of + * another. + *

+ */ + public int compareTo(Object obj) { + Trigger other = (Trigger) obj; + + Date myTime = getNextFireTime(); + Date otherTime = other.getNextFireTime(); + + if (myTime == null && otherTime == null) return 0; + + if (myTime == null) return 1; + + if (otherTime == null) return -1; + + if(myTime.before(otherTime)) + return -1; + + if(myTime.after(otherTime)) + return 1; + + return 0; + } + + public boolean equals(Object obj) { + if (!(obj instanceof Trigger)) return false; + + Trigger other = (Trigger) obj; + + if (!other.getName().equals(getName())) return false; + if (!other.getGroup().equals(getGroup())) return false; + + return true; + } + + + public int hashCode() { + return getFullName().hashCode(); + } + + public Object clone() { + Trigger copy; + try { + copy = (Trigger) super.clone(); + } catch (CloneNotSupportedException ex) { + throw new IncompatibleClassChangeError("Not Cloneable."); + } + return copy; + } + +} Index: 3rdParty_sources/quartz/org/quartz/TriggerListener.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/TriggerListener.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/TriggerListener.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,134 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +/** + *

+ * The interface to be implemented by classes that want to be informed when a + * {@link Trigger} fires. In general, applications that use a + * Scheduler will not have use for this mechanism. + *

+ * + * @see Scheduler + * @see Trigger + * @see JobListener + * @see JobExecutionContext + * + * @author James House + */ +public interface TriggerListener { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Get the name of the TriggerListener. + *

+ */ + public String getName(); + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * has fired, and it's associated {@link org.quartz.JobDetail} + * is about to be executed. + *

+ * + *

+ * It is called before the vetoJobExecution(..) method of this + * interface. + *

+ * + * @param trigger + * The Trigger that has fired. + * @param context + * The JobExecutionContext that will be passed to + * the Job'sexecute(xx) method. + */ + public void triggerFired(Trigger trigger, JobExecutionContext context); + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * has fired, and it's associated {@link org.quartz.JobDetail} + * is about to be executed. + *

+ * + *

+ * It is called after the triggerFired(..) method of this + * interface. + *

+ * + * @param trigger + * The Trigger that has fired. + * @param context + * The JobExecutionContext that will be passed to + * the Job'sexecute(xx) method. + */ + public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context); + + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * has misfired. + *

+ * + *

+ * Consideration should be given to how much time is spent in this method, + * as it will affect all triggers that are misfiring. If you have lots + * of triggers misfiring at once, it could be an issue it this method + * does a lot. + *

+ * + * @param trigger + * The Trigger that has misfired. + */ + public void triggerMisfired(Trigger trigger); + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * has fired, it's associated {@link org.quartz.JobDetail} + * has been executed, and it's triggered(xx) method has been + * called. + *

+ * + * @param trigger + * The Trigger that was fired. + * @param context + * The JobExecutionContext that was passed to the + * Job'sexecute(xx) method. + * @param triggerIntructionCode + * the result of the call on the Trigger'striggered(xx) + * method. + */ + public void triggerComplete(Trigger trigger, JobExecutionContext context, + int triggerInstructionCode); + +} Index: 3rdParty_sources/quartz/org/quartz/TriggerUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/TriggerUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/TriggerUtils.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,1365 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import java.util.Calendar; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; +import java.util.TimeZone; + +/** + *

+ * Convenience and utility methods for simplifying the construction and + * configuration of {@link Trigger}s. + *

+ * + *

+ * Please submit suggestions for additional convenience methods to either the + * Quartz user forum or the developer's mail list at + * source forge. + *

+ * + * @see CronTrigger + * @see SimpleTrigger + * + * @author James House + */ +public class TriggerUtils { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static final int SUNDAY = 1; + + public static final int MONDAY = 2; + + public static final int TUESDAY = 3; + + public static final int WEDNESDAY = 4; + + public static final int THURSDAY = 5; + + public static final int FRIDAY = 6; + + public static final int SATURDAY = 7; + + public static final int LAST_DAY_OF_MONTH = -1; + + public static final long MILLISECONDS_IN_MINUTE = 60l * 1000l; + + public static final long MILLISECONDS_IN_HOUR = 60l * 60l * 1000l; + + public static final long SECONDS_IN_DAY = 24l * 60l * 60L; + + public static final long MILLISECONDS_IN_DAY = SECONDS_IN_DAY * 1000l; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private static void validateDayOfWeek(int dayOfWeek) { + if (dayOfWeek < SUNDAY || dayOfWeek > SATURDAY) + throw new IllegalArgumentException("Invalid day of week."); + } + + private static void validateHour(int hour) { + if (hour < 0 || hour > 23) + throw new IllegalArgumentException( + "Invalid hour (must be >= 0 and <= 23)."); + } + + private static void validateMinute(int minute) { + if (minute < 0 || minute > 59) + throw new IllegalArgumentException( + "Invalid minute (must be >= 0 and <= 59)."); + } + + private static void validateSecond(int second) { + if (second < 0 || second > 59) + throw new IllegalArgumentException( + "Invalid second (must be >= 0 and <= 59)."); + } + + private static void validateDayOfMonth(int day) { + if ((day < 1 || day > 31) && day != LAST_DAY_OF_MONTH) + throw new IllegalArgumentException("Invalid day of month."); + } + + private static void validateMonth(int month) { + if (month < 1 || month > 12) + throw new IllegalArgumentException( + "Invalid month (must be >= 1 and <= 12."); + } + + private static void validateYear(int year) { + if (year < 1970 || year > 2099) + throw new IllegalArgumentException( + "Invalid year (must be >= 1970 and <= 2099."); + } + + /** + *

+ * Set the given Trigger's name to the given value, and its + * group to the default group (Scheduler.DEFAULT_GROUP). + *

+ * + * @param trig the tigger to change name to + * @param name the new trigger name + */ + public static void setTriggerIdentity(Trigger trig, String name) { + setTriggerIdentity(trig, name, Scheduler.DEFAULT_GROUP); + } + + /** + *

+ * Set the given Trigger's name to the given value, and its + * group to the given group. + *

+ * + * @param trig the tigger to change name to + * @param name the new trigger name + * @param group the new trigger group + */ + public static void setTriggerIdentity( + Trigger trig, String name, String group) { + trig.setName(name); + trig.setGroup(group); + } + + /** + *

+ * Make a trigger that will fire every day at the given time. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param hour the hour (0-23) upon which to fire + * @param minute the minute (0-59) upon which to fire + * @return the new trigger + */ + public static Trigger makeDailyTrigger(int hour, int minute) { + validateHour(hour); + validateMinute(minute); + + CronTrigger trig = new CronTrigger(); + + try { + trig.setCronExpression("0 " + minute + " " + hour + " ? * *"); + } catch (Exception ignore) { + return null; /* never happens... */ + } + + trig.setStartTime(new Date()); + + return trig; + } + + /** + *

+ * Make a trigger that will fire every day at the given time. + *

+ * + *

+ * The generated trigger will not have its group or end-time set. + * The Start time defaults to 'now'. + *

+ * + * @param trigName the trigger's name + * @param hour the hour (0-23) upon which to fire + * @param minute the minute (0-59) upon which to fire + * @return the newly created trigger + */ + public static Trigger makeDailyTrigger( + String trigName, int hour, int minute) { + Trigger trig = makeDailyTrigger(hour, minute); + trig.setName(trigName); + return trig; + } + + /** + *

+ * Make a trigger that will fire every week at the given day and time. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param dayOfWeek (1-7) the day of week upon which to fire + * @param hour the hour (0-23) upon which to fire + * @param minute the minute (0-59) upon which to fire + * @return the new trigger + * + * @see #SUNDAY + * @see #MONDAY + * @see #TUESDAY + * @see #WEDNESDAY + * @see #THURSDAY + * @see #FRIDAY + * @see #SATURDAY + */ + public static Trigger makeWeeklyTrigger( + int dayOfWeek, int hour, int minute) { + validateDayOfWeek(dayOfWeek); + validateHour(hour); + validateMinute(minute); + + CronTrigger trig = new CronTrigger(); + + try { + trig.setCronExpression("0 " + minute + " " + hour + " ? * " + + dayOfWeek); + } catch (Exception ignore) { + return null; /* never happens... */ + } + + trig.setStartTime(new Date()); + + return trig; + } + + /** + *

+ * Make a trigger that will fire every week at the given day and time. + *

+ * + *

+ * The generated trigger will not have its group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param trigName the trigger's name + * @param dayOfWeek (1-7) the day of week upon which to fire + * @param hour the hour (0-23) upon which to fire + * @param minute the minute (0-59) upon which to fire + * @return the newly created trigger + * + * @see #SUNDAY + * @see #MONDAY + * @see #TUESDAY + * @see #WEDNESDAY + * @see #THURSDAY + * @see #FRIDAY + * @see #SATURDAY + */ + public static Trigger makeWeeklyTrigger( + String trigName, int dayOfWeek, int hour, int minute) { + Trigger trig = makeWeeklyTrigger(dayOfWeek, hour, minute); + trig.setName(trigName); + return trig; + } + + + /** + *

+ * Make a trigger that will fire every month at the given day and time. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + *

+ * If the day of the month specified does not occur in a given month, a + * firing will not occur that month. (i.e. if dayOfMonth is specified as + * 31, no firing will occur in the months of the year with fewer than 31 + * days). + *

+ * + * @param dayOfMonth (1-31, or -1) the day of week upon which to fire + * @param hour the hour (0-23) upon which to fire + * @param minute the minute (0-59) upon which to fire + * @return the newly created trigger + */ + public static Trigger makeMonthlyTrigger( + int dayOfMonth, int hour, int minute) { + validateDayOfMonth(dayOfMonth); + validateHour(hour); + validateMinute(minute); + + CronTrigger trig = new CronTrigger(); + + try { + if (dayOfMonth != LAST_DAY_OF_MONTH) trig.setCronExpression("0 " + + minute + " " + hour + " " + dayOfMonth + " * ?"); + else + trig.setCronExpression("0 " + minute + " " + hour + " L * ?"); + } catch (Exception ignore) { + return null; /* never happens... */ + } + + trig.setStartTime(new Date()); + + return trig; + } + + /** + *

+ * Make a trigger that will fire every month at the given day and time. + *

+ * + *

+ * The generated trigger will not have its group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + *

+ * If the day of the month specified does not occur in a given month, a + * firing will not occur that month. (i.e. if dayOfMonth is specified as + * 31, no firing will occur in the months of the year with fewer than 31 + * days). + *

+ * + * @param trigName the trigger's name + * @param dayOfMonth (1-31, or -1) the day of week upon which to fire + * @param hour the hour (0-23) upon which to fire + * @param minute the minute (0-59) upon which to fire + * @return the newly created trigger + */ + public static Trigger makeMonthlyTrigger( + String trigName, int dayOfMonth, int hour, int minute) { + Trigger trig = makeMonthlyTrigger(dayOfMonth, hour, minute); + trig.setName(trigName); + return trig; + } + + /* + *

Make a trigger that will fire every N days at the given time.

+ * + *

TThe generated trigger will not have its name, group, + * start-time and end-time set.

+ * + * @param hour the hour (0-23) upon which to fire @param minute the minute + * (0-59) upon which to fire @param interval the number of days between + * firings public static Trigger makeDailyTrigger(int interval, int hour, + * int minute) { + * + * SimpleTrigger trig = new SimpleTrigger(); + * + * MILLISECONDS_IN_DAY); + * trig.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY); + * + * return trig; + * } + */ + + /** + *

+ * Make a trigger that will fire repeatCount times, waiting + * repeatInterval milliseconds between each fire. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param repeatCount the number of times to fire the trigger + * @param repeatInterval the number of milliseconds to wait between fires + * @return the newly created trigger + */ + public static Trigger makeImmediateTrigger( + int repeatCount, long repeatInterval) { + SimpleTrigger trig = new SimpleTrigger(); + trig.setStartTime( new Date() ); + trig.setRepeatCount(repeatCount); + trig.setRepeatInterval(repeatInterval); + return trig; + } + + /** + *

+ * Make a trigger that will fire repeatCount times, waiting + * repeatInterval milliseconds between each fire. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param trigName the trigger's name + * @param repeatCount the number of times to fire the trigger + * @param repeatInterval the number of milliseconds to wait between fires + * @return the new trigger + */ + public static Trigger makeImmediateTrigger( + String trigName, int repeatCount, long repeatInterval) { + Trigger trig = makeImmediateTrigger(repeatCount, repeatInterval); + trig.setName(trigName); + return trig; + } + + /** + *

+ * Make a trigger that will fire every second, indefinitely. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * @return the new trigger + */ + public static Trigger makeSecondlyTrigger() { + return makeSecondlyTrigger(1, SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every second, indefinitely. + *

+ * + *

+ * The generated trigger will not have its group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param trigName the trigger's name + * @return the new trigger + */ + public static Trigger makeSecondlyTrigger(String trigName) { + return makeSecondlyTrigger( + trigName, 1, SimpleTrigger.REPEAT_INDEFINITELY); + } + + + /** + *

+ * Make a trigger that will fire every N seconds, indefinitely. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param intervalInSeconds the number of seconds between firings + * @return the new trigger + */ + public static Trigger makeSecondlyTrigger(int intervalInSeconds) { + return makeSecondlyTrigger( + intervalInSeconds, SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every N seconds, with the given number of + * repeats. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param intervalInSeconds the number of seconds between firings + * @param repeatCount the number of times to repeat the firing + * @return the new trigger + */ + public static Trigger makeSecondlyTrigger( + int intervalInSeconds, int repeatCount) { + SimpleTrigger trig = new SimpleTrigger(); + + trig.setRepeatInterval(intervalInSeconds * 1000l); + trig.setRepeatCount(repeatCount); + + return trig; + } + + /** + *

+ * Make a trigger that will fire every N seconds, with the given number of + * repeats. + *

+ * + *

+ * The generated trigger will not have its group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param trigName the trigger's name + * @param intervalInSeconds the number of seconds between firings + * @param repeatCount the number of times to repeat the firing + * @return the new trigger + */ + public static Trigger makeSecondlyTrigger( + String trigName, int intervalInSeconds, int repeatCount) { + Trigger trig = makeSecondlyTrigger(intervalInSeconds, repeatCount); + trig.setName(trigName); + return trig; + } + + /** + *

+ * Make a trigger that will fire every minute, indefinitely. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @return the new trigger + */ + public static Trigger makeMinutelyTrigger() { + return makeMinutelyTrigger(1, SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every minute, indefinitely. + *

+ * + *

+ * The generated trigger will not have its group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param trigName the trigger's name + * @return the new trigger + */ + public static Trigger makeMinutelyTrigger(String trigName) { + return makeMinutelyTrigger( + trigName, 1, SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every N minutes, indefinitely. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param intervalInMinutes the number of minutes between firings + * @return the new trigger + */ + public static Trigger makeMinutelyTrigger(int intervalInMinutes) { + return makeMinutelyTrigger( + intervalInMinutes, SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every N minutes, with the given number of + * repeats. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param intervalInMinutes the number of minutes between firings + * @param repeatCount the number of times to repeat the firing + * @return the new trigger + */ + public static Trigger makeMinutelyTrigger( + int intervalInMinutes, int repeatCount) { + SimpleTrigger trig = new SimpleTrigger(); + + trig.setRepeatInterval(intervalInMinutes * MILLISECONDS_IN_MINUTE); + trig.setRepeatCount(repeatCount); + + trig.setStartTime(new Date()); + + return trig; + } + + /** + *

+ * Make a trigger that will fire every N minutes, with the given number of + * repeats. + *

+ * + *

+ * The generated trigger will not have its group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param trigName the trigger's name + * @param intervalInMinutes the number of minutes between firings + * @param repeatCount the number of times to repeat the firing + * @return the new trigger + */ + public static Trigger makeMinutelyTrigger( + String trigName, int intervalInMinutes, int repeatCount) { + Trigger trig = makeMinutelyTrigger(intervalInMinutes, repeatCount); + trig.setName(trigName); + return trig; + } + + /** + *

+ * Make a trigger that will fire every hour, indefinitely. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @return the new trigger + */ + public static Trigger makeHourlyTrigger() { + return makeHourlyTrigger(1, SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every hour, indefinitely. + *

+ * + *

+ * The generated trigger will not have its group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param trigName the trigger's name + * @return the new trigger + */ + public static Trigger makeHourlyTrigger(String trigName) { + return makeHourlyTrigger( + trigName, 1, SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every N hours, indefinitely. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param intervalInHours the number of hours between firings + * @return the new trigger + */ + public static Trigger makeHourlyTrigger(int intervalInHours) { + return makeHourlyTrigger( + intervalInHours, SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every N hours, with the given number of + * repeats. + *

+ * + *

+ * The generated trigger will not have its name, group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param intervalInHours the number of hours between firings + * @param repeatCount the number of times to repeat the firing + * @return the new trigger + */ + public static Trigger makeHourlyTrigger( + int intervalInHours, int repeatCount) { + SimpleTrigger trig = new SimpleTrigger(); + + trig.setRepeatInterval(intervalInHours * MILLISECONDS_IN_HOUR); + trig.setRepeatCount(repeatCount); + + trig.setStartTime(new Date()); + + return trig; + } + + /** + *

+ * Make a trigger that will fire every N hours, with the given number of + * repeats. + *

+ * + *

+ * The generated trigger will not have its group, + * or end-time set. The Start time defaults to 'now'. + *

+ * + * @param trigName the trigger's name + * @param intervalInHours the number of hours between firings + * @param repeatCount the number of times to repeat the firing + * @return the new trigger + */ + public static Trigger makeHourlyTrigger( + String trigName, int intervalInHours, int repeatCount) { + Trigger trig =makeHourlyTrigger(intervalInHours, repeatCount); + trig.setName(trigName); + return trig; + } + + /** + *

+ * Returns a date that is rounded to the next even hour above the given + * date. + *

+ * + *

+ * For example an input date with a time of 08:13:54 would result in a date + * with the time of 09:00:00. If the date's time is in the 23rd hour, the + * date's 'day' will be promoted, and the time will be set to 00:00:00. + *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * @return the new rounded date + */ + public static Date getEvenHourDate(Date date) { + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.setLenient(true); + + c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) + 1); + c.set(Calendar.MINUTE, 0); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Returns a date that is rounded to the previous even hour below the given + * date. + *

+ * + *

+ * For example an input date with a time of 08:13:54 would result in a date + * with the time of 08:00:00. + *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * @return the new rounded date + */ + public static Date getEvenHourDateBefore(Date date) { + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + + c.set(Calendar.MINUTE, 0); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Returns a date that is rounded to the next even minute above the given + * date. + *

+ * + *

+ * For example an input date with a time of 08:13:54 would result in a date + * with the time of 08:14:00. If the date's time is in the 59th minute, + * then the hour (and possibly the day) will be promoted. + *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * @return the new rounded date + */ + public static Date getEvenMinuteDate(Date date) { + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.setLenient(true); + + c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + 1); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Returns a date that is rounded to the previous even minute below the + * given date. + *

+ * + *

+ * For example an input date with a time of 08:13:54 would result in a date + * with the time of 08:13:00. + *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * @return the new rounded date + */ + public static Date getEvenMinuteDateBefore(Date date) { + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Returns a date that is rounded to the next even second above the given + * date. + *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * @return the new rounded date + */ + public static Date getEvenSecondDate(Date date) { + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.setLenient(true); + + c.set(Calendar.SECOND, c.get(Calendar.SECOND) + 1); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Returns a date that is rounded to the previous even second below the + * given date. + *

+ * + *

+ * For example an input date with a time of 08:13:54.341 would result in a + * date with the time of 08:13:00.000. + *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * @return the new rounded date + */ + public static Date getEvenSecondDateBefore(Date date) { + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Returns a date that is rounded to the next even multiple of the given + * minute. + *

+ * + *

+ * For example an input date with a time of 08:13:54, and an input + * minute-base of 5 would result in a date with the time of 08:15:00. The + * same input date with an input minute-base of 10 would result in a date + * with the time of 08:20:00. But a date with the time 08:53:31 and an + * input minute-base of 45 would result in 09:00:00, because the even-hour + * is the next 'base' for 45-minute intervals. + *

+ * + *

+ * More examples: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Input TimeMinute-BaseResult Time
11:16:412011:20:00
11:36:412011:40:00
11:46:412012:00:00
11:26:413011:30:00
11:36:413012:00:00
11:16:411711:17:00
11:17:411711:34:00
11:52:411712:00:00
11:52:41511:55:00
11:57:41512:00:00
11:17:41012:00:00
11:17:41111:08:00
+ *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * @param minuteBase + * the base-minute to set the time on + * @return the new rounded date + * + * @see #getNextGivenSecondDate(Date, int) + */ + public static Date getNextGivenMinuteDate(Date date, int minuteBase) { + if (minuteBase < 0 || minuteBase > 59) + throw new IllegalArgumentException( + "minuteBase must be >=0 and <= 59"); + + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.setLenient(true); + + if (minuteBase == 0) { + c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) + 1); + c.set(Calendar.MINUTE, 0); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + int minute = c.get(Calendar.MINUTE); + + int arItr = minute / minuteBase; + + int nextMinuteOccurance = minuteBase * (arItr + 1); + + if (nextMinuteOccurance < 60) { + c.set(Calendar.MINUTE, nextMinuteOccurance); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } else { + c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) + 1); + c.set(Calendar.MINUTE, 0); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + } + + /** + *

+ * Returns a date that is rounded to the next even multiple of the given + * minute. + *

+ * + *

+ * The rules for calculating the second are the same as those for + * calculating the minute in the method + * getNextGivenMinuteDate(..). + *

+ * + * @param date the Date to round, if null the current time will + * be used + * @param secondBase the base-second to set the time on + * @return the new rounded date + * + * @see #getNextGivenMinuteDate(Date, int) + */ + public static Date getNextGivenSecondDate(Date date, int secondBase) { + if (secondBase < 0 || secondBase > 59) + throw new IllegalArgumentException( + "secondBase must be >=0 and <= 59"); + + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.setLenient(true); + + if (secondBase == 0) { + c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + 1); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + int second = c.get(Calendar.SECOND); + + int arItr = second / secondBase; + + int nextSecondOccurance = secondBase * (arItr + 1); + + if (nextSecondOccurance < 60) { + c.set(Calendar.SECOND, nextSecondOccurance); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } else { + c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + 1); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + } + + /** + *

+ * Get a Date object that represents the given time, on + * today's date. + *

+ * + * @param second + * The value (0-59) to give the seconds field of the date + * @param minute + * The value (0-59) to give the minutes field of the date + * @param hour + * The value (0-23) to give the hours field of the date + * @return the new date + */ + public static Date getDateOf(int second, int minute, int hour) { + validateSecond(second); + validateMinute(minute); + validateHour(hour); + + Date date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.setLenient(true); + + c.set(Calendar.HOUR_OF_DAY, hour); + c.set(Calendar.MINUTE, minute); + c.set(Calendar.SECOND, second); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Get a Date object that represents the given time, on the + * given date. + *

+ * + * @param second + * The value (0-59) to give the seconds field of the date + * @param minute + * The value (0-59) to give the minutes field of the date + * @param hour + * The value (0-23) to give the hours field of the date + * @param dayOfMonth + * The value (1-31) to give the day of month field of the date + * @param month + * The value (1-12) to give the month field of the date + * @return the new date + */ + public static Date getDateOf(int second, int minute, int hour, + int dayOfMonth, int month) { + validateSecond(second); + validateMinute(minute); + validateHour(hour); + validateDayOfMonth(dayOfMonth); + validateMonth(month); + + Date date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + + c.set(Calendar.MONTH, month - 1); + c.set(Calendar.DAY_OF_MONTH, dayOfMonth); + c.set(Calendar.HOUR_OF_DAY, hour); + c.set(Calendar.MINUTE, minute); + c.set(Calendar.SECOND, second); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Get a Date object that represents the given time, on the + * given date. + *

+ * + * @param second + * The value (0-59) to give the seconds field of the date + * @param minute + * The value (0-59) to give the minutes field of the date + * @param hour + * The value (0-23) to give the hours field of the date + * @param dayOfMonth + * The value (1-31) to give the day of month field of the date + * @param month + * The value (1-12) to give the month field of the date + * @param year + * The value (1970-2099) to give the year field of the date + * @return the new date + */ + public static Date getDateOf(int second, int minute, int hour, + int dayOfMonth, int month, int year) { + validateSecond(second); + validateMinute(minute); + validateHour(hour); + validateDayOfMonth(dayOfMonth); + validateMonth(month); + validateYear(year); + + Date date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + + c.set(Calendar.YEAR, year); + c.set(Calendar.MONTH, month - 1); + c.set(Calendar.DAY_OF_MONTH, dayOfMonth); + c.set(Calendar.HOUR_OF_DAY, hour); + c.set(Calendar.MINUTE, minute); + c.set(Calendar.SECOND, second); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + * Returns a list of Dates that are the next fire times of a + * Trigger. + * The input trigger will be cloned before any work is done, so you need + * not worry about its state being altered by this method. + * + * @param trigg + * The trigger upon which to do the work + * @param cal + * The calendar to apply to the trigger's schedule + * @param numTimes + * The number of next fire times to produce + * @return List of java.util.Date objects + */ + public static List computeFireTimes(Trigger trigg, org.quartz.Calendar cal, + int numTimes) { + LinkedList lst = new LinkedList(); + + Trigger t = (Trigger) trigg.clone(); + + if (t.getNextFireTime() == null) { + t.computeFirstFireTime(cal); + } + + for (int i = 0; i < numTimes; i++) { + Date d = t.getNextFireTime(); + if (d != null) { + lst.add(d); + t.triggered(cal); + } else + break; + } + + return java.util.Collections.unmodifiableList(lst); + } + + /** + * Returns a list of Dates that are the next fire times of a + * Trigger + * that fall within the given date range. The input trigger will be cloned + * before any work is done, so you need not worry about its state being + * altered by this method. + * + *

+ * NOTE: if this is a trigger that has previously fired within the given + * date range, then firings which have already occured will not be listed + * in the output List. + *

+ * + * @param trigg + * The trigger upon which to do the work + * @param cal + * The calendar to apply to the trigger's schedule + * @param from + * The starting date at which to find fire times + * @param to + * The ending date at which to stop finding fire times + * @return List of java.util.Date objects + */ + public static List computeFireTimesBetween(Trigger trigg, + org.quartz.Calendar cal, Date from, Date to) { + LinkedList lst = new LinkedList(); + + Trigger t = (Trigger) trigg.clone(); + + if (t.getNextFireTime() == null) { + t.setStartTime(from); + t.setEndTime(to); + t.computeFirstFireTime(cal); + } + + // TODO: this method could be more efficient by using logic specific + // to the type of trigger ... + while (true) { + Date d = t.getNextFireTime(); + if (d != null) { + if (d.before(from)) { + t.triggered(cal); + continue; + } + if (d.after(to)) break; + lst.add(d); + t.triggered(cal); + } else + break; + } + + return java.util.Collections.unmodifiableList(lst); + } + + /** + * Translate a date & time from a users timezone to the another + * (probably server) timezone to assist in creating a simple trigger with + * the right date & time. + * + * @param date the date to translate + * @param src the original time-zone + * @param dest the destination time-zone + * @return the translated date + */ + public static Date translateTime(Date date, TimeZone src, TimeZone dest) { + + Date newDate = new Date(); + + int offset = ( + getOffset(date.getTime(), dest) - getOffset(date.getTime(), src) + ); + + newDate.setTime(date.getTime() - offset); + + return newDate; + } + + /** + * Gets the offset from UT for the given date in the given timezone, + * taking into account daylight savings. + * + *

+ * Equivalent of TimeZone.getOffset(date) in JDK 1.4, but Quartz is trying + * to support JDK 1.3. + *

+ * + * @param date the date (in milliseconds) that is the base for the offset + * @param tz the time-zone to calculate to offset to + * @return the offset + */ + public static int getOffset(long date, TimeZone tz) { + + if (tz.inDaylightTime(new Date(date))) { + return tz.getRawOffset() + getDSTSavings(tz); + } + + return tz.getRawOffset(); + } + + /** + *

+ * Equivalent of TimeZone.getDSTSavings() in JDK 1.4, but Quartz is trying + * to support JDK 1.3. + *

+ * + * @param tz the target time-zone + * @return the amount of saving time in milliseconds + */ + public static int getDSTSavings(TimeZone tz) { + + if (tz.useDaylightTime()) { + return 3600000; + } + return 0; + } +} Index: 3rdParty_sources/quartz/org/quartz/UICronTrigger.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/UICronTrigger.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/UICronTrigger.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,1353 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz; + +import org.quartz.Job; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.quartz.Scheduler; +import org.quartz.SimpleTrigger; +import org.quartz.Trigger; +import org.quartz.CronTrigger; + +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TimeZone; +import java.util.TreeSet; +import java.text.ParseException; + +/** + *

+ * A concrete {@link Trigger} that is used to fire a {@link Job} + * at given moments in time, defined with Unix 'cron-like' definitions. + *

+ * + *

+ * What you should know about this particular trigger is that it is based on + * org.quartz.CronTrigger, but the the functionality to build the sets from a + * string are unused. Whereas CronTrigger would essentially deserialize by + * rebuilding the TreeSets from the cronExpression, this class does not have a + * cronExpression, and de/serializes the TreeSets in their entirety. This is + * because the TreeSets map directly to the Struts user interface for set + * selection, and no effort is made to write an interpreter to map them back + * and forth between legacy UN*X cron expressions that CronTrigger uses. + *

+ * + *

+ * The method I use with this trigger is to instantiate it, then put it in the + * ActionForm of a Struts bean, then let Struts manipulate it directly through + * BeanUtils. You are by no means required to do that, but to fully understand + * the concepts here, at least until there is better documentation, you should + * understand how it works within that context first so you can write the + * appropriate code that Struts does for you for free. I'll try to explain that + * here. + *

+ * + *

+ * Struts JSP tags allow the user to use Apache BeanUtils to reference + * components of beans by path. This is to say that a bean Foo + * that has an accessor method Bar getBar() and given + * Bar + * has a primitive type String as a field named splat, + * one can set the field to "new string value" as follows: + *

+ * + * // create a new Foo with contained reference to a new Bar + * Foo fooBean = new Foo(); + * fooBean.setBar(new Bar()); + * // set the splat string in the Bar bean from Foo + * BeanUtils.setProperty(fooBean, "bar.splat", "new string value"); + * + *

+ * In turn, Struts JSP tags use the bean addressing provided by BeanUtils to + * address accessor methods within the bean graph that is rooted with the + * ActionForm that is put into the Action context. + *

+ *

+ * Finally, having all this allows you to put direct selection lists on the + * screen of the UI, then map them directly into the UICronTrigger bean. Given + * a ActionForm bean that was set up to contain a UICronTrigger + * in a field called trigger, the following HTML code will + * completely create your UI in Struts: + *

+ * + * + * + * Date + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * Time + * + * + * + * + * + * + * + * + * + * + *

+ * So if you don't want to use Struts, what you have to do is take the + * information that was submitted on the form in the HTML select ranges, + * iterate each of them, and add the values to the appropriate sets in the + * fields of this class. Make sense? + *

+ * + * Note that this is not as versatile as the standard CronTrigger. There are + * tricks with "last day of month" and repeating sets that need to be manually + * selected, and sets that can happen for date ranges much longer than we can + * reasonably map with direct selection in a UI. + * + * @see org.quartz.CronTrigger + * @see Trigger + * @see SimpleTrigger + * + * @author Brian Topping + * @author based on code by Sharada Jambula, James House, Mads Henderson + * @deprecated + */ +public class UICronTrigger extends Trigger { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Instructs the {@link Scheduler} that upon a mis-fire + * situation, the {@link org.quartz.CronTrigger} wants to be + * fired now by Scheduler. + *

+ */ + public static final int MISFIRE_INSTRUCTION_FIRE_ONCE_NOW = 1; + + /** + *

+ * Instructs the {@link Scheduler} that upon a mis-fire + * situation, the {@link org.quartz.CronTrigger} wants to + * have it's next-fire-time updated to the next time in the schedule after + * the current time, but it does not to be fired now. + *

+ */ + public static final int MISFIRE_INSTRUCTION_DO_NOTHING = 2; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + private static final int ALL_SPEC_INT = 99; // '*' + + private static final int NO_SPEC_INT = 98; // '?' + + private static final Integer ALL_SPEC = new Integer(ALL_SPEC_INT); + + private static final Integer NO_SPEC = new Integer(NO_SPEC_INT); + + private static Map monthMap = new HashMap(20); + + private static Map dayMap = new HashMap(60); + + static { + monthMap.put("JAN", new Integer(0)); + monthMap.put("FEB", new Integer(1)); + monthMap.put("MAR", new Integer(2)); + monthMap.put("APR", new Integer(3)); + monthMap.put("MAY", new Integer(4)); + monthMap.put("JUN", new Integer(5)); + monthMap.put("JUL", new Integer(6)); + monthMap.put("AUG", new Integer(7)); + monthMap.put("SEP", new Integer(8)); + monthMap.put("OCT", new Integer(9)); + monthMap.put("NOV", new Integer(10)); + monthMap.put("DEC", new Integer(11)); + + dayMap.put("SUN", new Integer(1)); + dayMap.put("MON", new Integer(2)); + dayMap.put("TUE", new Integer(3)); + dayMap.put("WED", new Integer(4)); + dayMap.put("THU", new Integer(5)); + dayMap.put("FRI", new Integer(6)); + dayMap.put("SAT", new Integer(7)); + } + + private Date startTime = null; + + private Date endTime = null; + + private Date nextFireTime = null; + + private TimeZone timeZone = null; + + private Date previousFireTime = null; + + private TreeSet seconds = null; + + private TreeSet minutes = null; + + private TreeSet hours = null; + + private TreeSet daysOfMonth = null; + + private TreeSet months = null; + + private TreeSet daysOfWeek = null; + + private TreeSet years = null; + + private transient boolean lastdayOfWeek = false; + + private transient int nthdayOfWeek = 0; + + private transient boolean lastdayOfMonth = false; + + private transient boolean calendardayOfWeek = false; + + private transient boolean calendardayOfMonth = false; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public void reset() { + seconds = new TreeSet(); + minutes = new TreeSet(); + hours = new TreeSet(); + daysOfMonth = new TreeSet(); + months = new TreeSet(); + daysOfWeek = new TreeSet(); + years = new TreeSet(); + + // we always fire on the minute + seconds.add(new Integer(0)); + + minutes.add(ALL_SPEC); + for (int i = 0; i < 60; i++) + minutes.add(new Integer(i)); + + hours.add(ALL_SPEC); + for (int i = 0; i < 24; i++) + hours.add(new Integer(i)); + + daysOfMonth.add(ALL_SPEC); + for (int i = 1; i <= 31; i++) + daysOfMonth.add(new Integer(i)); + + months.add(ALL_SPEC); + for (int i = 1; i <= 12; i++) + months.add(new Integer(i)); + + daysOfWeek.add(NO_SPEC); + + years.add(ALL_SPEC); + for (int i = 1970; i <= 2099; i++) + years.add(new Integer(i)); + + startTime = new Date(); + setStartTime(startTime); + setTimeZone(TimeZone.getDefault()); + } + + /** + *

+ * Create a CronTrigger with no settings. + *

+ */ + public UICronTrigger() { + super(); + reset(); + } + + /** + *

+ * Create a CronTrigger with the given name and group. + *

+ */ + public UICronTrigger(String name, String group) { + super(name, group); + reset(); + } + + /** + *

+ * Create a CronTrigger with the given name and group, and + * associated with the identified {@link Job}. + *

+ */ + public UICronTrigger(String name, String group, String jobName, + String jobGroup) { + super(name, group, jobName, jobGroup); + reset(); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Get the time at which the CronTrigger should occur. + *

+ */ + public Date getStartTime() { + return this.startTime; + } + + public void setStartTime(Date startTime) { + if (startTime == null) + throw new IllegalArgumentException("Start time cannot be null"); + + Date eTime = getEndTime(); + if (eTime != null && startTime != null && eTime.before(startTime)) + throw new IllegalArgumentException( + "End time cannot be before start time"); + + + // round off millisecond... + // Note timeZone is not needed here as parameter for + // Calendar.getInstance(), since time zone is implicit + // when using a Date in the setTime method. + Calendar cl = Calendar.getInstance(); + cl.setTime(startTime); + cl.set(Calendar.MILLISECOND, 0); + + this.startTime = cl.getTime(); + } + + /** + *

+ * Get the time at which the CronTrigger should quit + * repeating - even if repeastCount isn't yet satisfied. + *

+ * + * @see #getFinalFireTime() + */ + public Date getEndTime() { + return this.endTime; + } + + public void setEndTime(Date endTime) { + Date sTime = getStartTime(); + if (sTime != null && endTime != null && sTime.after(endTime)) + throw new IllegalArgumentException( + "End time cannot be before start time"); + + this.endTime = endTime; + } + + /** + *

+ * Returns the next time at which the CronTrigger will fire. + * If the trigger will not fire again, null will be + * returned. The value returned is not guaranteed to be valid until after + * the Trigger has been added to the scheduler. + *

+ */ + public Date getNextFireTime() { + return this.nextFireTime; + } + + public void updateAfterMisfire(org.quartz.Calendar cal) { + int instr = getMisfireInstruction(); + + if (instr == MISFIRE_INSTRUCTION_SMART_POLICY) + instr = MISFIRE_INSTRUCTION_DO_NOTHING; + + if (instr == MISFIRE_INSTRUCTION_DO_NOTHING) { + Date newFireTime = getFireTimeAfter(new Date()); + while (newFireTime != null && cal != null + && !cal.isTimeIncluded(newFireTime.getTime())) { + newFireTime = getFireTimeAfter(newFireTime); + } + + setNextFireTime(newFireTime); + + } else if (instr == MISFIRE_INSTRUCTION_FIRE_ONCE_NOW) { + setNextFireTime(new Date()); + } + } + + public Date getPreviousFireTime() { + return this.previousFireTime; + } + + /** + *

+ * Set the previous time at which the SimpleTrigger fired. + *

+ * + *

+ * This method should not be invoked by client code. + *

+ */ + public void setPreviousFireTime(Date previousFireTime) { + this.previousFireTime = previousFireTime; + } + + /** + *

+ * Sets the next time at which the CronTrigger will fire. If + * the trigger will not fire again, null will be returned. + *

+ */ + public void setNextFireTime(Date nextFireTime) { + this.nextFireTime = nextFireTime; + } + + /** + *

+ * Returns the time zone for which the cronExpression of + * this CronTrigger will be resolved. + *

+ */ + public TimeZone getTimeZone() { + return this.timeZone; + } + + /** + *

+ * Sets the time zone for which the cronExpression of this + * CronTrigger will be resolved. + *

+ */ + public void setTimeZone(TimeZone timeZone) { + this.timeZone = timeZone; + } + + /** + *

+ * Returns the next time at which the CronTrigger will fire, + * after the given time. If the trigger will not fire after the given time, + * null will be returned. + *

+ * + *

+ * Note that the date returned is NOT validated against the related + * org.quartz.Calendar (if any) + *

+ */ + public Date getFireTimeAfter(Date afterTime) { + if (afterTime == null) afterTime = new Date(); + + if (startTime.after(afterTime)) + afterTime = new Date(startTime.getTime() - 1000l); + + Date pot = getTimeAfter(afterTime); + if (endTime != null && pot != null && pot.after(endTime)) return null; + + return pot; + } + + /** + *

+ * Returns the final time at which the CronTrigger will + * fire. + *

+ * + *

+ * Note that the return time *may* be in the past. and the date returned is + * not validated against org.quartz.calendar + *

+ */ + public Date getFinalFireTime() { + if (this.endTime != null) return getTimeBefore(this.endTime); + else + return null; + } + + /** + *

+ * Determines whether or not the CronTrigger will occur + * again. + *

+ */ + public boolean mayFireAgain() { + return (getNextFireTime() != null); + } + + protected boolean validateMisfireInstruction(int misfireInstruction) { + if (misfireInstruction < MISFIRE_INSTRUCTION_SMART_POLICY) + return false; + + if (misfireInstruction > MISFIRE_INSTRUCTION_DO_NOTHING) return false; + + return true; + } + + /** + *

+ * Updates the CronTrigger's state based on the + * MISFIRE_INSTRUCTION_XXX that was selected when the SimpleTrigger + * was created. + *

+ * + *

+ * If the misfire instruction is set to MISFIRE_INSTRUCTION_SMART_POLICY, + * then the following scheme will be used:
+ *

    + *
  • The instruction will be interpreted as MISFIRE_INSTRUCTION_DO_NOTHING + *
+ *

+ */ + public void updateAfterMisfire() { + int instr = getMisfireInstruction(); + + if (instr == MISFIRE_INSTRUCTION_SMART_POLICY) + instr = MISFIRE_INSTRUCTION_DO_NOTHING; + + if (instr == MISFIRE_INSTRUCTION_DO_NOTHING) { + setNextFireTime(getFireTimeAfter(new Date())); + } else if (instr == MISFIRE_INSTRUCTION_FIRE_ONCE_NOW) { + setNextFireTime(new Date()); + } + } + + /** + *

+ * Determines whether the date & time of the given java.util.Calendar + * instance falls on a scheduled fire-time of this trigger. + *

+ * + *

+ * Note that the date returned is NOT validated against the related + * org.quartz.Calendar (if any) + *

+ */ + public boolean willFireOn(Calendar test) { + Integer second = new Integer(test.get(Calendar.SECOND)); + Integer minute = new Integer(test.get(Calendar.MINUTE)); + Integer hour = new Integer(test.get(Calendar.HOUR_OF_DAY)); + Integer day = new Integer(test.get(Calendar.DAY_OF_MONTH)); + Integer month = new Integer(test.get(Calendar.MONTH)); + + if ((seconds.contains(second) || seconds.contains(ALL_SPEC)) + && (minutes.contains(minute) || minutes.contains(ALL_SPEC)) + && (hours.contains(hour) || hours.contains(ALL_SPEC)) + && (daysOfMonth.contains(day) || daysOfMonth.contains(ALL_SPEC)) + && (months.contains(month) || months.contains(ALL_SPEC))) { + + return true; } + + return false; + } + + /** + *

+ * Called after the {@link Scheduler} has executed the + * {@link Job} associated with the Trigger in + * order to get the final instruction code from the trigger. + *

+ * + * @param context + * is the JobExecutionContext that was used by the + * Job'sexecute(xx) method. + * @param result + * is the JobExecutionException thrown by the + * Job, if any (may be null). + * @return one of the Trigger.INSTRUCTION_XXX constants. + * + * @see #INSTRUCTION_NOOP + * @see #INSTRUCTION_RE_EXECUTE_JOB + * @see #INSTRUCTION_DELETE_TRIGGER + * @see #INSTRUCTION_SET_TRIGGER_COMPLETE + * @see #triggered(Calendar) + */ + public int executionComplete(JobExecutionContext context, + JobExecutionException result) { + if (result != null && result.refireImmediately()) + return Trigger.INSTRUCTION_RE_EXECUTE_JOB; + + if (result != null && result.refireImmediately()) + return INSTRUCTION_RE_EXECUTE_JOB; + + if (result != null && result.unscheduleFiringTrigger()) + return INSTRUCTION_SET_TRIGGER_COMPLETE; + + if (result != null && result.unscheduleAllTriggers()) + return INSTRUCTION_SET_ALL_JOB_TRIGGERS_COMPLETE; + + if (!mayFireAgain()) return INSTRUCTION_DELETE_TRIGGER; + + return INSTRUCTION_NOOP; + } + + /** + *

+ * Called when the {@link Scheduler} has decided to 'fire' + * the trigger (execute the associated Job), in order to + * give the Trigger a chance to update itself for its next + * triggering (if any). + *

+ * + * @see #executionComplete(JobExecutionContext, JobExecutionException) + */ + public void triggered(org.quartz.Calendar calendar) { + previousFireTime = nextFireTime; + nextFireTime = getFireTimeAfter(nextFireTime); + + while (nextFireTime != null && calendar != null + && !calendar.isTimeIncluded(nextFireTime.getTime())) { + nextFireTime = getFireTimeAfter(nextFireTime); + } + } + + /** + * + * @see org.quartz.Trigger#updateWithNewCalendar(org.quartz.Calendar, long) + */ + public void updateWithNewCalendar(org.quartz.Calendar calendar, long misfireThreshold) + { + nextFireTime = getFireTimeAfter(previousFireTime); + + Date now = new Date(); + do { + while (nextFireTime != null && calendar != null + && !calendar.isTimeIncluded(nextFireTime.getTime())) { + nextFireTime = getFireTimeAfter(nextFireTime); + } + + if(nextFireTime != null && nextFireTime.before(now)) { + long diff = now.getTime() - nextFireTime.getTime(); + if(diff >= misfireThreshold) { + nextFireTime = getFireTimeAfter(nextFireTime); + continue; + } + } + }while(false); + } + + /** + *

+ * Called by the scheduler at the time a Trigger is first + * added to the scheduler, in order to have the Trigger + * compute its first fire time, based on any associated calendar. + *

+ * + *

+ * After this method has been called, getNextFireTime() + * should return a valid answer. + *

+ * + * @return the first time at which the Trigger will be fired + * by the scheduler, which is also the same value getNextFireTime() + * will return (until after the first firing of the Trigger). + *

+ */ + public Date computeFirstFireTime(org.quartz.Calendar calendar) { + nextFireTime = getFireTimeAfter(new Date(startTime.getTime() - 1000l)); + + while (nextFireTime != null && calendar != null + && !calendar.isTimeIncluded(nextFireTime.getTime())) { + nextFireTime = getFireTimeAfter(nextFireTime); + } + + return nextFireTime; + } + + public String getExpressionSummary() { + StringBuffer buf = new StringBuffer(); + + buf.append("seconds: "); + buf.append(getExpressionSetSummary(seconds)); + buf.append("\n"); + buf.append("minutes: "); + buf.append(getExpressionSetSummary(minutes)); + buf.append("\n"); + buf.append("hours: "); + buf.append(getExpressionSetSummary(hours)); + buf.append("\n"); + buf.append("daysOfMonth: "); + buf.append(getExpressionSetSummary(daysOfMonth)); + buf.append("\n"); + buf.append("months: "); + buf.append(getExpressionSetSummary(months)); + buf.append("\n"); + buf.append("daysOfWeek: "); + buf.append(getExpressionSetSummary(daysOfWeek)); + buf.append("\n"); + buf.append("lastdayOfWeek: "); + buf.append(lastdayOfWeek); + buf.append("\n"); + buf.append("lastdayOfMonth: "); + buf.append(lastdayOfMonth); + buf.append("\n"); + buf.append("calendardayOfWeek: "); + buf.append(calendardayOfWeek); + buf.append("\n"); + buf.append("calendardayOfMonth: "); + buf.append(calendardayOfMonth); + buf.append("\n"); + buf.append("years: "); + buf.append(getExpressionSetSummary(years)); + buf.append("\n"); + + return buf.toString(); + } + + private String getExpressionSetSummary(Set set) { + + if (set.contains(NO_SPEC)) return "?"; + if (set.contains(ALL_SPEC)) return "*"; + + StringBuffer buf = new StringBuffer(); + + Iterator itr = set.iterator(); + boolean first = true; + while (itr.hasNext()) { + Integer iVal = (Integer) itr.next(); + String val = iVal.toString(); + if (!first) buf.append(","); + buf.append(val); + first = false; + } + + return buf.toString(); + } + + //////////////////////////////////////////////////////////////////////////// + // + // Computation Functions + // + //////////////////////////////////////////////////////////////////////////// + + private Date getTimeAfter(Date afterTime) { + Calendar cl = Calendar.getInstance(timeZone); + + // move ahead one second, since we're computing the time *after* the + // given time + afterTime = new Date(afterTime.getTime() + 1000); + // CronTrigger does not deal with milliseconds + cl.setTime(afterTime); + cl.set(Calendar.MILLISECOND, 0); + + boolean gotOne = false; + + // loop until we've computed the next time, or we've past the endTime + while (!gotOne) { + + if (endTime != null && cl.getTime().after(endTime)) return null; + + SortedSet st = null; + int t = 0; + + int sec = cl.get(Calendar.SECOND); + int min = cl.get(Calendar.MINUTE); + + // get second................................................. + st = seconds.tailSet(new Integer(sec)); + if (st != null && st.size() != 0) { + sec = ((Integer) st.first()).intValue(); + } else { + sec = ((Integer) seconds.first()).intValue(); + min++; + cl.set(Calendar.MINUTE, min); + } + cl.set(Calendar.SECOND, sec); + + min = cl.get(Calendar.MINUTE); + int hr = cl.get(Calendar.HOUR_OF_DAY); + t = -1; + + // get minute................................................. + st = minutes.tailSet(new Integer(min)); + if (st != null && st.size() != 0) { + t = min; + min = ((Integer) st.first()).intValue(); + } else { + min = ((Integer) minutes.first()).intValue(); + hr++; + } + if (min != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, min); + cl.set(Calendar.HOUR_OF_DAY, hr); + continue; + } + cl.set(Calendar.MINUTE, min); + + hr = cl.get(Calendar.HOUR_OF_DAY); + int day = cl.get(Calendar.DAY_OF_MONTH); + t = -1; + + // get hour................................................... + st = hours.tailSet(new Integer(hr)); + if (st != null && st.size() != 0) { + t = hr; + hr = ((Integer) st.first()).intValue(); + } else { + hr = ((Integer) hours.first()).intValue(); + day++; + } + if (hr != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, hr); + cl.set(Calendar.DAY_OF_MONTH, day); + continue; + } + cl.set(Calendar.HOUR_OF_DAY, hr); + + day = cl.get(Calendar.DAY_OF_MONTH); + int mon = cl.get(Calendar.MONTH) + 1; // '+ 1' because calendar is + // 0-based for this field, + // and we are 1-based + t = -1; + + // get day................................................... + boolean dayOfMSpec = !daysOfMonth.contains(NO_SPEC); + boolean dayOfWSpec = !daysOfWeek.contains(NO_SPEC); + if (dayOfMSpec && !dayOfWSpec) { // get day only by day of month + // rule + st = daysOfMonth.tailSet(new Integer(day)); + if (lastdayOfMonth) { + t = day; + day = getLastDayOfMonth(mon); + } else if (st != null && st.size() != 0) { + t = day; + day = ((Integer) st.first()).intValue(); + } else { + day = ((Integer) daysOfMonth.first()).intValue(); + mon++; + } + if (day != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, day); + cl.set(Calendar.MONTH, mon - 1); // '- 1' because calendar + // is 0-based for this + // field, and we are + // 1-based + continue; + } + } else if (dayOfWSpec && !dayOfMSpec) { // get day only by day of + // week rule + if (lastdayOfWeek) { // are we looking for the last XXX day of + // the month? + int dow = ((Integer) daysOfWeek.first()).intValue(); // desired + // d-o-w + int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w + int daysToAdd = 0; + if (cDow < dow) daysToAdd = dow - cDow; + if (cDow > dow) daysToAdd = dow + (7 - cDow); + + int lDay = getLastDayOfMonth(mon); + + if (day + daysToAdd > lDay) { // did we already miss the + // last one? + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon); // no '- 1' here because + // we are promoting the + // month + continue; + } + + // find date of last occurance of this day in this month... + while ((day + daysToAdd + 7) <= lDay) + daysToAdd += 7; + + day += daysToAdd; + } else if (nthdayOfWeek != 0) { // are we looking for the Nth + // XXX day in the month? + int dow = ((Integer) daysOfWeek.first()).intValue(); // desired + // d-o-w + int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w + int daysToAdd = 0; + if (cDow < dow) daysToAdd = dow - cDow; + else if (cDow > dow) daysToAdd = dow + (7 - cDow); + + day += daysToAdd; + int weekOfMonth = day / 7; + if (day % 7 > 0) weekOfMonth++; + + daysToAdd = (nthdayOfWeek - weekOfMonth) * 7; + day += daysToAdd; + if (daysToAdd < 0 || day > getLastDayOfMonth(mon)) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon); // no '- 1' here because + // we are promoting the + // month + continue; + } + } else { + int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w + int dow = ((Integer) daysOfWeek.first()).intValue(); // desired + // d-o-w + st = daysOfWeek.tailSet(new Integer(cDow)); + if (st != null && st.size() > 0) { + dow = ((Integer) st.first()).intValue(); + } + + int daysToAdd = 0; + if (cDow < dow) daysToAdd = dow - cDow; + if (cDow > dow) daysToAdd = dow + (7 - cDow); + + int lDay = getLastDayOfMonth(mon); + + if (day + daysToAdd > lDay) { // will we pass the end of + // the month? + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon); // no '- 1' here because + // we are promoting the + // month + continue; + } else if (daysToAdd > 0) { // are we swithing days? + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, day + daysToAdd); + cl.set(Calendar.MONTH, mon - 1); // '- 1' because + // calendar is 0-based + // for this field, and + // we are 1-based + continue; + } + } + } else { // dayOfWSpec && !dayOfMSpec + throw new UnsupportedOperationException( + "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented."); // TODO: + } + cl.set(Calendar.DAY_OF_MONTH, day); + + mon = cl.get(Calendar.MONTH) + 1; // '+ 1' because calendar is + // 0-based for this field, and we + // are 1-based + int year = cl.get(Calendar.YEAR); + t = -1; + + // get month................................................... + st = months.tailSet(new Integer(mon)); + if (st != null && st.size() != 0) { + t = mon; + mon = ((Integer) st.first()).intValue(); + } else { + mon = ((Integer) months.first()).intValue(); + year++; + } + if (mon != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon - 1); // '- 1' because calendar is + // 0-based for this field, and + // we are 1-based + cl.set(Calendar.YEAR, year); + continue; + } + cl.set(Calendar.MONTH, mon - 1); // '- 1' because calendar is + // 0-based for this field, and we + // are 1-based + + year = cl.get(Calendar.YEAR); + t = -1; + + // get year................................................... + st = years.tailSet(new Integer(year)); + if (st != null && st.size() != 0) { + t = year; + year = ((Integer) st.first()).intValue(); + } else + return null; // ran out of years... + + if (year != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon - 1); // '- 1' because calendar is + // 0-based for this field, and + // we are 1-based + cl.set(Calendar.YEAR, year); + continue; + } + cl.set(Calendar.YEAR, year); + + gotOne = true; + } // while( !done ) + + return cl.getTime(); + } + + private Date getTimeBefore(Date endTime) // TODO: implement + { + return null; + } + + public boolean isLeapYear() { + Calendar cl = Calendar.getInstance(timeZone); + int year = cl.get(Calendar.YEAR); + + if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) return true; + else + return false; + } + + public int getLastDayOfMonth(int monthNum) { + + switch (monthNum) { + case 1: + return 31; + case 2: + return (isLeapYear()) ? 29 : 28; + case 3: + return 31; + case 4: + return 30; + case 5: + return 31; + case 6: + return 30; + case 7: + return 31; + case 8: + return 31; + case 9: + return 30; + case 10: + return 31; + case 11: + return 30; + case 12: + return 31; + default: + throw new IllegalArgumentException("Illegal month number: " + + monthNum); + } + } + + public Integer[] getSecondsValues() { + Integer list[] = new Integer[60]; + for (int i = 0; i < 60; i++) { + list[i] = new Integer(i); + } + + return list; + } + + public Integer[] getSecondsLabels() { + return getSecondsValues(); + } + + public Integer[] getSeconds() { + Integer list[] = new Integer[seconds.size()]; + if (seconds != null) { + int i = 0; + for (Iterator it = seconds.iterator(); it.hasNext(); i++) { + list[i] = (Integer) it.next(); + } + } + return list; + } + + public void setSeconds(Integer[] val) { + if (seconds != null) seconds.clear(); + else + seconds = new TreeSet(); + + for (int i = 0; i < val.length; i++) { + seconds.add(val[i]); + } + } + + public Integer[] getMinutesValues() { + Integer list[] = new Integer[60]; + for (int i = 0; i < 60; i++) { + list[i] = new Integer(i); + } + + return list; + } + + public Integer[] getMinutesLabels() { + return getMinutesValues(); + } + + public Integer[] getMinutes() { + Integer list[] = new Integer[minutes.size()]; + if (minutes != null) { + int i = 0; + for (Iterator it = minutes.iterator(); it.hasNext(); i++) { + list[i] = (Integer) it.next(); + } + } + return list; + } + + public void setMinutes(Integer[] val) { + if (minutes != null) minutes.clear(); + else + minutes = new TreeSet(); + + for (int i = 0; i < val.length; i++) { + minutes.add(val[i]); + } + } + + public Integer[] getHoursValues() { + Integer list[] = new Integer[24]; + for (int i = 0; i < 24; i++) { + list[i] = new Integer(i); + } + + return list; + } + + public String[] getHoursLabels() { + String vals[] = {"12AM (Midnight)", "1AM", "2AM", "3AM", "4AM", "5AM", + "6AM", "7AM", "8AM", "9AM", "10AM", "11AM", "12PM (Noon)", + "1PM", "2PM", "3PM", "4PM", "5PM", "6PM", "7PM", "8PM", "9PM", + "10PM", "11PM"}; + return vals; + } + + public Integer[] getHours() { + Integer list[] = new Integer[hours.size()]; + if (hours != null) { + int i = 0; + for (Iterator it = hours.iterator(); it.hasNext(); i++) { + list[i] = (Integer) it.next(); + } + } + return list; + } + + public void setHours(Integer[] val) { + if (hours != null) hours.clear(); + else + hours = new TreeSet(); + + for (int i = 0; i < val.length; i++) { + hours.add(val[i]); + } + } + + public Integer[] getDaysOfMonthValues() { + Integer list[] = new Integer[31]; + for (int i = 0; i < 31; i++) { + list[i] = new Integer(i + 1); + } + + return list; + } + + public Integer[] getDaysOfMonthLabels() { + return getDaysOfMonthValues(); + } + + public Integer[] getDaysOfMonth() { + Integer list[] = new Integer[daysOfMonth.size()]; + if (daysOfMonth != null) { + int i = 0; + for (Iterator it = daysOfMonth.iterator(); it.hasNext(); i++) { + list[i] = (Integer) it.next(); + } + } + return list; + } + + public void setDaysOfMonth(Integer[] val) { + if (daysOfMonth != null) daysOfMonth.clear(); + else + daysOfMonth = new TreeSet(); + + for (int i = 0; i < val.length; i++) { + daysOfMonth.add(val[i]); + } + daysOfWeek.clear(); + daysOfWeek.add(NO_SPEC); + } + + public Integer[] getMonthsValues() { + Integer list[] = new Integer[12]; + for (int i = 0; i < 12; i++) { + list[i] = new Integer(i + 1); + } + + return list; + } + + public String[] getMonthsLabels() { + String vals[] = {"January", "February", "March", "April", "May", + "June", "July", "August", "September", "October", "November", + "December"}; + return vals; + } + + public Integer[] getMonths() { + Integer list[] = new Integer[months.size()]; + if (months != null) { + int i = 0; + for (Iterator it = months.iterator(); it.hasNext(); i++) { + list[i] = (Integer) it.next(); + } + } + return list; + } + + public void setMonths(Integer[] val) { + if (months != null) months.clear(); + else + months = new TreeSet(); + + for (int i = 0; i < val.length; i++) { + months.add(val[i]); + } + } + + public String[] getDaysOfWeekLabels() { + String list[] = {"Sunday", "Monday", "Tuesday", "Wednesday", + "Thursday", "Friday", "Saturday"}; + return list; + } + + public Integer[] getDaysOfWeekValues() { + Integer list[] = new Integer[7]; + for (int i = 0; i < 7; i++) + list[i] = new Integer(i + 1); + return list; + } + + public Integer[] getDaysOfWeek() { + Integer list[] = new Integer[daysOfWeek.size()]; + if (daysOfWeek != null) { + int i = 0; + for (Iterator it = daysOfWeek.iterator(); it.hasNext(); i++) { + list[i] = (Integer) it.next(); + } + } + return list; + } + + public void setDaysOfWeek(Integer[] val) { + if (daysOfWeek != null) daysOfWeek.clear(); + else + daysOfWeek = new TreeSet(); + + for (int i = 0; i < val.length; i++) { + daysOfWeek.add(val[i]); + } + + daysOfMonth.clear(); + daysOfMonth.add(NO_SPEC); + } + + public Integer[] getYearsValues() { + Integer list[] = new Integer[20]; + Calendar now = Calendar.getInstance(); + int year = now.get(Calendar.YEAR); + for (int i = 0; i < 20; i++) { + list[i] = new Integer(i + year); + } + + return list; + } + + public Integer[] getYearsLabels() { + return getYearsValues(); + } + + public Integer[] getYears() { + Integer list[] = new Integer[years.size()]; + if (years != null) { + int i = 0; + for (Iterator it = years.iterator(); it.hasNext(); i++) { + list[i] = (Integer) it.next(); + } + } + return list; + } + + public void setYears(Integer[] val) { + if (years != null) years.clear(); + else + years = new TreeSet(); + + for (int i = 0; i < val.length; i++) { + years.add(val[i]); + } + } + + public static void main(String[] argv) { + CronTrigger ct = new CronTrigger("a", "a"); + try { + ct.setCronExpression("0 * * * * ? *"); + } catch (ParseException e) { + // log.error("caught an exception", e); + } + ct.setStartTime(new Date()); + ct.setTimeZone(TimeZone.getDefault()); + System.out.println(ct.getExpressionSummary()); + ct.computeFirstFireTime(null); + + UICronTrigger uict = new UICronTrigger("a", "a"); + Integer set[] = new Integer[1]; + set[0] = new Integer(1); + uict.setSeconds(set); + System.out.println(ct.getExpressionSummary()); + uict.computeFirstFireTime(null); + + } +} Index: 3rdParty_sources/quartz/org/quartz/UnableToInterruptJobException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/UnableToInterruptJobException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/UnableToInterruptJobException.java 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,63 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ + +package org.quartz; + +/** + *

+ * An exception that is thrown to indicate that a call to + * InterruptableJob.interrupt() failed without interrupting the Job. + *

+ * + * @see org.quartz.InterruptableJob#interrupt() + * + * @author James House + */ +public class UnableToInterruptJobException extends SchedulerException { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a UnableToInterruptJobException with the given message. + *

+ */ + public UnableToInterruptJobException(String msg) { + super(msg); + } + + /** + *

+ * Create a UnableToInterruptJobException with the given cause. + *

+ */ + public UnableToInterruptJobException(Exception cause) { + super(cause); + } + +} Index: 3rdParty_sources/quartz/org/quartz/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/package.html 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,15 @@ + + +Package org.quartz + + +

The main package of Quartz, containing the client-side interfaces.

+ +
+
+
+See the Quartz project + at Open Symphony for more information. + + + \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/quartz.properties =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/quartz.properties,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/quartz.properties 17 Aug 2012 15:10:17 -0000 1.1 @@ -0,0 +1,19 @@ +# Default Properties file for use by StdSchedulerFactory +# to create a Quartz Scheduler Instance, if a different +# properties file is not explicitly specified. +# + +org.quartz.scheduler.instanceName = DefaultQuartzScheduler +org.quartz.scheduler.rmi.export = false +org.quartz.scheduler.rmi.proxy = false +org.quartz.scheduler.wrapJobExecutionInUserTransaction = false + +org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool +org.quartz.threadPool.threadCount = 10 +org.quartz.threadPool.threadPriority = 5 +org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true + +org.quartz.jobStore.misfireThreshold = 60000 + +org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore + Index: 3rdParty_sources/quartz/org/quartz/core/JobRunShell.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/core/JobRunShell.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/core/JobRunShell.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,412 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.core; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.Job; +import org.quartz.JobDetail; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.quartz.JobPersistenceException; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.Trigger; +import org.quartz.spi.TriggerFiredBundle; + +/** + *

+ * JobRunShell instances are responsible for providing the 'safe' environment + * for Job s to run in, and for performing all of the work of + * executing the Job, catching ANY thrown exceptions, updating + * the Trigger with the Job's completion code, + * etc. + *

+ * + *

+ * A JobRunShell instance is created by a JobRunShellFactory + * on behalf of the QuartzSchedulerThread which then runs the + * shell in a thread from the configured ThreadPool when the + * scheduler determines that a Job has been triggered. + *

+ * + * @see JobRunShellFactory + * @see org.quartz.core.QuartzSchedulerThread + * @see org.quartz.Job + * @see org.quartz.Trigger + * + * @author James House + */ +public class JobRunShell implements Runnable { + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected JobExecutionContext jec = null; + + protected QuartzScheduler qs = null; + + protected Scheduler scheduler = null; + + protected SchedulingContext schdCtxt = null; + + protected JobRunShellFactory jobRunShellFactory = null; + + protected boolean shutdownRequested = false; + + protected Log log = LogFactory.getLog(getClass()); + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a JobRunShell instance with the given settings. + *

+ * + * @param jobRunShellFactory + * A handle to the JobRunShellFactory that produced + * this JobRunShell. + * @param scheduler + * The Scheduler instance that should be made + * available within the JobExecutionContext. + * @param schdCtxt + * the SchedulingContext that should be used by the + * JobRunShell when making updates to the JobStore. + */ + public JobRunShell(JobRunShellFactory jobRunShellFactory, + Scheduler scheduler, SchedulingContext schdCtxt) { + this.jobRunShellFactory = jobRunShellFactory; + this.scheduler = scheduler; + this.schdCtxt = schdCtxt; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private static Log getLog() + { + return LogFactory.getLog(JobRunShell.class); + } + + public void initialize(QuartzScheduler qs, TriggerFiredBundle firedBundle) + throws SchedulerException { + this.qs = qs; + + Job job = null; + JobDetail jobDetail = firedBundle.getJobDetail(); + + try { + job = qs.getJobFactory().newJob(firedBundle); + } catch (SchedulerException se) { + qs.notifySchedulerListenersError( + "An error occured instantiating job to be executed. job= '" + + jobDetail.getFullName() + "'", se); + throw se; + } catch (Exception e) { + SchedulerException se = new SchedulerException( + "Problem instantiating class '" + + jobDetail.getJobClass().getName() + "'", e); + qs.notifySchedulerListenersError( + "An error occured instantiating job to be executed. job= '" + + jobDetail.getFullName() + "'", se); + throw se; + } catch (Throwable ncdfe) { // such as NoClassDefFoundError + SchedulerException se = new SchedulerException( + "Problem instantiating class '" + + jobDetail.getJobClass().getName() + "' - " + ncdfe); + qs.notifySchedulerListenersError( + "An error occured instantiating job to be executed. job= '" + + jobDetail.getFullName() + "'", se); + throw se; + } + + this.jec = new JobExecutionContext(scheduler, firedBundle, job); + } + + public void requestShutdown() { + shutdownRequested = true; + } + + public void run() { + Trigger trigger = jec.getTrigger(); + JobDetail jobDetail = jec.getJobDetail(); + + do { + + JobExecutionException jobExEx = null; + Job job = jec.getJobInstance(); + + try { + begin(); + } catch (SchedulerException se) { + qs.notifySchedulerListenersError("Error executing Job (" + + jec.getJobDetail().getFullName() + + ": couldn't begin execution.", se); + break; + } + + // notify job & trigger listeners... + try { + if (!notifyListenersBeginning(jec)) break; + } + catch(VetoedException ve) { + try { + complete(true); + } catch (SchedulerException se) { + qs.notifySchedulerListenersError("Error during veto of Job (" + + jec.getJobDetail().getFullName() + + ": couldn't finalize execution.", se); + } + break; + } + + long startTime = System.currentTimeMillis(); + long endTime = startTime; + + // execute the job + try { + log.debug("Calling execute on job " + jobDetail.getFullName()); + job.execute(jec); + endTime = System.currentTimeMillis(); + } catch (JobExecutionException jee) { + endTime = System.currentTimeMillis(); + jobExEx = jee; + getLog().info("Job " + jobDetail.getFullName() + + " threw a JobExecutionException: ", jobExEx); + } catch (Exception e) { + endTime = System.currentTimeMillis(); + getLog().error("Job " + jobDetail.getFullName() + + " threw an unhandled Exception: ", e); + SchedulerException se = new SchedulerException( + "Job threw an unhandled exception.", e); + se.setErrorCode(SchedulerException.ERR_JOB_EXECUTION_THREW_EXCEPTION); + qs.notifySchedulerListenersError("Job (" + + jec.getJobDetail().getFullName() + + " threw an exception.", se); + jobExEx = new JobExecutionException(se, false); + jobExEx.setErrorCode(JobExecutionException.ERR_JOB_EXECUTION_THREW_EXCEPTION); + } + + jec.setJobRunTime(endTime - startTime); + + // notify all job listeners + if (!notifyJobListenersComplete(jec, jobExEx)) break; + + int instCode = Trigger.INSTRUCTION_NOOP; + + // update the trigger + try { + instCode = trigger.executionComplete(jec, jobExEx); + } catch (Exception e) { + // If this happens, there's a bug in the trigger... + SchedulerException se = new SchedulerException( + "Trigger threw an unhandled exception.", e); + se.setErrorCode(SchedulerException.ERR_TRIGGER_THREW_EXCEPTION); + qs.notifySchedulerListenersError( + "Please report this error to the Quartz developers.", + se); + } + + // notify all trigger listeners + if (!notifyTriggerListenersComplete(jec, instCode)) break; + + // update job/trigger or re-execute job + if (instCode == Trigger.INSTRUCTION_RE_EXECUTE_JOB) { + jec.incrementRefireCount(); + try { + complete(false); + } catch (SchedulerException se) { + qs.notifySchedulerListenersError("Error executing Job (" + + jec.getJobDetail().getFullName() + + ": couldn't finalize execution.", se); + } + continue; + } + + try { + complete(true); + } catch (SchedulerException se) { + qs.notifySchedulerListenersError("Error executing Job (" + + jec.getJobDetail().getFullName() + + ": couldn't finalize execution.", se); + continue; + } + + try { + qs.notifyJobStoreJobComplete(schdCtxt, trigger, jobDetail, + instCode); + } catch (JobPersistenceException jpe) { + qs.notifySchedulerListenersError( + "An error occured while marking executed job complete. job= '" + + jobDetail.getFullName() + "'", jpe); + if (!completeTriggerRetryLoop(trigger, jobDetail, instCode)) + ; + return; + } + + break; + } while (true); + + qs.notifySchedulerThread(); + + jobRunShellFactory.returnJobRunShell(this); + } + + protected void begin() throws SchedulerException { + } + + protected void complete(boolean successfulExecution) + throws SchedulerException { + } + + public void passivate() { + jec = null; + qs = null; + } + + private boolean notifyListenersBeginning(JobExecutionContext jec) throws VetoedException { + + boolean vetoed = false; + + // notify all trigger listeners + try { + vetoed = qs.notifyTriggerListenersFired(jec); + } catch (SchedulerException se) { + qs.notifySchedulerListenersError( + "Unable to notify TriggerListener(s) while firing trigger " + + "(Trigger and Job will NOT be fired!). trigger= " + + jec.getTrigger().getFullName() + " job= " + + jec.getJobDetail().getFullName(), se); + + return false; + } + + if(vetoed) { + try { + qs.notifyJobListenersWasVetoed(jec); + } catch (SchedulerException se) { + qs.notifySchedulerListenersError( + "Unable to notify JobListener(s) of vetoed execution " + + "while firing trigger (Trigger and Job will NOT be " + + "fired!). trigger= " + + jec.getTrigger().getFullName() + " job= " + + jec.getJobDetail().getFullName(), se); + + } + throw new VetoedException(); + } + + // notify all job listeners + try { + qs.notifyJobListenersToBeExecuted(jec); + } catch (SchedulerException se) { + qs.notifySchedulerListenersError( + "Unable to notify JobListener(s) of Job to be executed: " + + "(Job will NOT be executed!). trigger= " + + jec.getTrigger().getFullName() + " job= " + + jec.getJobDetail().getFullName(), se); + + return false; + } + + return true; + } + + private boolean notifyJobListenersComplete(JobExecutionContext jec, + JobExecutionException jobExEx) { + try { + qs.notifyJobListenersWasExecuted(jec, jobExEx); + } catch (SchedulerException se) { + qs.notifySchedulerListenersError( + "Unable to notify JobListener(s) of Job that was executed: " + + "(error will be ignored). trigger= " + + jec.getTrigger().getFullName() + " job= " + + jec.getJobDetail().getFullName(), se); + + return false; + } + + return true; + } + + private boolean notifyTriggerListenersComplete(JobExecutionContext jec, + int instCode) { + try { + qs.notifyTriggerListenersComplete(jec, instCode); + + } catch (SchedulerException se) { + qs.notifySchedulerListenersError( + "Unable to notify TriggerListener(s) of Job that was executed: " + + "(error will be ignored). trigger= " + + jec.getTrigger().getFullName() + " job= " + + jec.getJobDetail().getFullName(), se); + + return false; + } + if (jec.getTrigger().getNextFireTime() == null) + qs.notifySchedulerListenersFinalized(jec.getTrigger()); + + return true; + } + + public boolean completeTriggerRetryLoop(Trigger trigger, + JobDetail jobDetail, int instCode) { + while (!shutdownRequested) { + try { + Thread.sleep(5 * 1000l); // retry every 5 seconds (the db + // connection must be failed) + qs.notifyJobStoreJobComplete(schdCtxt, trigger, jobDetail, + instCode); + return true; + } catch (JobPersistenceException jpe) { + qs.notifySchedulerListenersError( + "An error occured while marking executed job complete. job= '" + + jobDetail.getFullName() + "'", jpe); + } catch (InterruptedException ignore) { + } + } + return false; + } + + + class VetoedException extends Exception + { + public VetoedException() + { + } + } +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/core/JobRunShellFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/core/JobRunShellFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/core/JobRunShellFactory.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,82 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.core; + +import org.quartz.Scheduler; +import org.quartz.SchedulerConfigException; +import org.quartz.SchedulerException; + +/** + *

+ * Responsible for creating the instances of {@link JobRunShell} + * to be used within the {@link QuartzScheduler} instance. + *

+ * + *

+ * Although this interface looks a lot like an 'object pool', implementations + * do not have to support the re-use of instances. If an implementation does + * not wish to pool instances, then the borrowJobRunShell() + * method would simply create a new instance, and the returnJobRunShell + * method would do nothing. + *

+ * + * @author James House + */ +public interface JobRunShellFactory { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Initialize the factory, providing a handle to the Scheduler + * that should be made available within the JobRunShell and + * the JobExecutionCOntext s within it, and a handle to the + * SchedulingContext that the shell will use in its own + * operations with the JobStore. + *

+ */ + public void initialize(Scheduler scheduler, SchedulingContext schedCtxt) + throws SchedulerConfigException; + + /** + *

+ * Called by the {@link org.quartz.core.QuartzSchedulerThread} + * to obtain instances of {@link JobRunShell}. + *

+ */ + public JobRunShell borrowJobRunShell() throws SchedulerException; + + /** + *

+ * Called by the {@link org.quartz.core.QuartzSchedulerThread} + * to return instances of {@link JobRunShell}. + *

+ */ + public void returnJobRunShell(JobRunShell jobRunShell); + +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/core/QuartzScheduler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/core/QuartzScheduler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/core/QuartzScheduler.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,2077 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.core; + +import java.io.IOException; +import java.io.InputStream; +import java.rmi.RemoteException; +import java.rmi.registry.LocateRegistry; +import java.rmi.registry.Registry; +import java.rmi.server.UnicastRemoteObject; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; +import java.util.Random; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.Calendar; +import org.quartz.InterruptableJob; +import org.quartz.Job; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.quartz.JobListener; +import org.quartz.JobPersistenceException; +import org.quartz.ObjectAlreadyExistsException; +import org.quartz.Scheduler; +import org.quartz.SchedulerContext; +import org.quartz.SchedulerException; +import org.quartz.SchedulerListener; +import org.quartz.Trigger; +import org.quartz.TriggerListener; +import org.quartz.UnableToInterruptJobException; +import org.quartz.impl.SchedulerRepository; +import org.quartz.simpl.SimpleJobFactory; +import org.quartz.spi.JobFactory; +import org.quartz.spi.SchedulerPlugin; +import org.quartz.spi.SchedulerSignaler; + +/** + *

+ * This is the heart of Quartz, an indirect implementation of the {@link org.quartz.Scheduler} + * interface, containing methods to schedule {@link org.quartz.Job}s, + * register {@link org.quartz.JobListener} instances, etc. + *

// TODO: more docs... + * + * @see org.quartz.Scheduler + * @see org.quartz.core.QuartzSchedulerThread + * @see org.quartz.spi.JobStore + * @see org.quartz.spi.ThreadPool + * + * @author James House + */ +public class QuartzScheduler implements RemotableQuartzScheduler { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private static String VERSION_MAJOR = "UNKNOWN"; + private static String VERSION_MINOR = "UNKNOWN"; + private static String VERSION_ITERATION = "UNKNOWN"; + + static { + Properties props = new Properties(); + try { + InputStream is = + QuartzScheduler.class.getResourceAsStream("/build.properties"); + if(is != null) { + props.load(is); + VERSION_MAJOR = props.getProperty("version.major"); + VERSION_MINOR = props.getProperty("version.minor"); + VERSION_ITERATION = props.getProperty("version.iter"); + } + } catch (IOException e) { + getLog().error("Error loading version info from build.properties.", e); + } + } + + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private QuartzSchedulerResources resources; + + private QuartzSchedulerThread schedThread; + + private ThreadGroup threadGroup; + + private SchedulerContext context = new SchedulerContext(); + + private HashMap jobListeners = new HashMap(10); + + private ArrayList globalJobListeners = new ArrayList(10); + + private HashMap triggerListeners = new HashMap(10); + + private ArrayList globalTriggerListeners = new ArrayList(10); + + private ArrayList schedulerListeners = new ArrayList(10); + + private ArrayList schedulerPlugins = new ArrayList(10); + + private JobFactory jobFactory = new SimpleJobFactory(); + + ExecutingJobsManager jobMgr = null; + + ErrorLogger errLogger = null; + + private SchedulerSignaler signaler; + + private Random random = new Random(); + + private ArrayList holdToPreventGC = new ArrayList(5); + + private boolean signalOnSchedulingChange = true; + + private boolean closed = false; + + private Date initialStart = null; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a QuartzScheduler with the given configuration + * properties. + *

+ * + * @see QuartzSchedulerResources + */ + public QuartzScheduler(QuartzSchedulerResources resources, + SchedulingContext ctxt, long idleWaitTime, long dbRetryInterval) + throws SchedulerException { + this.resources = resources; + try { + bind(); + } catch (Exception re) { + throw new SchedulerException( + "Unable to bind scheduler to RMI Registry.", re); + } + + this.schedThread = new QuartzSchedulerThread(this, resources, ctxt); + if (idleWaitTime > 0) this.schedThread.setIdleWaitTime(idleWaitTime); + if (dbRetryInterval > 0) + this.schedThread.setDbFailureRetryInterval(dbRetryInterval); + + jobMgr = new ExecutingJobsManager(); + addGlobalJobListener(jobMgr); + errLogger = new ErrorLogger(); + addSchedulerListener(errLogger); + + signaler = new SchedulerSignalerImpl(this); + + getLog().info("Quartz Scheduler v." + getVersion() + " created."); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public String getVersion() { + return getVersionMajor() + "." + getVersionMinor() + "." + + getVersionIteration(); + } + + public static String getVersionMajor() { + return VERSION_MAJOR; + } + + public static String getVersionMinor() { + return VERSION_MINOR; + } + + public static String getVersionIteration() { + return VERSION_ITERATION; + } + + public SchedulerSignaler getSchedulerSignaler() { + return signaler; + } + + public static Log getLog() { + return LogFactory.getLog(QuartzScheduler.class); + } + + /** + *

+ * Bind the scheduler to an RMI registry. + *

+ */ + private void bind() throws RemoteException { + String host = resources.getRMIRegistryHost(); + // don't export if we're not configured to do so... + if (host == null || host.length() == 0) return; + + RemotableQuartzScheduler exportable = null; + + if(resources.getRMIServerPort() > 0) + exportable = (RemotableQuartzScheduler) UnicastRemoteObject + .exportObject(this, resources.getRMIServerPort()); + else + exportable = (RemotableQuartzScheduler) UnicastRemoteObject + .exportObject(this); + + Registry registry = null; + + if (resources.getRMICreateRegistryStrategy().equals( + QuartzSchedulerResources.CREATE_REGISTRY_AS_NEEDED)) { + try { + // First try to get an existing one, instead of creating it, + // since if + // we're in a web-app being 'hot' re-depoloyed, then the JVM + // still + // has the registry that we created above the first time... + registry = LocateRegistry.getRegistry(resources + .getRMIRegistryPort()); + registry.list(); + } catch (Exception e) { + registry = LocateRegistry.createRegistry(resources + .getRMIRegistryPort()); + } + } else if (resources.getRMICreateRegistryStrategy().equals( + QuartzSchedulerResources.CREATE_REGISTRY_ALWAYS)) { + try { + registry = LocateRegistry.createRegistry(resources + .getRMIRegistryPort()); + } catch (Exception e) { + // Fall back to an existing one, instead of creating it, since + // if + // we're in a web-app being 'hot' re-depoloyed, then the JVM + // still + // has the registry that we created above the first time... + registry = LocateRegistry.getRegistry(resources + .getRMIRegistryPort()); + } + } else { + registry = LocateRegistry.getRegistry(resources + .getRMIRegistryHost(), resources.getRMIRegistryPort()); + } + + registry.rebind(resources.getUniqueIdentifier(), exportable); + + getLog().info("Scheduler bound to RMI registry."); + } + + /** + *

+ * Un-bind the scheduler from an RMI registry. + *

+ */ + private void unBind() throws RemoteException { + String host = resources.getRMIRegistryHost(); + // don't un-export if we're not configured to do so... + if (host == null || host.length() == 0) return; + + Registry registry = LocateRegistry.getRegistry(resources + .getRMIRegistryHost(), resources.getRMIRegistryPort()); + + try { + registry.unbind(resources.getUniqueIdentifier()); + UnicastRemoteObject.unexportObject(this, true); + } catch (java.rmi.NotBoundException nbe) { + } + + getLog().info("Scheduler un-bound from RMI registry."); + } + + /** + *

+ * Returns the name of the QuartzScheduler. + *

+ */ + public String getSchedulerName() { + return resources.getName(); + } + + /** + *

+ * Returns the instance Id of the QuartzScheduler. + *

+ */ + public String getSchedulerInstanceId() { + return resources.getInstanceId(); + } + + /** + *

+ * Returns the name of the QuartzScheduler. + *

+ */ + public ThreadGroup getSchedulerThreadGroup() { + if (threadGroup == null) { + threadGroup = new ThreadGroup("QuartzScheduler:" + + getSchedulerName()); + } + + return threadGroup; + } + + public void addNoGCObject(Object obj) { + holdToPreventGC.add(obj); + } + + public boolean removeNoGCObject(Object obj) { + return holdToPreventGC.remove(obj); + } + + /** + *

+ * Returns the SchedulerContext of the Scheduler. + *

+ */ + public SchedulerContext getSchedulerContext() throws SchedulerException { + return context; + } + + public boolean isSignalOnSchedulingChange() { + return signalOnSchedulingChange; + } + + public void setSignalOnSchedulingChange(boolean signalOnSchedulingChange) { + this.signalOnSchedulingChange = signalOnSchedulingChange; + } + + /////////////////////////////////////////////////////////////////////////// + /// + /// Schedululer State Management Methods + /// + /////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Starts the QuartzScheduler's threads that fire {@link org.quartz.Trigger}s. + *

+ * + *

+ * All {@link org.quartz.Trigger}s that have misfired will + * be passed to the appropriate TriggerListener(s). + *

+ */ + public void start() throws SchedulerException { + + if (closed) + throw new SchedulerException( + "The Scheduler cannot be restarted after shutdown() has been called."); + + schedThread.togglePause(false); + + if (initialStart == null) { + initialStart = new Date(); + this.resources.getJobStore().schedulerStarted(); + startPlugins(); + } + + getLog().info( + "Scheduler " + resources.getUniqueIdentifier() + " started."); + } + + /** + *

+ * Temporarily halts the QuartzScheduler's firing of {@link org.quartz.Trigger}s. + *

+ * + *

+ * The scheduler is not destroyed, and can be re-started at any time. + *

+ */ + public void standby() { + schedThread.togglePause(true); + getLog().info( + "Scheduler " + resources.getUniqueIdentifier() + " paused."); + } + + /** + *

+ * Reports whether the Scheduler is paused. + *

+ */ + public boolean isInStandbyMode() { + return schedThread.isPaused(); + } + + public Date runningSince() { + return initialStart; + } + + public int numJobsExecuted() { + return jobMgr.getNumJobsFired(); + } + + public Class getJobStoreClass() { + return resources.getJobStore().getClass(); + } + + public boolean supportsPersistence() { + return resources.getJobStore().supportsPersistence(); + } + + public Class getThreadPoolClass() { + return resources.getThreadPool().getClass(); + } + + public int getThreadPoolSize() { + return resources.getThreadPool().getPoolSize(); + } + + /** + *

+ * Halts the QuartzScheduler's firing of {@link org.quartz.Trigger}s, + * and cleans up all resources associated with the QuartzScheduler. + * Equivalent to shutdown(false). + *

+ * + *

+ * The scheduler cannot be re-started. + *

+ */ + public void shutdown() { + shutdown(false); + } + + /** + *

+ * Halts the QuartzScheduler's firing of {@link org.quartz.Trigger}s, + * and cleans up all resources associated with the QuartzScheduler. + *

+ * + *

+ * The scheduler cannot be re-started. + *

+ * + * @param waitForJobsToComplete + * if true the scheduler will not allow this method + * to return until all currently executing jobs have completed. + */ + public void shutdown(boolean waitForJobsToComplete) { + + if(closed == true) + return; + + getLog().info( + "Scheduler " + resources.getUniqueIdentifier() + + " shutting down."); + standby(); + + closed = true; + + schedThread.halt(); + + resources.getThreadPool().shutdown(waitForJobsToComplete); + + if (waitForJobsToComplete) { + while (jobMgr.getNumJobsCurrentlyExecuting() > 0) + try { + Thread.sleep(100); + } catch (Exception ignore) { + } + } + + resources.getJobStore().shutdown(); + + notifySchedulerListenersShutdown(); + + shutdownPlugins(); + + SchedulerRepository.getInstance().remove(resources.getName()); + + holdToPreventGC.clear(); + + try { + unBind(); + } catch (RemoteException re) { + } + + getLog().info( + "Scheduler " + resources.getUniqueIdentifier() + + " shutdown complete."); + } + + /** + *

+ * Reports whether the Scheduler has been shutdown. + *

+ */ + public boolean isShutdown() { + return closed; + } + + public void validateState() throws SchedulerException { + if (isShutdown()) + throw new SchedulerException("The Scheduler has been shutdown."); + + // other conditions to check (?) + } + + /** + *

+ * Return a list of JobExecutionContext objects that + * represent all currently executing Jobs. + *

+ * + *

+ * Note that the list returned is an 'instantaneous' snap-shot, and that as + * soon as it's returned, the true list of executing jobs may be different. + *

+ */ + public List getCurrentlyExecutingJobs() { + return jobMgr.getExecutingJobs(); + } + + /////////////////////////////////////////////////////////////////////////// + /// + /// Scheduling-related Methods + /// + /////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Add the {@link org.quartz.Job} identified by the given + * {@link org.quartz.JobDetail} to the Scheduler, and + * associate the given {@link org.quartz.Trigger} with it. + *

+ * + *

+ * If the given Trigger does not reference any Job, then it + * will be set to reference the Job passed with it into this method. + *

+ * + * @throws SchedulerException + * if the Job or Trigger cannot be added to the Scheduler, or + * there is an internal Scheduler error. + */ + public Date scheduleJob(SchedulingContext ctxt, JobDetail jobDetail, + Trigger trigger) throws SchedulerException { + validateState(); + + jobDetail.validate(); + + if (trigger.getJobName() == null) { + trigger.setJobName(jobDetail.getName()); + trigger.setJobGroup(jobDetail.getGroup()); + } else if (trigger.getJobName() != null + && !trigger.getJobName().equals(jobDetail.getName())) { + throw new SchedulerException( + "Trigger does not reference given job!", + SchedulerException.ERR_CLIENT_ERROR); + } else if (trigger.getJobGroup() != null + && !trigger.getJobGroup().equals(jobDetail.getGroup())) { + throw new SchedulerException( + "Trigger does not reference given job!", + SchedulerException.ERR_CLIENT_ERROR); + } + + trigger.validate(); + + Calendar cal = null; + if (trigger.getCalendarName() != null) { + cal = resources.getJobStore().retrieveCalendar(ctxt, + trigger.getCalendarName()); + } + Date ft = trigger.computeFirstFireTime(cal); + + if (ft == null) + throw new SchedulerException( + "Based on configured schedule, the given trigger will never fire.", + SchedulerException.ERR_CLIENT_ERROR); + + resources.getJobStore().storeJobAndTrigger(ctxt, jobDetail, trigger); + notifySchedulerThread(); + notifySchedulerListenersSchduled(trigger); + + return ft; + } + + /** + *

+ * Schedule the given {@link org.quartz.Trigger} with the + * Job identified by the Trigger's settings. + *

+ * + * @throws SchedulerException + * if the indicated Job does not exist, or the Trigger cannot be + * added to the Scheduler, or there is an internal Scheduler + * error. + */ + public Date scheduleJob(SchedulingContext ctxt, Trigger trigger) + throws SchedulerException { + validateState(); + + trigger.validate(); + + Calendar cal = null; + if (trigger.getCalendarName() != null) { + cal = resources.getJobStore().retrieveCalendar(ctxt, + trigger.getCalendarName()); + if(cal == null) + throw new SchedulerException( + "Calendar not found: " + trigger.getCalendarName(), + SchedulerException.ERR_PERSISTENCE_CALENDAR_DOES_NOT_EXIST); + } + Date ft = trigger.computeFirstFireTime(cal); + + if (ft == null) + throw new SchedulerException( + "Based on configured schedule, the given trigger will never fire.", + SchedulerException.ERR_CLIENT_ERROR); + + resources.getJobStore().storeTrigger(ctxt, trigger, false); + notifySchedulerThread(); + notifySchedulerListenersSchduled(trigger); + + return ft; + } + + /** + *

+ * Add the given Job to the Scheduler - with no associated + * Trigger. The Job will be 'dormant' until + * it is scheduled with a Trigger, or Scheduler.triggerJob() + * is called for it. + *

+ * + *

+ * The Job must by definition be 'durable', if it is not, + * SchedulerException will be thrown. + *

+ * + * @throws SchedulerException + * if there is an internal Scheduler error, or if the Job is not + * durable, or a Job with the same name already exists, and + * replace is false. + */ + public void addJob(SchedulingContext ctxt, JobDetail jobDetail, + boolean replace) throws SchedulerException { + validateState(); + + if (!jobDetail.isDurable() && !replace) + throw new SchedulerException( + "Jobs added with no trigger must be durable.", + SchedulerException.ERR_CLIENT_ERROR); + + resources.getJobStore().storeJob(ctxt, jobDetail, replace); + } + + /** + *

+ * Delete the identified Job from the Scheduler - and any + * associated Triggers. + *

+ * + * @return true if the Job was found and deleted. + * @throws SchedulerException + * if there is an internal Scheduler error. + */ + public boolean deleteJob(SchedulingContext ctxt, String jobName, + String groupName) throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + return resources.getJobStore().removeJob(ctxt, jobName, groupName); + } + + /** + *

+ * Remove the indicated {@link org.quartz.Trigger} from the + * scheduler. + *

+ */ + public boolean unscheduleJob(SchedulingContext ctxt, String triggerName, + String groupName) throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + if (resources.getJobStore().removeTrigger(ctxt, triggerName, groupName)) { + notifySchedulerThread(); + notifySchedulerListenersUnschduled(triggerName, groupName); + } else + return false; + + return true; + } + + + /** + *

+ * Remove (delete) the {@link org.quartz.Trigger} with the + * given name, and store the new given one - which must be associated + * with the same job. + *

+ * + * @param triggerName + * The name of the Trigger to be removed. + * @param groupName + * The group name of the Trigger to be removed. + * @param newTrigger + * The new Trigger to be stored. + * @return null if a Trigger with the given + * name & group was not found and removed from the store, otherwise + * the first fire time of the newly scheduled trigger. + */ + public Date rescheduleJob(SchedulingContext ctxt, String triggerName, + String groupName, Trigger newTrigger) throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + newTrigger.validate(); + + Calendar cal = null; + if (newTrigger.getCalendarName() != null) { + cal = resources.getJobStore().retrieveCalendar(ctxt, + newTrigger.getCalendarName()); + } + Date ft = newTrigger.computeFirstFireTime(cal); + + if (ft == null) + throw new SchedulerException( + "Based on configured schedule, the given trigger will never fire.", + SchedulerException.ERR_CLIENT_ERROR); + + if (resources.getJobStore().replaceTrigger(ctxt, triggerName, groupName, newTrigger)) { + notifySchedulerThread(); + notifySchedulerListenersUnschduled(triggerName, groupName); + notifySchedulerListenersSchduled(newTrigger); + } else + return null; + + return ft; + + } + + + private String newTriggerId() { + long r = random.nextLong(); + if (r < 0) r = -r; + return "MT_" + + Long.toString(r, 30 + (int) (System.currentTimeMillis() % 7)); + } + + /** + *

+ * Trigger the identified {@link org.quartz.Job} (execute it + * now) - with a non-volatile trigger. + *

+ */ + public void triggerJob(SchedulingContext ctxt, String jobName, + String groupName, JobDataMap data) throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + Trigger trig = new org.quartz.SimpleTrigger(newTriggerId(), + Scheduler.DEFAULT_MANUAL_TRIGGERS, jobName, groupName, + new Date(), null, 0, 0); + trig.setVolatility(false); + trig.computeFirstFireTime(null); + if(data != null) + trig.setJobDataMap(data); + + boolean collision = true; + while (collision) { + try { + resources.getJobStore().storeTrigger(ctxt, trig, false); + collision = false; + } catch (ObjectAlreadyExistsException oaee) { + trig.setName(newTriggerId()); + } + } + + notifySchedulerThread(); + notifySchedulerListenersSchduled(trig); + } + + /** + *

+ * Trigger the identified {@link org.quartz.Job} (execute it + * now) - with a volatile trigger. + *

+ */ + public void triggerJobWithVolatileTrigger(SchedulingContext ctxt, + String jobName, String groupName, JobDataMap data) throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + Trigger trig = new org.quartz.SimpleTrigger(newTriggerId(), + Scheduler.DEFAULT_MANUAL_TRIGGERS, jobName, groupName, + new Date(), null, 0, 0); + trig.setVolatility(true); + trig.computeFirstFireTime(null); + if(data != null) + trig.setJobDataMap(data); + + boolean collision = true; + while (collision) { + try { + resources.getJobStore().storeTrigger(ctxt, trig, false); + collision = false; + } catch (ObjectAlreadyExistsException oaee) { + trig.setName(newTriggerId()); + } + } + + notifySchedulerThread(); + notifySchedulerListenersSchduled(trig); + } + + /** + *

+ * Pause the {@link Trigger} with the given name. + *

+ * + */ + public void pauseTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + resources.getJobStore().pauseTrigger(ctxt, triggerName, groupName); + notifySchedulerThread(); + notifySchedulerListenersPausedTrigger(triggerName, groupName); + } + + /** + *

+ * Pause all of the {@link Trigger}s in the given group. + *

+ * + */ + public void pauseTriggerGroup(SchedulingContext ctxt, String groupName) + throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + resources.getJobStore().pauseTriggerGroup(ctxt, groupName); + notifySchedulerThread(); + notifySchedulerListenersPausedTrigger(null, groupName); + } + + /** + *

+ * Pause the {@link org.quartz.JobDetail} with the given + * name - by pausing all of its current Triggers. + *

+ * + */ + public void pauseJob(SchedulingContext ctxt, String jobName, + String groupName) throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + resources.getJobStore().pauseJob(ctxt, jobName, groupName); + notifySchedulerThread(); + notifySchedulerListenersPausedJob(jobName, groupName); + } + + /** + *

+ * Pause all of the {@link org.quartz.JobDetail}s in the + * given group - by pausing all of their Triggers. + *

+ * + */ + public void pauseJobGroup(SchedulingContext ctxt, String groupName) + throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + resources.getJobStore().pauseJobGroup(ctxt, groupName); + notifySchedulerThread(); + notifySchedulerListenersPausedJob(null, groupName); + } + + /** + *

+ * Resume (un-pause) the {@link Trigger} with the given + * name. + *

+ * + *

+ * If the Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + */ + public void resumeTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + resources.getJobStore().resumeTrigger(ctxt, triggerName, groupName); + notifySchedulerThread(); + notifySchedulerListenersResumedTrigger(triggerName, groupName); + } + + /** + *

+ * Resume (un-pause) all of the {@link Trigger}s in the + * given group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + */ + public void resumeTriggerGroup(SchedulingContext ctxt, String groupName) + throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + resources.getJobStore().resumeTriggerGroup(ctxt, groupName); + notifySchedulerThread(); + notifySchedulerListenersResumedTrigger(null, groupName); + } + + public Set getPausedTriggerGroups(SchedulingContext ctxt) throws SchedulerException { + return resources.getJobStore().getPausedTriggerGroups(ctxt); + } + + /** + *

+ * Resume (un-pause) the {@link org.quartz.JobDetail} with + * the given name. + *

+ * + *

+ * If any of the Job'sTrigger s missed one + * or more fire-times, then the Trigger's misfire + * instruction will be applied. + *

+ * + */ + public void resumeJob(SchedulingContext ctxt, String jobName, + String groupName) throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + resources.getJobStore().resumeJob(ctxt, jobName, groupName); + notifySchedulerThread(); + notifySchedulerListenersResumedJob(jobName, groupName); + } + + /** + *

+ * Resume (un-pause) all of the {@link org.quartz.JobDetail}s + * in the given group. + *

+ * + *

+ * If any of the Job s had Trigger s that + * missed one or more fire-times, then the Trigger's + * misfire instruction will be applied. + *

+ * + */ + public void resumeJobGroup(SchedulingContext ctxt, String groupName) + throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + resources.getJobStore().resumeJobGroup(ctxt, groupName); + notifySchedulerThread(); + notifySchedulerListenersResumedJob(null, groupName); + } + + /** + *

+ * Pause all triggers - equivalent of calling pauseTriggerGroup(group) + * on every group. + *

+ * + *

+ * When resumeAll() is called (to un-pause), trigger misfire + * instructions WILL be applied. + *

+ * + * @see #resumeAll(SchedulingContext) + * @see #pauseTriggerGroup(SchedulingContext, String) + * @see #pause() + */ + public void pauseAll(SchedulingContext ctxt) throws SchedulerException { + validateState(); + + resources.getJobStore().pauseAll(ctxt); + notifySchedulerThread(); + notifySchedulerListenersPausedTrigger(null, null); + } + + /** + *

+ * Resume (un-pause) all triggers - equivalent of calling resumeTriggerGroup(group) + * on every group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseAll(SchedulingContext) + */ + public void resumeAll(SchedulingContext ctxt) throws SchedulerException { + validateState(); + + resources.getJobStore().resumeAll(ctxt); + notifySchedulerThread(); + notifySchedulerListenersResumedTrigger(null, null); + } + + /** + *

+ * Get the names of all known {@link org.quartz.Job} groups. + *

+ */ + public String[] getJobGroupNames(SchedulingContext ctxt) + throws SchedulerException { + validateState(); + + return resources.getJobStore().getJobGroupNames(ctxt); + } + + /** + *

+ * Get the names of all the {@link org.quartz.Job}s in the + * given group. + *

+ */ + public String[] getJobNames(SchedulingContext ctxt, String groupName) + throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + return resources.getJobStore().getJobNames(ctxt, groupName); + } + + /** + *

+ * Get all {@link Trigger} s that are associated with the + * identified {@link org.quartz.JobDetail}. + *

+ */ + public Trigger[] getTriggersOfJob(SchedulingContext ctxt, String jobName, + String groupName) throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + return resources.getJobStore().getTriggersForJob(ctxt, jobName, + groupName); + } + + /** + *

+ * Get the names of all known {@link org.quartz.Trigger} + * groups. + *

+ */ + public String[] getTriggerGroupNames(SchedulingContext ctxt) + throws SchedulerException { + validateState(); + + return resources.getJobStore().getTriggerGroupNames(ctxt); + } + + /** + *

+ * Get the names of all the {@link org.quartz.Trigger}s in + * the given group. + *

+ */ + public String[] getTriggerNames(SchedulingContext ctxt, String groupName) + throws SchedulerException { + validateState(); + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + return resources.getJobStore().getTriggerNames(ctxt, groupName); + } + + /** + *

+ * Get the {@link JobDetail} for the Job + * instance with the given name and group. + *

+ */ + public JobDetail getJobDetail(SchedulingContext ctxt, String jobName, + String jobGroup) throws SchedulerException { + validateState(); + + if(jobGroup == null) + jobGroup = Scheduler.DEFAULT_GROUP; + + return resources.getJobStore().retrieveJob(ctxt, jobName, jobGroup); + } + + /** + *

+ * Get the {@link Trigger} instance with the given name and + * group. + *

+ */ + public Trigger getTrigger(SchedulingContext ctxt, String triggerName, + String triggerGroup) throws SchedulerException { + validateState(); + + if(triggerGroup == null) + triggerGroup = Scheduler.DEFAULT_GROUP; + + return resources.getJobStore().retrieveTrigger(ctxt, triggerName, + triggerGroup); + } + + /** + *

+ * Get the current state of the identified {@link Trigger}. + *

+ * + * @see Trigger#STATE_NORMAL + * @see Trigger#STATE_PAUSED + * @see Trigger#STATE_COMPLETE + * @see Trigger#STATE_ERROR + */ + public int getTriggerState(SchedulingContext ctxt, String triggerName, + String triggerGroup) throws SchedulerException { + validateState(); + + if(triggerGroup == null) + triggerGroup = Scheduler.DEFAULT_GROUP; + + return resources.getJobStore().getTriggerState(ctxt, triggerName, + triggerGroup); + } + + /** + *

+ * Add (register) the given Calendar to the Scheduler. + *

+ * + * @throws SchedulerException + * if there is an internal Scheduler error, or a Calendar with + * the same name already exists, and replace is + * false. + */ + public void addCalendar(SchedulingContext ctxt, String calName, + Calendar calendar, boolean replace, boolean updateTriggers) throws SchedulerException { + validateState(); + + resources.getJobStore().storeCalendar(ctxt, calName, calendar, replace, updateTriggers); + } + + /** + *

+ * Delete the identified Calendar from the Scheduler. + *

+ * + * @return true if the Calendar was found and deleted. + * @throws SchedulerException + * if there is an internal Scheduler error. + */ + public boolean deleteCalendar(SchedulingContext ctxt, String calName) + throws SchedulerException { + validateState(); + + return resources.getJobStore().removeCalendar(ctxt, calName); + } + + /** + *

+ * Get the {@link Calendar} instance with the given name. + *

+ */ + public Calendar getCalendar(SchedulingContext ctxt, String calName) + throws SchedulerException { + validateState(); + + return resources.getJobStore().retrieveCalendar(ctxt, calName); + } + + /** + *

+ * Get the names of all registered {@link Calendar}s. + *

+ */ + public String[] getCalendarNames(SchedulingContext ctxt) + throws SchedulerException { + validateState(); + + return resources.getJobStore().getCalendarNames(ctxt); + } + + /** + *

+ * Add the given {@link org.quartz.JobListener} to the + * Scheduler'sglobal list. + *

+ * + *

+ * Listeners in the 'global' list receive notification of execution events + * for ALL {@link org.quartz.Job}s. + *

+ */ + public void addGlobalJobListener(JobListener jobListener) { + if (jobListener.getName() == null + || jobListener.getName().length() == 0) + throw new IllegalArgumentException( + "JobListener name cannot be empty."); + + globalJobListeners.add(jobListener); + } + + /** + *

+ * Add the given {@link org.quartz.JobListener} to the + * Scheduler's list, of registered JobListeners. + */ + public void addJobListener(JobListener jobListener) { + if (jobListener.getName() == null + || jobListener.getName().length() == 0) + throw new IllegalArgumentException( + "JobListener name cannot be empty."); + + jobListeners.put(jobListener.getName(), jobListener); + } + + /** + *

+ * Remove the given {@link org.quartz.JobListener} from the + * Scheduler's list of global listeners. + *

+ * + * @return true if the identifed listener was found in the list, and + * removed. + */ + public boolean removeGlobalJobListener(JobListener jobListener) { + return globalJobListeners.remove(jobListener); + } + + /** + *

+ * Remove the identifed {@link org.quartz.JobListener} from + * the Scheduler's list of registered listeners. + *

+ * + * @return true if the identifed listener was found in the list, and + * removed. + */ + public boolean removeJobListener(String name) { + Object o = jobListeners.remove(name); + + if (o != null) return true; + + return false; + } + + /** + *

+ * Get a List containing all of the {@link org.quartz.JobListener} + * s in the Scheduler'sglobal list. + *

+ */ + public List getGlobalJobListeners() { + return new LinkedList(globalJobListeners); + } + + /** + *

+ * Get a Set containing the names of all the non-global{@link org.quartz.JobListener} + * s registered with the Scheduler. + *

+ */ + public Set getJobListenerNames() { + return Collections.unmodifiableSet(jobListeners.keySet()); + } + + /** + *

+ * Get the non-global{@link org.quartz.JobListener} + * that has the given name. + *

+ */ + public JobListener getJobListener(String name) { + return (JobListener) jobListeners.get(name); + } + + /** + *

+ * Add the given {@link org.quartz.TriggerListener} to the + * Scheduler'sglobal list. + *

+ * + *

+ * Listeners in the 'global' list receive notification of execution events + * for ALL {@link org.quartz.Trigger}s. + *

+ */ + public void addGlobalTriggerListener(TriggerListener triggerListener) { + if (triggerListener.getName() == null + || triggerListener.getName().length() == 0) + throw new IllegalArgumentException( + "TriggerListener name cannot be empty."); + + globalTriggerListeners.add(triggerListener); + } + + /** + *

+ * Add the given {@link org.quartz.TriggerListener} to the + * Scheduler's list, of registered TriggerListeners. + */ + public void addTriggerListener(TriggerListener triggerListener) { + if (triggerListener.getName() == null + || triggerListener.getName().length() == 0) + throw new IllegalArgumentException( + "TriggerListener name cannot be empty."); + + triggerListeners.put(triggerListener.getName(), triggerListener); + } + + /** + *

+ * Remove the given {@link org.quartz.TriggerListener} from + * the Scheduler's list of global listeners. + *

+ * + * @return true if the identifed listener was found in the list, and + * removed. + */ + public boolean removeGlobalTriggerListener(TriggerListener triggerListener) { + return globalTriggerListeners.remove(triggerListener); + } + + /** + *

+ * Remove the identifed {@link org.quartz.TriggerListener} + * from the Scheduler's list of registered listeners. + *

+ * + * @return true if the identifed listener was found in the list, and + * removed. + */ + public boolean removeTriggerListener(String name) { + Object o = triggerListeners.remove(name); + + if (o != null) return true; + + return false; + } + + /** + *

+ * Get a list containing all of the {@link org.quartz.TriggerListener} + * s in the Scheduler'sglobal list. + *

+ */ + public List getGlobalTriggerListeners() { + return new LinkedList(globalTriggerListeners); + } + + /** + *

+ * Get a Set containing the names of all the non-global{@link org.quartz.TriggerListener} + * s registered with the Scheduler. + *

+ */ + public Set getTriggerListenerNames() { + return Collections.unmodifiableSet(triggerListeners.keySet()); + } + + /** + *

+ * Get the non-global{@link org.quartz.TriggerListener} + * that has the given name. + *

+ */ + public TriggerListener getTriggerListener(String name) { + return (TriggerListener) triggerListeners.get(name); + } + + /** + *

+ * Register the given {@link SchedulerListener} with the + * Scheduler. + *

+ */ + public void addSchedulerListener(SchedulerListener schedulerListener) { + schedulerListeners.add(schedulerListener); + } + + /** + *

+ * Remove the given {@link SchedulerListener} from the + * Scheduler. + *

+ * + * @return true if the identifed listener was found in the list, and + * removed. + */ + public boolean removeSchedulerListener(SchedulerListener schedulerListener) { + return schedulerListeners.remove(schedulerListener); + } + + /** + *

+ * Get a List containing all of the {@link SchedulerListener} + * s registered with the Scheduler. + *

+ */ + public List getSchedulerListeners() { + return (List) schedulerListeners.clone(); + } + + protected void notifyJobStoreJobComplete(SchedulingContext ctxt, + Trigger trigger, JobDetail detail, int instCode) + throws JobPersistenceException { + + resources.getJobStore().triggeredJobComplete(ctxt, trigger, detail, + instCode); + } + + protected void notifySchedulerThread() { + if (isSignalOnSchedulingChange()) schedThread.signalSchedulingChange(); + } + + private List buildTriggerListenerList(String[] additionalLstnrs) + throws SchedulerException { + List triggerListeners = getGlobalTriggerListeners(); + for (int i = 0; i < additionalLstnrs.length; i++) { + TriggerListener tl = getTriggerListener(additionalLstnrs[i]); + + if (tl != null) triggerListeners.add(tl); + else + throw new SchedulerException("TriggerListener '" + + additionalLstnrs[i] + "' not found.", + SchedulerException.ERR_TRIGGER_LISTENER_NOT_FOUND); + } + + return triggerListeners; + } + + private List buildJobListenerList(String[] additionalLstnrs) + throws SchedulerException { + List jobListeners = getGlobalJobListeners(); + for (int i = 0; i < additionalLstnrs.length; i++) { + JobListener jl = getJobListener(additionalLstnrs[i]); + + if (jl != null) jobListeners.add(jl); + else + throw new SchedulerException("JobListener '" + + additionalLstnrs[i] + "' not found.", + SchedulerException.ERR_JOB_LISTENER_NOT_FOUND); + } + + return jobListeners; + } + + public boolean notifyTriggerListenersFired(JobExecutionContext jec) + throws SchedulerException { + // build a list of all trigger listeners that are to be notified... + List triggerListeners = buildTriggerListenerList(jec.getTrigger() + .getTriggerListenerNames()); + + boolean vetoedExecution = false; + + // notify all trigger listeners in the list + java.util.Iterator itr = triggerListeners.iterator(); + while (itr.hasNext()) { + TriggerListener tl = (TriggerListener) itr.next(); + try { + tl.triggerFired(jec.getTrigger(), jec); + + if(tl.vetoJobExecution(jec.getTrigger(), jec)) + vetoedExecution = true; + } catch (Exception e) { + SchedulerException se = new SchedulerException( + "TriggerListener '" + tl.getName() + + "' threw exception: " + e.getMessage(), e); + se.setErrorCode(SchedulerException.ERR_TRIGGER_LISTENER); + throw se; + } + } + + return vetoedExecution; + } + + + public void notifyTriggerListenersMisfired(Trigger trigger) + throws SchedulerException { + // build a list of all trigger listeners that are to be notified... + List triggerListeners = buildTriggerListenerList(trigger + .getTriggerListenerNames()); + + // notify all trigger listeners in the list + java.util.Iterator itr = triggerListeners.iterator(); + while (itr.hasNext()) { + TriggerListener tl = (TriggerListener) itr.next(); + try { + tl.triggerMisfired(trigger); + } catch (Exception e) { + SchedulerException se = new SchedulerException( + "TriggerListener '" + tl.getName() + + "' threw exception: " + e.getMessage(), e); + se.setErrorCode(SchedulerException.ERR_TRIGGER_LISTENER); + throw se; + } + } + } + + public void notifyTriggerListenersComplete(JobExecutionContext jec, + int instCode) throws SchedulerException { + // build a list of all trigger listeners that are to be notified... + List triggerListeners = buildTriggerListenerList(jec.getTrigger() + .getTriggerListenerNames()); + + // notify all trigger listeners in the list + java.util.Iterator itr = triggerListeners.iterator(); + while (itr.hasNext()) { + TriggerListener tl = (TriggerListener) itr.next(); + try { + tl.triggerComplete(jec.getTrigger(), jec, instCode); + } catch (Exception e) { + SchedulerException se = new SchedulerException( + "TriggerListener '" + tl.getName() + + "' threw exception: " + e.getMessage(), e); + se.setErrorCode(SchedulerException.ERR_TRIGGER_LISTENER); + throw se; + } + } + } + + public void notifyJobListenersToBeExecuted(JobExecutionContext jec) + throws SchedulerException { + // build a list of all job listeners that are to be notified... + List jobListeners = buildJobListenerList(jec.getJobDetail() + .getJobListenerNames()); + + // notify all job listeners + java.util.Iterator itr = jobListeners.iterator(); + while (itr.hasNext()) { + JobListener jl = (JobListener) itr.next(); + try { + jl.jobToBeExecuted(jec); + } catch (Exception e) { + SchedulerException se = new SchedulerException( + "JobListener '" + jl.getName() + "' threw exception: " + + e.getMessage(), e); + se.setErrorCode(SchedulerException.ERR_JOB_LISTENER); + throw se; + } + } + } + + public void notifyJobListenersWasVetoed(JobExecutionContext jec) + throws SchedulerException { + // build a list of all job listeners that are to be notified... + List jobListeners = buildJobListenerList(jec.getJobDetail() + .getJobListenerNames()); + + // notify all job listeners + java.util.Iterator itr = jobListeners.iterator(); + while (itr.hasNext()) { + JobListener jl = (JobListener) itr.next(); + try { + jl.jobExecutionVetoed(jec); + } catch (Exception e) { + SchedulerException se = new SchedulerException( + "JobListener '" + jl.getName() + "' threw exception: " + + e.getMessage(), e); + se.setErrorCode(SchedulerException.ERR_JOB_LISTENER); + throw se; + } + } + } + + public void notifyJobListenersWasExecuted(JobExecutionContext jec, + JobExecutionException je) throws SchedulerException { + // build a list of all job listeners that are to be notified... + List jobListeners = buildJobListenerList(jec.getJobDetail() + .getJobListenerNames()); + + // notify all job listeners + java.util.Iterator itr = jobListeners.iterator(); + while (itr.hasNext()) { + JobListener jl = (JobListener) itr.next(); + try { + jl.jobWasExecuted(jec, je); + } catch (Exception e) { + SchedulerException se = new SchedulerException( + "JobListener '" + jl.getName() + "' threw exception: " + + e.getMessage(), e); + se.setErrorCode(SchedulerException.ERR_JOB_LISTENER); + throw se; + } + } + } + + public void notifySchedulerListenersError(String msg, SchedulerException se) { + // build a list of all scheduler listeners that are to be notified... + List schedListeners = getSchedulerListeners(); + + // notify all scheduler listeners + java.util.Iterator itr = schedListeners.iterator(); + while (itr.hasNext()) { + SchedulerListener sl = (SchedulerListener) itr.next(); + try { + sl.schedulerError(msg, se); + } catch (Exception e) { + getLog() + .error( + "Error while notifying SchedulerListener of error: ", + e); + getLog().error( + " Original error (for notification) was: " + msg, se); + } + } + } + + public void notifySchedulerListenersSchduled(Trigger trigger) { + // build a list of all scheduler listeners that are to be notified... + List schedListeners = getSchedulerListeners(); + + // notify all scheduler listeners + java.util.Iterator itr = schedListeners.iterator(); + while (itr.hasNext()) { + SchedulerListener sl = (SchedulerListener) itr.next(); + try { + sl.jobScheduled(trigger); + } catch (Exception e) { + getLog().error( + "Error while notifying SchedulerListener of scheduled job." + + " Triger=" + trigger.getFullName(), e); + } + } + } + + public void notifySchedulerListenersUnschduled(String triggerName, + String triggerGroup) { + // build a list of all scheduler listeners that are to be notified... + List schedListeners = getSchedulerListeners(); + + // notify all scheduler listeners + java.util.Iterator itr = schedListeners.iterator(); + while (itr.hasNext()) { + SchedulerListener sl = (SchedulerListener) itr.next(); + try { + sl.jobUnscheduled(triggerName, triggerGroup); + } catch (Exception e) { + getLog().error( + "Error while notifying SchedulerListener of unscheduled job." + + " Triger=" + triggerGroup + "." + + triggerName, e); + } + } + } + + public void notifySchedulerListenersFinalized(Trigger trigger) { + // build a list of all scheduler listeners that are to be notified... + List schedListeners = getSchedulerListeners(); + + // notify all scheduler listeners + java.util.Iterator itr = schedListeners.iterator(); + while (itr.hasNext()) { + SchedulerListener sl = (SchedulerListener) itr.next(); + try { + sl.triggerFinalized(trigger); + } catch (Exception e) { + getLog().error( + "Error while notifying SchedulerListener of finalized trigger." + + " Triger=" + trigger.getFullName(), e); + } + } + } + + public void notifySchedulerListenersPausedTrigger(String name, String group) { + // build a list of all job listeners that are to be notified... + List schedListeners = getSchedulerListeners(); + + // notify all scheduler listeners + java.util.Iterator itr = schedListeners.iterator(); + while (itr.hasNext()) { + SchedulerListener sl = (SchedulerListener) itr.next(); + try { + sl.triggersPaused(name, group); + } catch (Exception e) { + getLog().error( + "Error while notifying SchedulerListener of paused trigger/group." + + " Triger=" + group + "." + name, e); + } + } + } + + public void notifySchedulerListenersResumedTrigger(String name, String group) { + // build a list of all job listeners that are to be notified... + List schedListeners = getSchedulerListeners(); + + // notify all scheduler listeners + java.util.Iterator itr = schedListeners.iterator(); + while (itr.hasNext()) { + SchedulerListener sl = (SchedulerListener) itr.next(); + try { + sl.triggersResumed(name, group); + } catch (Exception e) { + getLog().error( + "Error while notifying SchedulerListener of resumed trigger/group." + + " Triger=" + group + "." + name, e); + } + } + } + + public void notifySchedulerListenersPausedJob(String name, String group) { + // build a list of all job listeners that are to be notified... + List schedListeners = getSchedulerListeners(); + + // notify all scheduler listeners + java.util.Iterator itr = schedListeners.iterator(); + while (itr.hasNext()) { + SchedulerListener sl = (SchedulerListener) itr.next(); + try { + sl.jobsPaused(name, group); + } catch (Exception e) { + getLog().error( + "Error while notifying SchedulerListener of paused job/group." + + " Job=" + group + "." + name, e); + } + } + } + + public void notifySchedulerListenersResumedJob(String name, String group) { + // build a list of all job listeners that are to be notified... + List schedListeners = getSchedulerListeners(); + + // notify all scheduler listeners + java.util.Iterator itr = schedListeners.iterator(); + while (itr.hasNext()) { + SchedulerListener sl = (SchedulerListener) itr.next(); + try { + sl.jobsResumed(name, group); + } catch (Exception e) { + getLog().error( + "Error while notifying SchedulerListener of resumed job/group." + + " Job=" + group + "." + name, e); + } + } + } + + public void notifySchedulerListenersShutdown() { + // build a list of all job listeners that are to be notified... + List schedListeners = getSchedulerListeners(); + + // notify all scheduler listeners + java.util.Iterator itr = schedListeners.iterator(); + while (itr.hasNext()) { + SchedulerListener sl = (SchedulerListener) itr.next(); + try { + sl.schedulerShutdown(); + } catch (Exception e) { + getLog().error( + "Error while notifying SchedulerListener of shutdown.", + e); + } + } + } + /** + *

+ * Add the given {@link org.quartz.spi.SchedulerPlugin} to + * the Scheduler. This method expects the plugin's + * "initialize" method to be invoked externally (either before or after + * this method is called). + */ + public void addSchedulerPlugin(SchedulerPlugin plugin) { + schedulerPlugins.add(plugin); + } + + + public void setJobFactory(JobFactory factory) throws SchedulerException { + + if(factory == null) + throw new IllegalArgumentException("JobFactory cannot be set to null!"); + + getLog().info("JobFactory set to: " + factory); + + this.jobFactory = factory; + } + + public JobFactory getJobFactory() { + return jobFactory; + } + + + /** + * Interrupt all instances of the identified InterruptableJob. + * + * @see org.quartz.core.RemotableQuartzScheduler#interrupt(java.lang.String, java.lang.String) + */ + public boolean interrupt(SchedulingContext ctxt, String jobName, String groupName) throws UnableToInterruptJobException { + + if(groupName == null) + groupName = Scheduler.DEFAULT_GROUP; + + List jobs = getCurrentlyExecutingJobs(); + java.util.Iterator it = jobs.iterator(); + + JobExecutionContext jec = null; + JobDetail jobDetail = null; + Job job = null; + + boolean interrupted = false; + + while (it.hasNext()) { + jec = (JobExecutionContext)it.next(); + jobDetail = jec.getJobDetail(); + if (jobName.equals(jobDetail.getName()) + && groupName.equals(jobDetail.getGroup())){ + job = jec.getJobInstance(); + if (job instanceof InterruptableJob) { + ((InterruptableJob)job).interrupt(); + interrupted = true; + } else { + throw new UnableToInterruptJobException( + "Job '" + + jobName + + "' of group '" + + groupName + + "' can not be interrupted, since it does not implement " + + InterruptableJob.class.getName()); + + } + } + } + + return interrupted; + } + + private void shutdownPlugins() { + java.util.Iterator itr = schedulerPlugins.iterator(); + while (itr.hasNext()) { + SchedulerPlugin plugin = (SchedulerPlugin) itr.next(); + plugin.shutdown(); + } + } + + private void startPlugins() { + java.util.Iterator itr = schedulerPlugins.iterator(); + while (itr.hasNext()) { + SchedulerPlugin plugin = (SchedulerPlugin) itr.next(); + plugin.start(); + } + } + +} + +///////////////////////////////////////////////////////////////////////////// +// +// ErrorLogger - Scheduler Listener Class +// +///////////////////////////////////////////////////////////////////////////// + +class ErrorLogger implements SchedulerListener { + + public static Log getLog() { + return LogFactory.getLog(ErrorLogger.class); + } + + ErrorLogger() { + } + + public void jobScheduled(Trigger trigger) { + // do nothing... + } + + public void jobUnscheduled(String triggerName, String triggerGroup) { + // do nothing... + } + + public void triggerFinalized(Trigger trigger) { + // do nothing... + } + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * or group of {@link Trigger}s has been paused. + *

+ * + *

+ * If a group was paused, then the triggerName parameter + * will be null. + *

+ */ + public void triggersPaused(String triggerName, String triggerGroup) { + // do nothing... + } + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * or group of {@link Trigger}s has been un-paused. + *

+ * + *

+ * If a group was resumed, then the triggerName parameter + * will be null. + *

+ */ + public void triggersResumed(String triggerName, String triggerGroup) { + // do nothing... + } + + /** + *

+ * Called by the {@link Scheduler} when a {@link org.quartz.JobDetail} + * or group of {@link org.quartz.JobDetail}s has been + * paused. + *

+ * + *

+ * If a group was paused, then the jobName parameter will be + * null. + *

+ */ + public void jobsPaused(String jobName, String jobGroup) { + // do nothing... + } + + /** + *

+ * Called by the {@link Scheduler} when a {@link org.quartz.JobDetail} + * or group of {@link org.quartz.JobDetail}s has been + * un-paused. + *

+ * + *

+ * If a group was paused, then the jobName parameter will be + * null. + *

+ */ + public void jobsResumed(String jobName, String jobGroup) { + // do nothing... + } + + public void schedulerError(String msg, SchedulerException cause) { + getLog().error(msg, cause); + } + + public void schedulerShutdown() { + // do nothing... + } +} + +///////////////////////////////////////////////////////////////////////////// +// +// ExecutingJobsManager - Job Listener Class +// +///////////////////////////////////////////////////////////////////////////// + +class ExecutingJobsManager implements JobListener { + HashMap executingJobs = new HashMap(); + + int numJobsFired = 0; + + ExecutingJobsManager() { + } + + public String getName() { + return getClass().getName(); + } + + public int getNumJobsCurrentlyExecuting() { + synchronized (executingJobs) { + return executingJobs.size(); + } + } + + public void jobToBeExecuted(JobExecutionContext context) { + numJobsFired++; + + synchronized (executingJobs) { + executingJobs + .put(context.getTrigger().getFireInstanceId(), context); + } + } + + public void jobWasExecuted(JobExecutionContext context, + JobExecutionException jobException) { + synchronized (executingJobs) { + executingJobs.remove(context.getTrigger().getFireInstanceId()); + } + } + + public int getNumJobsFired() { + return numJobsFired; + } + + public List getExecutingJobs() { + synchronized (executingJobs) { + return java.util.Collections.unmodifiableList(new ArrayList( + executingJobs.values())); + } + } + + public void jobExecutionVetoed(JobExecutionContext context) { + + } +} Index: 3rdParty_sources/quartz/org/quartz/core/QuartzSchedulerResources.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/core/QuartzSchedulerResources.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/core/QuartzSchedulerResources.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,363 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.core; + +import org.quartz.spi.JobStore; +import org.quartz.spi.ThreadPool; + +/** + *

+ * Contains all of the resources (JobStore,ThreadPool, + * etc.) necessary to create a {@link QuartzScheduler} instance. + *

+ * + * @see QuartzScheduler + * + * @author James House + */ +public class QuartzSchedulerResources { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static final String CREATE_REGISTRY_NEVER = "never"; + + public static final String CREATE_REGISTRY_ALWAYS = "always"; + + public static final String CREATE_REGISTRY_AS_NEEDED = "as_needed"; + + private String name; + + private String instanceId; + + private String threadName; + + private String rmiRegistryHost = null; + + private int rmiRegistryPort = 1099; + + private int rmiServerPort = -1; + + private String rmiCreateRegistryStrategy = CREATE_REGISTRY_NEVER; + + private ThreadPool threadPool; + + private JobStore jobStore; + + private JobRunShellFactory jobRunShellFactory; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create an instance with no properties initialized. + *

+ */ + public QuartzSchedulerResources() { + // do nothing... + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Get the name for the {@link QuartzScheduler}. + *

+ */ + public String getName() { + return name; + } + + /** + *

+ * Set the name for the {@link QuartzScheduler}. + *

+ * + * @exception IllegalArgumentException + * if name is null or empty. + */ + public void setName(String name) { + if (name == null || name.trim().length() == 0) + throw new IllegalArgumentException( + "Scheduler name cannot be empty."); + + this.name = name; + + if (threadName == null) { + // thread name not already set, use default thread name + setThreadName(name + "_QuartzSchedulerThread"); + } + } + + /** + *

+ * Get the instance Id for the {@link QuartzScheduler}. + *

+ */ + public String getInstanceId() { + return instanceId; + } + + /** + *

+ * Set the name for the {@link QuartzScheduler}. + *

+ * + * @exception IllegalArgumentException + * if name is null or empty. + */ + public void setInstanceId(String instanceId) { + if (instanceId == null || instanceId.trim().length() == 0) + throw new IllegalArgumentException( + "Scheduler instanceId cannot be empty."); + + this.instanceId = instanceId; + } + + public static String getUniqueIdentifier(String schedName, + String schedInstId) { + return schedName + "_$_" + schedInstId; + } + + public String getUniqueIdentifier() { + return getUniqueIdentifier(name, instanceId); + } + + /** + *

+ * Get the host name of the RMI Registry that the scheduler should export + * itself to. + *

+ */ + public String getRMIRegistryHost() { + return rmiRegistryHost; + } + + /** + *

+ * Set the host name of the RMI Registry that the scheduler should export + * itself to. + *

+ */ + public void setRMIRegistryHost(String hostName) { + this.rmiRegistryHost = hostName; + } + + /** + *

+ * Get the port number of the RMI Registry that the scheduler should export + * itself to. + *

+ */ + public int getRMIRegistryPort() { + return rmiRegistryPort; + } + + /** + *

+ * Set the port number of the RMI Registry that the scheduler should export + * itself to. + *

+ */ + public void setRMIRegistryPort(int port) { + this.rmiRegistryPort = port; + } + + + /** + *

+ * Get the port number the scheduler server will be bound to. + *

+ */ + public int getRMIServerPort() { + return rmiServerPort; + } + + /** + *

+ * Set the port number the scheduler server will be bound to. + *

+ */ + public void setRMIServerPort(int port) { + this.rmiServerPort = port; + } + + /** + *

+ * Get the setting of whether or not Quartz should create an RMI Registry, + * and if so, how. + *

+ */ + public String getRMICreateRegistryStrategy() { + return rmiCreateRegistryStrategy; + } + + /** + *

+ * Get the name for the {@link QuartzSchedulerThread}. + *

+ */ + public String getThreadName() { + return threadName; + } + + /** + *

+ * Set the name for the {@link QuartzSchedulerThread}. + *

+ * + * @exception IllegalArgumentException + * if name is null or empty. + */ + public void setThreadName(String threadName) { + if (threadName == null || threadName.trim().length() == 0) + throw new IllegalArgumentException( + "Scheduler thread name cannot be empty."); + + this.threadName = threadName; + } + + /** + *

+ * Set whether or not Quartz should create an RMI Registry, and if so, how. + *

+ * + * @see #CREATE_REGISTRY_ALWAYS + * @see #CREATE_REGISTRY_AS_NEEDED + * @see #CREATE_REGISTRY_NEVER + */ + public void setRMICreateRegistryStrategy(String rmiCreateRegistryStrategy) { + if (rmiCreateRegistryStrategy == null + || rmiCreateRegistryStrategy.trim().length() == 0) rmiCreateRegistryStrategy = CREATE_REGISTRY_NEVER; + else if (rmiCreateRegistryStrategy.equalsIgnoreCase("true")) rmiCreateRegistryStrategy = CREATE_REGISTRY_AS_NEEDED; + else if (rmiCreateRegistryStrategy.equalsIgnoreCase("false")) rmiCreateRegistryStrategy = CREATE_REGISTRY_NEVER; + else if (rmiCreateRegistryStrategy + .equalsIgnoreCase(CREATE_REGISTRY_ALWAYS)) rmiCreateRegistryStrategy = CREATE_REGISTRY_ALWAYS; + else if (rmiCreateRegistryStrategy + .equalsIgnoreCase(CREATE_REGISTRY_AS_NEEDED)) rmiCreateRegistryStrategy = CREATE_REGISTRY_AS_NEEDED; + else if (rmiCreateRegistryStrategy + .equalsIgnoreCase(CREATE_REGISTRY_NEVER)) rmiCreateRegistryStrategy = CREATE_REGISTRY_NEVER; + else + throw new IllegalArgumentException( + "Faild to set RMICreateRegistryStrategy - strategy unknown: '" + + rmiCreateRegistryStrategy + "'"); + + this.rmiCreateRegistryStrategy = rmiCreateRegistryStrategy; + } + + /** + *

+ * Get the {@link ThreadPool} for the {@link QuartzScheduler} + * to use. + *

+ */ + public ThreadPool getThreadPool() { + return threadPool; + } + + /** + *

+ * Set the {@link ThreadPool} for the {@link QuartzScheduler} + * to use. + *

+ * + * @exception IllegalArgumentException + * if threadPool is null. + */ + public void setThreadPool(ThreadPool threadPool) { + if (threadPool == null) + throw new IllegalArgumentException("ThreadPool cannot be null."); + + this.threadPool = threadPool; + } + + /** + *

+ * Get the {@link JobStore} for the {@link QuartzScheduler} + * to use. + *

+ */ + public JobStore getJobStore() { + return jobStore; + } + + /** + *

+ * Set the {@link JobStore} for the {@link QuartzScheduler} + * to use. + *

+ * + * @exception IllegalArgumentException + * if jobStore is null. + */ + public void setJobStore(JobStore jobStore) { + if (jobStore == null) + throw new IllegalArgumentException("JobStore cannot be null."); + + this.jobStore = jobStore; + } + + /** + *

+ * Get the {@link JobRunShellFactory} for the {@link QuartzScheduler} + * to use. + *

+ */ + public JobRunShellFactory getJobRunShellFactory() { + return jobRunShellFactory; + } + + /** + *

+ * Set the {@link JobRunShellFactory} for the {@link QuartzScheduler} + * to use. + *

+ * + * @exception IllegalArgumentException + * if jobRunShellFactory is null. + */ + public void setJobRunShellFactory(JobRunShellFactory jobRunShellFactory) { + if (jobRunShellFactory == null) + throw new IllegalArgumentException( + "JobRunShellFactory cannot be null."); + + this.jobRunShellFactory = jobRunShellFactory; + } + +} Index: 3rdParty_sources/quartz/org/quartz/core/QuartzSchedulerThread.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/core/QuartzSchedulerThread.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/core/QuartzSchedulerThread.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,478 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.core; + +import java.util.Random; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.Job; +import org.quartz.JobPersistenceException; +import org.quartz.SchedulerException; +import org.quartz.Trigger; +import org.quartz.spi.TriggerFiredBundle; + +/** + *

+ * The thread responsible for performing the work of firing {@link Trigger} + * s that are registered with the {@link QuartzScheduler}. + *

+ * + * @see QuartzScheduler + * @see Job + * @see Trigger + * + * @author James House + */ +public class QuartzSchedulerThread extends Thread { + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + private QuartzScheduler qs; + + private QuartzSchedulerResources qsRsrcs; + + private Object pauseLock = new Object(); + + private Object idleLock = new Object(); + + private boolean signaled; + + private boolean paused; + + private boolean halted; + + private SchedulingContext ctxt = null; + + private Random random = new Random(System.currentTimeMillis()); + + // When the scheduler finds there is no current trigger to fire, how long + // it should wait until checking again... + private static long DEFAULT_IDLE_WAIT_TIME = 30L * 1000L; + + private long idleWaitTime = DEFAULT_IDLE_WAIT_TIME; + + private int idleWaitVariablness = 7 * 1000; + + private long dbFailureRetryInterval = 15L * 1000L; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Construct a new QuartzSchedulerThread for the given + * QuartzScheduler as a non-daemon Thread + * with normal priority. + *

+ */ + QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs, + SchedulingContext ctxt) { + this(qs, qsRsrcs, ctxt, false, Thread.NORM_PRIORITY); + } + + /** + *

+ * Construct a new QuartzSchedulerThread for the given + * QuartzScheduler as a Thread with the given + * attributes. + *

+ */ + QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs, + SchedulingContext ctxt, boolean setDaemon, int threadPrio) { + super(qs.getSchedulerThreadGroup(), qsRsrcs.getThreadName()); + this.qs = qs; + this.qsRsrcs = qsRsrcs; + this.ctxt = ctxt; + this.setDaemon(setDaemon); + this.setPriority(threadPrio); + + // start the underlying thread, but put this object into the 'paused' + // state + // so processing doesn't start yet... + paused = true; + halted = false; + this.start(); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + void setIdleWaitTime(long waitTime) { + idleWaitTime = waitTime; + idleWaitVariablness = (int) (waitTime * 0.2); + } + + private long getDbFailureRetryInterval() { + return dbFailureRetryInterval; + } + + public void setDbFailureRetryInterval(long dbFailureRetryInterval) { + this.dbFailureRetryInterval = dbFailureRetryInterval; + } + + private long getRandomizedIdleWaitTime() { + return idleWaitTime - random.nextInt(idleWaitVariablness); + } + + /** + *

+ * Signals the main processing loop to pause at the next possible point. + *

+ */ + void togglePause(boolean pause) { + synchronized (pauseLock) { + paused = pause; + + if (paused) { + signalSchedulingChange(); + } else { + pauseLock.notify(); + } + } + } + + /** + *

+ * Signals the main processing loop to pause at the next possible point. + *

+ */ + void halt() { + synchronized (pauseLock) { + halted = true; + + if (paused) { + pauseLock.notify(); + } else { + signalSchedulingChange(); + } + } + } + + boolean isPaused() { + return paused; + } + + /** + *

+ * Signals the main processing loop that a change in scheduling has been + * made - in order to interrupt any sleeping that may be occuring while + * waiting for the fire time to arrive. + *

+ */ + void signalSchedulingChange() { + signaled = true; + } + + /** + *

+ * The main processing loop of the QuartzSchedulerThread. + *

+ */ + public void run() { + boolean lastAcquireFailed = false; + + while (!halted) { + + signaled = false; + + try { + // check if we're supposed to pause... + synchronized (pauseLock) { + while (paused && !halted) { + try { + // wait until togglePause(false) is called... + pauseLock.wait(100L); + } catch (InterruptedException ignore) { + } + } + + if (halted) { + break; + } + } + + Trigger trigger = null; + + long now = System.currentTimeMillis(); + + try { + trigger = qsRsrcs.getJobStore().acquireNextTrigger( + ctxt, now + idleWaitTime); + lastAcquireFailed = false; + } catch (JobPersistenceException jpe) { + if(!lastAcquireFailed) + qs.notifySchedulerListenersError( + "An error occured while scanning for the next trigger to fire.", + jpe); + lastAcquireFailed = true; + } + catch (RuntimeException e) { + if(!lastAcquireFailed) + getLog().error("quartzSchedulerThreadLoop: RuntimeException " + +e.getMessage(), e); + lastAcquireFailed = true; + } + + if (trigger != null) { + + now = System.currentTimeMillis(); + long triggerTime = trigger.getNextFireTime().getTime(); + long timeUntilTrigger = triggerTime - now; + long spinInterval = 10; + + // this looping may seem a bit silly, but it's the + // current work-around + // for a dead-lock that can occur if the Thread.sleep() + // is replaced with + // a obj.wait() that gets notified when the signal is + // set... + // so to be able to detect the signal change without + // sleeping the entire + // timeUntilTrigger, we spin here... don't worry + // though, this spinning + // doesn't even register 0.2% cpu usage on a pentium 4. + int numPauses = (int) (timeUntilTrigger / spinInterval); + while (numPauses >= 0 && !signaled) { + + try { + Thread.sleep(spinInterval); + } catch (InterruptedException ignore) { + } + + now = System.currentTimeMillis(); + timeUntilTrigger = triggerTime - now; + numPauses = (int) (timeUntilTrigger / spinInterval); + } + if (signaled) { + try { + qsRsrcs.getJobStore().releaseAcquiredTrigger( + ctxt, trigger); + } catch (JobPersistenceException jpe) { + qs.notifySchedulerListenersError( + "An error occured while releasing trigger '" + + trigger.getFullName() + "'", + jpe); + // db connection must have failed... keep + // retrying until it's up... + releaseTriggerRetryLoop(trigger); + } catch (RuntimeException e) { + getLog().error( + "releaseTriggerRetryLoop: RuntimeException " + +e.getMessage(), e); + // db connection must have failed... keep + // retrying until it's up... + releaseTriggerRetryLoop(trigger); + } + signaled = false; + continue; + } + + // set trigger to 'executing' + TriggerFiredBundle bndle = null; + + try { + bndle = qsRsrcs.getJobStore().triggerFired(ctxt, + trigger); + } catch (SchedulerException se) { + qs.notifySchedulerListenersError( + "An error occured while firing trigger '" + + trigger.getFullName() + "'", se); + } catch (RuntimeException e) { + getLog().error( + "RuntimeException while firing trigger " + + trigger.getFullName(), e); + // db connection must have failed... keep + // retrying until it's up... + releaseTriggerRetryLoop(trigger); + } + + // it's possible to get 'null' if the trigger was paused, + // blocked, or other similar occurances that prevent it being + // fired at this time... + if (bndle == null) { + try { + qsRsrcs.getJobStore().releaseAcquiredTrigger(ctxt, + trigger); + } catch (SchedulerException se) { + qs.notifySchedulerListenersError( + "An error occured while releasing trigger '" + + trigger.getFullName() + "'", se); + // db connection must have failed... keep retrying + // until it's up... + releaseTriggerRetryLoop(trigger); + } + continue; + } + + // TODO: improvements: + // + // 1- get thread from pool before firing trigger. + // 2- make sure we can get a job runshell first as well, or + // don't let that throw an exception (right now it never does, + // bugthe signature says it can). + // 3- acquire more triggers at a time (based on num threads?) + + + JobRunShell shell = null; + try { + shell = qsRsrcs.getJobRunShellFactory().borrowJobRunShell(); + shell.initialize(qs, bndle); + } catch (SchedulerException se) { + try { + qsRsrcs.getJobStore().triggeredJobComplete(ctxt, + trigger, bndle.getJobDetail(), Trigger.INSTRUCTION_SET_ALL_JOB_TRIGGERS_ERROR); + } catch (SchedulerException se2) { + qs.notifySchedulerListenersError( + "An error occured while releasing trigger '" + + trigger.getFullName() + "'", se2); + // db connection must have failed... keep retrying + // until it's up... + errorTriggerRetryLoop(bndle); + } + continue; + } + + qsRsrcs.getThreadPool().runInThread(shell); + + continue; + } + + // this looping may seem a bit silly, but it's the current + // work-around + // for a dead-lock that can occur if the Thread.sleep() is replaced + // with + // a obj.wait() that gets notified when the signal is set... + // so to be able to detect the signal change without sleeping the + // entier + // getRandomizedIdleWaitTime(), we spin here... don't worry though, + // the + // CPU usage of this spinning can't even be measured on a pentium + // 4. + now = System.currentTimeMillis(); + long waitTime = now + getRandomizedIdleWaitTime(); + long timeUntilContinue = waitTime - now; + long spinInterval = 10; + int numPauses = (int) (timeUntilContinue / spinInterval); + + while (numPauses > 0 && !signaled) { + + try { + Thread.sleep(10L); + } catch (InterruptedException ignore) { + } + + now = System.currentTimeMillis(); + timeUntilContinue = waitTime - now; + numPauses = (int) (timeUntilContinue / spinInterval); + } + } + catch(RuntimeException re) { + getLog().error("Runtime error occured in main trigger firing loop.", re); + } + } // loop... + + // drop references to scheduler stuff to aid garbage collection... + qs = null; + qsRsrcs = null; + } + + public void errorTriggerRetryLoop(TriggerFiredBundle bndle) { + int retryCount = 0; + try { + while (!halted) { + try { + Thread.sleep(getDbFailureRetryInterval()); // retry every N + // seconds (the db + // connection must + // be failed) + retryCount++; + qsRsrcs.getJobStore().triggeredJobComplete(ctxt, + bndle.getTrigger(), bndle.getJobDetail(), Trigger.INSTRUCTION_SET_ALL_JOB_TRIGGERS_ERROR); + retryCount = 0; + break; + } catch (JobPersistenceException jpe) { + if(retryCount % 4 == 0) + qs.notifySchedulerListenersError( + "An error occured while releasing trigger '" + + bndle.getTrigger().getFullName() + "'", jpe); + } catch (RuntimeException e) { + getLog().error("releaseTriggerRetryLoop: RuntimeException "+e.getMessage(), e); + } catch (InterruptedException e) { + getLog().error("releaseTriggerRetryLoop: InterruptedException "+e.getMessage(), e); + } + } + } finally { + if(retryCount == 0) + getLog().info("releaseTriggerRetryLoop: connection restored."); + } + } + + public void releaseTriggerRetryLoop(Trigger trigger) { + int retryCount = 0; + try { + while (!halted) { + try { + Thread.sleep(getDbFailureRetryInterval()); // retry every N + // seconds (the db + // connection must + // be failed) + retryCount++; + qsRsrcs.getJobStore().releaseAcquiredTrigger(ctxt, trigger); + retryCount = 0; + break; + } catch (JobPersistenceException jpe) { + if(retryCount % 4 == 0) + qs.notifySchedulerListenersError( + "An error occured while releasing trigger '" + + trigger.getFullName() + "'", jpe); + } catch (RuntimeException e) { + getLog().error("releaseTriggerRetryLoop: RuntimeException "+e.getMessage(), e); + } catch (InterruptedException e) { + getLog().error("releaseTriggerRetryLoop: InterruptedException "+e.getMessage(), e); + } + } + } finally { + if(retryCount == 0) + getLog().info("releaseTriggerRetryLoop: connection restored."); + } + } + + public static Log getLog() { + return LogFactory.getLog(QuartzSchedulerThread.class); + } + +} // end of QuartzSchedulerThread Index: 3rdParty_sources/quartz/org/quartz/core/RemotableQuartzScheduler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/core/RemotableQuartzScheduler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/core/RemotableQuartzScheduler.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,231 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.core; + +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.util.Date; +import java.util.List; +import java.util.Set; + +import org.quartz.Calendar; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.JobListener; +import org.quartz.SchedulerContext; +import org.quartz.SchedulerException; +import org.quartz.SchedulerListener; +import org.quartz.Trigger; +import org.quartz.TriggerListener; +import org.quartz.UnableToInterruptJobException; + +/** + * @author James House + */ +public interface RemotableQuartzScheduler extends Remote { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public String getSchedulerName() throws RemoteException; + + public String getSchedulerInstanceId() throws RemoteException; + + public SchedulerContext getSchedulerContext() throws SchedulerException, + RemoteException; + + public void start() throws SchedulerException, RemoteException; + + public void standby() throws RemoteException; + + public boolean isInStandbyMode() throws RemoteException; + + public void shutdown() throws RemoteException; + + public void shutdown(boolean waitForJobsToComplete) throws RemoteException; + + public boolean isShutdown() throws RemoteException; + + public Date runningSince() throws RemoteException; + + public String getVersion() throws RemoteException; + + public int numJobsExecuted() throws RemoteException; + + public Class getJobStoreClass() throws RemoteException; + + public boolean supportsPersistence() throws RemoteException; + + public Class getThreadPoolClass() throws RemoteException; + + public int getThreadPoolSize() throws RemoteException; + + public List getCurrentlyExecutingJobs() throws SchedulerException, + RemoteException; + + public Date scheduleJob(SchedulingContext ctxt, JobDetail jobDetail, + Trigger trigger) throws SchedulerException, RemoteException; + + public Date scheduleJob(SchedulingContext ctxt, Trigger trigger) + throws SchedulerException, RemoteException; + + public void addJob(SchedulingContext ctxt, JobDetail jobDetail, + boolean replace) throws SchedulerException, RemoteException; + + public boolean deleteJob(SchedulingContext ctxt, String jobName, + String groupName) throws SchedulerException, RemoteException; + + public boolean unscheduleJob(SchedulingContext ctxt, String triggerName, + String groupName) throws SchedulerException, RemoteException; + + public Date rescheduleJob(SchedulingContext ctxt, String triggerName, + String groupName, Trigger newTrigger) throws SchedulerException, RemoteException; + + + public void triggerJob(SchedulingContext ctxt, String jobName, + String groupName, JobDataMap data) throws SchedulerException, RemoteException; + + public void triggerJobWithVolatileTrigger(SchedulingContext ctxt, + String jobName, String groupName, JobDataMap data) throws SchedulerException, + RemoteException; + + public void pauseTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws SchedulerException, RemoteException; + + public void pauseTriggerGroup(SchedulingContext ctxt, String groupName) + throws SchedulerException, RemoteException; + + public void pauseJob(SchedulingContext ctxt, String jobName, + String groupName) throws SchedulerException, RemoteException; + + public void pauseJobGroup(SchedulingContext ctxt, String groupName) + throws SchedulerException, RemoteException; + + public void resumeTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws SchedulerException, RemoteException; + + public void resumeTriggerGroup(SchedulingContext ctxt, String groupName) + throws SchedulerException, RemoteException; + + public Set getPausedTriggerGroups(SchedulingContext ctxt) + throws SchedulerException, RemoteException; + + public void resumeJob(SchedulingContext ctxt, String jobName, + String groupName) throws SchedulerException, RemoteException; + + public void resumeJobGroup(SchedulingContext ctxt, String groupName) + throws SchedulerException, RemoteException; + + public void pauseAll(SchedulingContext ctxt) throws SchedulerException, + RemoteException; + + public void resumeAll(SchedulingContext ctxt) throws SchedulerException, + RemoteException; + + public String[] getJobGroupNames(SchedulingContext ctxt) + throws SchedulerException, RemoteException; + + public String[] getJobNames(SchedulingContext ctxt, String groupName) + throws SchedulerException, RemoteException; + + public Trigger[] getTriggersOfJob(SchedulingContext ctxt, String jobName, + String groupName) throws SchedulerException, RemoteException; + + public String[] getTriggerGroupNames(SchedulingContext ctxt) + throws SchedulerException, RemoteException; + + public String[] getTriggerNames(SchedulingContext ctxt, String groupName) + throws SchedulerException, RemoteException; + + public JobDetail getJobDetail(SchedulingContext ctxt, String jobName, + String jobGroup) throws SchedulerException, RemoteException; + + public Trigger getTrigger(SchedulingContext ctxt, String triggerName, + String triggerGroup) throws SchedulerException, RemoteException; + + public int getTriggerState(SchedulingContext ctxt, String triggerName, + String triggerGroup) throws SchedulerException, RemoteException; + + public void addCalendar(SchedulingContext ctxt, String calName, + Calendar calendar, boolean replace, boolean updateTriggers) throws SchedulerException, + RemoteException; + + public boolean deleteCalendar(SchedulingContext ctxt, String calName) + throws SchedulerException, RemoteException; + + public Calendar getCalendar(SchedulingContext ctxt, String calName) + throws SchedulerException, RemoteException; + + public String[] getCalendarNames(SchedulingContext ctxt) + throws SchedulerException, RemoteException; + + public void addGlobalJobListener(JobListener jobListener) + throws RemoteException; + + public void addJobListener(JobListener jobListener) throws RemoteException; + + public boolean removeGlobalJobListener(JobListener jobListener) + throws RemoteException; + + public boolean removeJobListener(String name) throws RemoteException; + + public List getGlobalJobListeners() throws RemoteException; + + public Set getJobListenerNames() throws RemoteException; + + public JobListener getJobListener(String name) throws RemoteException; + + public void addGlobalTriggerListener(TriggerListener triggerListener) + throws RemoteException; + + public void addTriggerListener(TriggerListener triggerListener) + throws RemoteException; + + public boolean removeGlobalTriggerListener(TriggerListener triggerListener) + throws RemoteException; + + public boolean removeTriggerListener(String name) throws RemoteException; + + public List getGlobalTriggerListeners() throws RemoteException; + + public Set getTriggerListenerNames() throws RemoteException; + + public TriggerListener getTriggerListener(String name) + throws RemoteException; + + public void addSchedulerListener(SchedulerListener schedulerListener) + throws RemoteException; + + public boolean removeSchedulerListener(SchedulerListener schedulerListener) + throws RemoteException; + + public List getSchedulerListeners() throws RemoteException; + + public boolean interrupt(SchedulingContext ctxt, String jobName, String groupName) throws UnableToInterruptJobException,RemoteException ; + + +} Index: 3rdParty_sources/quartz/org/quartz/core/SchedulerSignalerImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/core/SchedulerSignalerImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/core/SchedulerSignalerImpl.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,81 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.core; + +import org.quartz.SchedulerException; +import org.quartz.Trigger; +import org.quartz.spi.SchedulerSignaler; + +/** + * An interface to be used by JobStore instances in order to + * communicate signals back to the QuartzScheduler. + * + * @author jhouse + */ +public class SchedulerSignalerImpl implements SchedulerSignaler { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private QuartzScheduler sched; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + SchedulerSignalerImpl(QuartzScheduler sched) { + this.sched = sched; + } + + public void notifyTriggerListenersMisfired(Trigger trigger) { + try { + sched.notifyTriggerListenersMisfired(trigger); + } catch (SchedulerException se) { + QuartzScheduler.getLog().error( + "Error notifying listeners of trigger misfire.", se); + sched.notifySchedulerListenersError( + "Error notifying listeners of trigger misfire.", se); + } + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public void signalSchedulingChange() { + sched.notifySchedulerThread(); + } + +} Index: 3rdParty_sources/quartz/org/quartz/core/SchedulingContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/core/SchedulingContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/core/SchedulingContext.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,87 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.core; + +/** + *

+ * An object used to pass information about the 'client' to the QuartzScheduler. + *

+ * + * @see QuartzScheduler + * + * @author James House + */ +public class SchedulingContext implements java.io.Serializable { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private String instanceId; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Construct a SchedulingContext with default values. + *

+ */ + public SchedulingContext() { + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * get the instanceId in the cluster. + *

+ */ + public String getInstanceId() { + return this.instanceId; + } + + /** + *

+ * Set the instanceId. + *

+ */ + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + +} Index: 3rdParty_sources/quartz/org/quartz/core/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/core/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/core/package.html 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,15 @@ + + +Package org.quartz.core + + +

Contains the core classes and interfaces for the Quartz job scheduler.

+ +
+
+
+See the Quartz project + at Open Symphony for more information. + + + \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/ee/jta/JTAJobRunShell.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/ee/jta/JTAJobRunShell.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/ee/jta/JTAJobRunShell.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,141 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.ee.jta; + +import javax.transaction.Status; +import javax.transaction.SystemException; +import javax.transaction.UserTransaction; + +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.core.JobRunShell; +import org.quartz.core.JobRunShellFactory; +import org.quartz.core.SchedulingContext; + +/** + *

+ * An extension of {@link org.quartz.core.JobRunShell} that + * begins an XA transaction before executing the Job, and commits (or + * rolls-back) the transaction after execution completes. + *

+ * + * @see org.quartz.core.JobRunShell + * + * @author James House + */ +public class JTAJobRunShell extends JobRunShell { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private UserTransaction ut; + + private UserTransactionHelper userTxHelper; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a JTAJobRunShell instance with the given settings. + *

+ */ + public JTAJobRunShell(JobRunShellFactory jobRunShellFactory, + Scheduler scheduler, SchedulingContext schdCtxt, + UserTransactionHelper userTxHelper) { + super(jobRunShellFactory, scheduler, schdCtxt); + + this.userTxHelper = userTxHelper; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected void begin() throws SchedulerException { + try { + log.debug("Looking up UserTransaction."); + ut = userTxHelper.lookup(); + + log.debug("Beginning UserTransaction."); + ut.begin(); + } catch (SchedulerException se) { + throw se; + } catch (Exception nse) { + + throw new SchedulerException( + "JTAJobRunShell could not start UserTransaction.", nse); + } + } + + protected void complete(boolean successfulExecution) + throws SchedulerException { + + if (ut == null) return; + + try { + if (ut.getStatus() == Status.STATUS_MARKED_ROLLBACK) { + log.debug("UserTransaction marked for rollback only."); + successfulExecution = false; + } + } catch (SystemException e) { + throw new SchedulerException( + "JTAJobRunShell could not read UserTransaction status.", e); + } + + if (successfulExecution) { + try { + log.debug("Committing UserTransaction."); + ut.commit(); + } catch (Exception nse) { + throw new SchedulerException( + "JTAJobRunShell could not commit UserTransaction.", nse); + } + } else { + try { + log.debug("Rolling-back UserTransaction."); + ut.rollback(); + } catch (Exception nse) { + throw new SchedulerException( + "JTAJobRunShell could not rollback UserTransaction.", + nse); + } + } + + ut = null; + } + +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/ee/jta/JTAJobRunShellFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/ee/jta/JTAJobRunShellFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/ee/jta/JTAJobRunShellFactory.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,117 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.ee.jta; + +import org.quartz.Scheduler; +import org.quartz.SchedulerConfigException; +import org.quartz.core.JobRunShell; +import org.quartz.core.JobRunShellFactory; +import org.quartz.core.SchedulingContext; + +/** + *

+ * Responsible for creating the instances of {@link org.quartz.ee.jta.JTAJobRunShell} + * to be used within the {@link org.quartz.core.QuartzScheduler} + * instance. + *

+ * + *

+ * This implementation does not re-use any objects, it simply makes a new + * JTAJobRunShell each time borrowJobRunShell() is called. + *

+ * + * @author James House + */ +public class JTAJobRunShellFactory implements JobRunShellFactory { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private Scheduler scheduler; + + private SchedulingContext schedCtxt; + + private UserTransactionHelper userTxHelper; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public JTAJobRunShellFactory(UserTransactionHelper userTxHelper) { + this.userTxHelper = userTxHelper; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Initialize the factory, providing a handle to the Scheduler + * that should be made available within the JobRunShell and + * the JobExecutionContext s within it, and a handle to the + * SchedulingContext that the shell will use in its own + * operations with the JobStore. + *

+ */ + public void initialize(Scheduler scheduler, SchedulingContext schedCtxt) + throws SchedulerConfigException { + this.scheduler = scheduler; + this.schedCtxt = schedCtxt; + } + + /** + *

+ * Called by the {@link org.quartz.core.QuartzSchedulerThread} + * to obtain instances of + * {@link org.quartz.core.JobRunShell}. + *

+ */ + public JobRunShell borrowJobRunShell() { + return new JTAJobRunShell(this, scheduler, schedCtxt, userTxHelper); + } + + /** + *

+ * Called by the {@link org.quartz.core.QuartzSchedulerThread} + * to return instances of + * {@link org.quartz.core.JobRunShell}. + *

+ */ + public void returnJobRunShell(JobRunShell jobRunShell) { + jobRunShell.passivate(); + } + +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/ee/jta/UserTransactionHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/ee/jta/UserTransactionHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/ee/jta/UserTransactionHelper.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,121 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.ee.jta; + +import javax.naming.InitialContext; +import javax.transaction.UserTransaction; + +import org.quartz.SchedulerConfigException; +import org.quartz.SchedulerException; + +/** + *

+ * A helper for obtaining a handle to a UserTransaction... + *

+ * + * @author James House + */ +public class UserTransactionHelper { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static final String DEFAULT_USER_TX_LOCATION = "java:comp/UserTransaction"; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private InitialContext ctxt; + + private UserTransaction ut; + + private String userTxURL; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a UserTransactionHelper instance with the given settings. + *

+ */ + public UserTransactionHelper(String userTxURL) + throws SchedulerConfigException { + + try { + ctxt = new InitialContext(); + } catch (Exception e) { + throw new SchedulerConfigException( + "JTAJobRunShellFactory initialization failed.", e); + } + setUserTxLocation(userTxURL); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public String getUserTxLocation() { + return userTxURL; + } + + /** + * Set the JNDI URL at which the Application Server's UserTransaction can + * be found. If not set, the default value is "java:comp/UserTransaction" - + * which works for nearly all application servers. + */ + public void setUserTxLocation(String userTxURL) { + if (userTxURL == null) userTxURL = DEFAULT_USER_TX_LOCATION; + + this.userTxURL = userTxURL; + } + + public UserTransaction lookup() throws SchedulerException { + try { + return (UserTransaction) ctxt.lookup(userTxURL); + } catch (Exception nse) { + throw new SchedulerException( + "UserTransactionHelper could not lookup/create UserTransaction.", + nse); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/ee/servlet/QuartzInitializerListener.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/ee/servlet/QuartzInitializerListener.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/ee/servlet/QuartzInitializerListener.java 17 Aug 2012 15:10:22 -0000 1.1 @@ -0,0 +1,178 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.ee.servlet; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +import org.quartz.Scheduler; +import org.quartz.impl.StdSchedulerFactory; + +/** + *

+ * A ServletContextListner that can be used to initialize Quartz. + *

+ * + *

+ * You'll want to add something like this to your WEB-INF/web.xml file: + * + *

+ *     <context-param>
+ *         <param-name>config-file</param-name>
+ *         <param-value>/some/path/my_quartz.properties</param-value>
+ *     </context-param>
+ *     <context-param>
+ *         <param-name>shutdown-on-unload</param-name>
+ *         <param-value>true</param-value>
+ *     </context-param>
+ *     <context-param>
+ *         <param-name>start-scheduler-on-load</param-name>
+ *         <param-value>true</param-value>
+ *     </context-param>
+ *
+ *     
+ *     <listener>
+ *         <listener-class>
+ *             org.quartz.ee.servlet.QuartzInitializerServletListener
+ *         </listener-class>
+ *     </listener>
+ * 
+ * + *

+ *

+ * The init parameter 'config-file' can be used to specify the path (and + * filename) of your Quartz properties file. If you leave out this parameter, + * the default ("quartz.properties") will be used. + *

+ * + *

+ * The init parameter 'shutdown-on-unload' can be used to specify whether you + * want scheduler.shutdown() called when the servlet is unloaded (usually when + * the application server is being shutdown). Possible values are "true" or + * "false". The default is "true". + *

+ * + *

+ * The init parameter 'start-scheduler-on-load' can be used to specify whether + * you want the scheduler.start() method called when the servlet is first loaded. + * If set to false, your application will need to call the start() method before + * teh scheduler begins to run and process jobs. Possible values are "true" or + * "false". The default is "true", which means the scheduler is started. + *

+ * + * A StdSchedulerFactory instance is stored into the ServletContext. You can gain access + * to the factory from a ServletContext instance like this: + *
+ * + * StdSchedulerFactory factory = (StdSchedulerFactory) ctx + * .getAttribute(QuartzFactoryServlet.QUARTZ_FACTORY_KEY); + * + *
+ * Once you have the factory instance, you can retrieve the Scheduler instance by calling + * getScheduler() on the factory. + * + * @author James House + * @author Chuck Cavaness + * @author John Petrocik + */ +public class QuartzInitializerListener implements ServletContextListener { + + public static final String QUARTZ_FACTORY_KEY = "org.quartz.impl.StdSchedulerFactory.KEY"; + + private boolean performShutdown = true; + + private Scheduler scheduler = null; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public void contextInitialized(ServletContextEvent sce) { + + System.out.println("Quartz Initializer Servlet loaded, initializing Scheduler..."); + + ServletContext servletContext = sce.getServletContext(); + StdSchedulerFactory factory; + try { + + String configFile = servletContext.getInitParameter("config-file"); + String shutdownPref = servletContext.getInitParameter("shutdown-on-unload"); + + if (shutdownPref != null) + performShutdown = Boolean.valueOf(shutdownPref).booleanValue(); + + // get Properties + if (configFile != null) { + factory = new StdSchedulerFactory(configFile); + } else { + factory = new StdSchedulerFactory(); + } + + // Should the Scheduler being started now or later + String startOnLoad = servletContext + .getInitParameter("start-scheduler-on-load"); + /* + * If the "start-scheduler-on-load" init-parameter is not specified, + * the scheduler will be started. This is to maintain backwards + * compatability. + */ + if (startOnLoad == null || (Boolean.valueOf(startOnLoad).booleanValue())) { + // Start now + scheduler = factory.getScheduler(); + scheduler.start(); + System.out.println("Scheduler has been started..."); + } else { + System.out.println("Scheduler has not been started. Use scheduler.start()"); + } + + System.out.println("Storing the Quartz Scheduler Factory in the servlet context at key: " + + QUARTZ_FACTORY_KEY); + servletContext.setAttribute(QUARTZ_FACTORY_KEY, factory); + + } catch (Exception e) { + System.out.println("Quartz Scheduler failed to initialize: " + e.toString()); + e.printStackTrace(); + } + } + + public void contextDestroyed(ServletContextEvent sce) { + + if (!performShutdown) + return; + + try { + if (scheduler != null) + scheduler.shutdown(); + } catch (Exception e) { + System.out.println("Quartz Scheduler failed to shutdown cleanly: " + e.toString()); + e.printStackTrace(); + } + + System.out.println("Quartz Scheduler successful shutdown."); + } + + +} Index: 3rdParty_sources/quartz/org/quartz/ee/servlet/QuartzInitializerServlet.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/ee/servlet/QuartzInitializerServlet.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/ee/servlet/QuartzInitializerServlet.java 17 Aug 2012 15:10:22 -0000 1.1 @@ -0,0 +1,200 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.ee.servlet; + +import java.io.IOException; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.quartz.Scheduler; +import org.quartz.impl.StdSchedulerFactory; + +/** + *

+ * A Servlet that can be used to initialize Quartz, if configured as a + * load-on-startup servlet in a web application. + *

+ * + *

+ * You'll want to add something like this to your WEB-INF/web.xml file: + * + *

+ *     <servlet>
+ *         <servlet-name>
+ *             QuartzInitializer
+ *         </servlet-name>
+ *         <display-name>
+ *             Quartz Initializer Servlet
+ *         </display-name>
+ *         <servlet-class>
+ *             org.quartz.ee.servlet.QuartzInitializerServlet
+ *         </servlet-class>
+ *         <load-on-startup>
+ *             1
+ *         </load-on-startup>
+ *         <init-param>
+ *             <param-name>config-file</param-name>
+ *             <param-value>/some/path/my_quartz.properties</param-value>
+ *         </init-param>
+ *         <init-param>
+ *             <param-name>shutdown-on-unload</param-name>
+ *             <param-value>true</param-value>
+ *         </init-param>
+ *
+ *         <init-param>
+ *             <param-name>start-scheduler-on-load</param-name>
+ *             <param-value>true</param-value>
+ *         </init-param>
+ *
+ *     </servlet>
+ * 
+ * + *

+ *

+ * The init parameter 'config-file' can be used to specify the path (and + * filename) of your Quartz properties file. If you leave out this parameter, + * the default ("quartz.properties") will be used. + *

+ * + *

+ * The init parameter 'shutdown-on-unload' can be used to specify whether you + * want scheduler.shutdown() called when the servlet is unloaded (usually when + * the application server is being shutdown). Possible values are "true" or + * "false". The default is "true". + *

+ * + *

+ * The init parameter 'start-scheduler-on-load' can be used to specify whether + * you want the scheduler.start() method called when the servlet is first loaded. + * If set to false, your application will need to call the start() method before + * teh scheduler begins to run and process jobs. Possible values are "true" or + * "false". The default is "true", which means the scheduler is started. + *

+ * + * A StdSchedulerFactory instance is stored into the ServletContext. You can gain access + * to the factory from a ServletContext instance like this: + *
+ * + * StdSchedulerFactory factory = (StdSchedulerFactory) ctx + * .getAttribute(QuartzFactoryServlet.QUARTZ_FACTORY_KEY); + * + *
+ * Once you have the factory instance, you can retrieve the Scheduler instance by calling + * getScheduler() on the factory. + * + * @author James House + * @author Chuck Cavaness + */ +public class QuartzInitializerServlet extends HttpServlet { + + public static final String QUARTZ_FACTORY_KEY = "org.quartz.impl.StdSchedulerFactory.KEY"; + + private boolean performShutdown = true; + + private Scheduler scheduler = null; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public void init(ServletConfig cfg) throws javax.servlet.ServletException { + super.init(cfg); + + log("Quartz Initializer Servlet loaded, initializing Scheduler..."); + + StdSchedulerFactory factory; + try { + + String configFile = cfg.getInitParameter("config-file"); + String shutdownPref = cfg.getInitParameter("shutdown-on-unload"); + + if (shutdownPref != null) + performShutdown = Boolean.valueOf(shutdownPref).booleanValue(); + + // get Properties + if (configFile != null) { + factory = new StdSchedulerFactory(configFile); + } else { + factory = new StdSchedulerFactory(); + } + + // Should the Scheduler being started now or later + String startOnLoad = cfg + .getInitParameter("start-scheduler-on-load"); + /* + * If the "start-scheduler-on-load" init-parameter is not specified, + * the scheduler will be started. This is to maintain backwards + * compatability. + */ + if (startOnLoad == null || (Boolean.valueOf(startOnLoad).booleanValue())) { + // Start now + scheduler = factory.getScheduler(); + scheduler.start(); + log("Scheduler has been started..."); + } else { + log("Scheduler has not been started. Use scheduler.start()"); + } + + log("Storing the Quartz Scheduler Factory in the servlet context at key: " + + QUARTZ_FACTORY_KEY); + cfg.getServletContext().setAttribute(QUARTZ_FACTORY_KEY, factory); + + } catch (Exception e) { + log("Quartz Scheduler failed to initialize: " + e.toString()); + throw new ServletException(e); + } + } + + public void destroy() { + + if (!performShutdown) + return; + + try { + if (scheduler != null) + scheduler.shutdown(); + } catch (Exception e) { + log("Quartz Scheduler failed to shutdown cleanly: " + e.toString()); + e.printStackTrace(); + } + + log("Quartz Scheduler successful shutdown."); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + } + +} Index: 3rdParty_sources/quartz/org/quartz/helpers/TriggerUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/helpers/TriggerUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/helpers/TriggerUtils.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,1158 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.helpers; + +import java.util.Calendar; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; +import java.util.TimeZone; + +import org.quartz.CronTrigger; +import org.quartz.Scheduler; +import org.quartz.SimpleTrigger; +import org.quartz.Trigger; + +/** + *

+ * Convenience and utility methods for simplifying the construction and + * configuration of {@link Trigger}s. + *

+ * + *

+ * Please submit suggestions for additional convenience methods to either the + * Quartz user forum or the developer's mail list at + * source forge. + *

+ * + * @see CronTrigger + * @see SimpleTrigger + * + * @deprecated use org.quartz.TriggerUtils instead! + * + * @author James House + */ +public class TriggerUtils { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static final int SUNDAY = 1; + + public static final int MONDAY = 2; + + public static final int TUESDAY = 3; + + public static final int WEDNESDAY = 4; + + public static final int THURSDAY = 5; + + public static final int FRIDAY = 6; + + public static final int SATURDAY = 7; + + public static final int LAST_DAY_OF_MONTH = -1; + + public static final long MILLISECONDS_IN_MINUTE = 60l * 1000l; + + public static final long MILLISECONDS_IN_HOUR = 60l * 60l * 1000l; + + public static final long SECONDS_IN_DAY = 24l * 60l * 60L; + + public static final long MILLISECONDS_IN_DAY = SECONDS_IN_DAY * 1000l; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private static void validateDayOfWeek(int dayOfWeek) { + if (dayOfWeek < SUNDAY || dayOfWeek > SATURDAY) + throw new IllegalArgumentException("Invalid day of week."); + } + + private static void validateHour(int hour) { + if (hour < 0 || hour > 23) + throw new IllegalArgumentException( + "Invalid hour (must be >= 0 and <= 23)."); + } + + private static void validateMinute(int minute) { + if (minute < 0 || minute > 59) + throw new IllegalArgumentException( + "Invalid minute (must be >= 0 and <= 59)."); + } + + private static void validateSecond(int second) { + if (second < 0 || second > 59) + throw new IllegalArgumentException( + "Invalid second (must be >= 0 and <= 59)."); + } + + private static void validateDayOfMonth(int day) { + if ((day < 1 || day > 31) && day != LAST_DAY_OF_MONTH) + throw new IllegalArgumentException("Invalid day of month."); + } + + private static void validateMonth(int month) { + if (month < 1 || month > 12) + throw new IllegalArgumentException( + "Invalid month (must be >= 1 and <= 12."); + } + + private static void validateYear(int year) { + if (year < 1970 || year > 2099) + throw new IllegalArgumentException( + "Invalid year (must be >= 1970 and <= 2099."); + } + + /** + *

+ * Set the given Trigger's name to the given value, and its + * group to the default group (Scheduler.DEFAULT_GROUP). + *

+ * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static void setTriggerIdentity(Trigger trig, String name) { + trig.setName(name); + trig.setGroup(Scheduler.DEFAULT_GROUP); + } + + /** + *

+ * Set the given Trigger's name to the given value, and its + * group to the given group. + *

+ * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static void setTriggerIdentity(Trigger trig, String name, + String group) { + trig.setName(name); + trig.setGroup(group); + } + + /** + *

+ * Make a trigger that will fire every day at the given time. + *

+ * + *

+ * The generated trigger will still need to have its name, group, + * start-time and end-time set. + *

+ * + * @param hour + * the hour (0-23) upon which to fire + * @param minute + * the minute (0-59) upon which to fire + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Trigger makeDailyTrigger(int hour, int minute) { + validateHour(hour); + validateMinute(minute); + + CronTrigger trig = new CronTrigger(); + + try { + trig.setCronExpression("0 " + minute + " " + hour + " ? * *"); + } catch (Exception ignore) { + return null; /* never happens... */ + } + + return trig; + } + + /** + *

+ * Make a trigger that will fire every day at the given time. + *

+ * + *

+ * The generated trigger will still need to have its name, group, + * start-time and end-time set. + *

+ * + * @param dayOfWeek + * (1-7) the day of week upon which to fire + * @param hour + * the hour (0-23) upon which to fire + * @param minute + * the minute (0-59) upon which to fire + * + * @see #SUNDAY + * @see #MONDAY + * @see #TUESDAY + * @see #WEDNESDAY + * @see #THURSDAY + * @see #FRIDAY + * @see #SATURDAY + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Trigger makeWeeklyTrigger(int dayOfWeek, int hour, int minute) { + validateDayOfWeek(dayOfWeek); + validateHour(hour); + validateMinute(minute); + + CronTrigger trig = new CronTrigger(); + + try { + trig.setCronExpression("0 " + minute + " " + hour + " ? * " + + dayOfWeek); + } catch (Exception ignore) { + return null; /* never happens... */ + } + + return trig; + } + + /** + *

+ * Make a trigger that will fire every day at the given time. + *

+ * + *

+ * The generated trigger will still need to have its name, group, + * start-time and end-time set. + *

+ * + *

+ * If the day of the month specified does not occur in a given month, a + * firing will not occur that month. (i.e. if dayOfMonth is specified as + * 31, no firing will occur in the months of the year with fewer than 31 + * days). + *

+ * + * @param dayOfMonth + * (1-31, or -1) the day of week upon which to fire + * @param hour + * the hour (0-23) upon which to fire + * @param minute + * the minute (0-59) upon which to fire + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Trigger makeMonthlyTrigger(int dayOfMonth, int hour, + int minute) { + validateDayOfMonth(dayOfMonth); + validateHour(hour); + validateMinute(minute); + + CronTrigger trig = new CronTrigger(); + + try { + if (dayOfMonth != LAST_DAY_OF_MONTH) trig.setCronExpression("0 " + + minute + " " + hour + " " + dayOfMonth + " * ?"); + else + trig.setCronExpression("0 " + minute + " " + hour + " L * ?"); + } catch (Exception ignore) { + return null; /* never happens... */ + } + + return trig; + } + + /* + *

Make a trigger that will fire every N days at the given time.

+ * + *

The generated trigger will still need to have its name, group, + * start-time and end-time set.

+ * + * @param hour the hour (0-23) upon which to fire @param minute the minute + * (0-59) upon which to fire @param interval the number of days between + * firings public static Trigger makeDailyTrigger(int interval, int hour, + * int minute) { + * + * SimpleTrigger trig = new SimpleTrigger(); + * + * MILLISECONDS_IN_DAY); + * trig.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY); + * + * return trig; + * } + */ + + /** + *

+ * Make a trigger that will fire every second, indefinitely. + *

+ * + *

+ * The generated trigger will still need to have its name, group, + * start-time and end-time set. + *

+ * + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Trigger makeSecondlyTrigger() { + return makeSecondlyTrigger(1, SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every N seconds, indefinitely. + *

+ * + *

+ * The generated trigger will still need to have its name, group, + * start-time and end-time set. + *

+ * + * @param intervalInSeconds + * the number of seconds between firings + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Trigger makeSecondlyTrigger(int intervalInSeconds) { + return makeSecondlyTrigger(intervalInSeconds, + SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every N seconds, with the given number of + * repeats. + *

+ * + *

+ * The generated trigger will still need to have its name, group, + * start-time and end-time set. + *

+ * + * @param intervalInSeconds + * the number of seconds between firings + * @param repeatCount + * the number of times to repeat the firing + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Trigger makeSecondlyTrigger(int intervalInSeconds, + int repeatCount) { + SimpleTrigger trig = new SimpleTrigger(); + + trig.setRepeatInterval(intervalInSeconds * 1000l); + trig.setRepeatCount(repeatCount); + + return trig; + } + + /** + *

+ * Make a trigger that will fire every minute, indefinitely. + *

+ * + *

+ * The generated trigger will still need to have its name, group, + * start-time and end-time set. + *

+ * + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Trigger makeMinutelyTrigger() { + return makeMinutelyTrigger(1, SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every N minutes, indefinitely. + *

+ * + *

+ * The generated trigger will still need to have its name, group, + * start-time and end-time set. + *

+ * + * @param intervalInMinutes + * the number of minutes between firings + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Trigger makeMinutelyTrigger(int intervalInMinutes) { + return makeMinutelyTrigger(intervalInMinutes, + SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every N minutes, with the given number of + * repeats. + *

+ * + *

+ * The generated trigger will still need to have its name, group, + * start-time and end-time set. + *

+ * + * @param intervalInMinutes + * the number of minutes between firings + * @param repeatCount + * the number of times to repeat the firing + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Trigger makeMinutelyTrigger(int intervalInMinutes, + int repeatCount) { + SimpleTrigger trig = new SimpleTrigger(); + + trig.setRepeatInterval(intervalInMinutes * MILLISECONDS_IN_MINUTE); + trig.setRepeatCount(repeatCount); + + return trig; + } + + /** + *

+ * Make a trigger that will fire every hour, indefinitely. + *

+ * + *

+ * The generated trigger will still need to have its name, group, + * start-time and end-time set. + *

+ * + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Trigger makeHourlyTrigger() { + return makeHourlyTrigger(1, SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every N hours, indefinitely. + *

+ * + *

+ * The generated trigger will still need to have its name, group, + * start-time and end-time set. + *

+ * + * @param intervalInHours + * the number of hours between firings + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Trigger makeHourlyTrigger(int intervalInHours) { + return makeHourlyTrigger(intervalInHours, + SimpleTrigger.REPEAT_INDEFINITELY); + } + + /** + *

+ * Make a trigger that will fire every N hours, with the given number of + * repeats. + *

+ * + *

+ * The generated trigger will still need to have its name, group, + * start-time and end-time set. + *

+ * + * @param intervalInHours + * the number of hours between firings + * @param repeatCount + * the number of times to repeat the firing + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Trigger makeHourlyTrigger(int intervalInHours, int repeatCount) { + SimpleTrigger trig = new SimpleTrigger(); + + trig.setRepeatInterval(intervalInHours * MILLISECONDS_IN_HOUR); + trig.setRepeatCount(repeatCount); + + return trig; + } + + /** + *

+ * Returns a date that is rounded to the next even hour above the given + * date. + *

+ * + *

+ * For example an input date with a time of 08:13:54 would result in a date + * with the time of 09:00:00. If the date's time is in the 23rd hour, the + * date's 'day' will be promoted, and the time will be set to 00:00:00. + *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Date getEvenHourDate(Date date) { + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.setLenient(true); + + c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) + 1); + c.set(Calendar.MINUTE, 0); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Returns a date that is rounded to the previous even hour below the given + * date. + *

+ * + *

+ * For example an input date with a time of 08:13:54 would result in a date + * with the time of 08:00:00. + *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Date getEvenHourDateBefore(Date date) { + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + + c.set(Calendar.MINUTE, 0); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Returns a date that is rounded to the next even hour above the given + * date. + *

+ * + *

+ * For example an input date with a time of 08:13:54 would result in a date + * with the time of 08:14:00. If the date's time is in the 59th minute, + * then the hour (and possibly the day) will be promoted. + *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Date getEvenMinuteDate(Date date) { + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.setLenient(true); + + c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + 1); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Returns a date that is rounded to the previous even hour below the given + * date. + *

+ * + *

+ * For example an input date with a time of 08:13:54 would result in a date + * with the time of 08:13:00. + *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Date getEvenMinuteDateBefore(Date date) { + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Returns a date that is rounded to the next even second above the given + * date. + *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Date getEvenSecondDate(Date date) { + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.setLenient(true); + + c.set(Calendar.SECOND, c.get(Calendar.SECOND) + 1); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Returns a date that is rounded to the previous even second below the + * given date. + *

+ * + *

+ * For example an input date with a time of 08:13:54.341 would result in a + * date with the time of 08:13:00.000. + *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Date getEvenSecondDateBefore(Date date) { + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Returns a date that is rounded to the next even multiple of the given + * minute. + *

+ * + *

+ * For example an input date with a time of 08:13:54, and an input + * minute-base of 5 would result in a date with the time of 08:15:00. The + * same input date with an input minute-base of 10 would result in a date + * with the time of 08:20:00. But a date with the time 08:53:31 and an + * input minute-base of 45 would result in 09:00:00, because the even-hour + * is the next 'base' for 45-minute intervals. + *

+ * + *

+ * More examples: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Input TimeMinute-BaseResult Time
11:16:412011:20:00
11:36:412011:40:00
11:46:412012:00:00
11:26:413011:30:00
11:36:413012:00:00
11:16:411711:17:00
11:17:411711:34:00
11:52:411712:00:00
11:52:41511:55:00
11:57:41512:00:00
11:17:41012:00:00
11:17:41111:08:00
+ *

+ * + * @param date + * the Date to round, if null the current time will + * be used + * @param minuteBase + * the base-minute to set the time on + * + * @see #getNextGivenSecondDate(Date, int) + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Date getNextGivenMinuteDate(Date date, int minuteBase) { + if (minuteBase < 0 || minuteBase > 59) + throw new IllegalArgumentException( + "minuteBase must be >=0 and <= 59"); + + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.setLenient(true); + + if (minuteBase == 0) { + c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) + 1); + c.set(Calendar.MINUTE, 0); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + int minute = c.get(Calendar.MINUTE); + + int arItr = minute / minuteBase; + + int nextMinuteOccurance = minuteBase * (arItr + 1); + + if (nextMinuteOccurance < 60) { + c.set(Calendar.MINUTE, nextMinuteOccurance); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } else { + c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) + 1); + c.set(Calendar.MINUTE, 0); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + } + + /** + *

+ * Returns a date that is rounded to the next even multiple of the given + * minute. + *

+ * + *

+ * The rules for calculating the second are the same as those for + * calculating the minute in the method getNextGivenMinuteDate(..).

+ * * + * @param date the Date to round, if null the current time will + * be used + * @param secondBase the base-second to set the time on + * + * @see #getNextGivenMinuteDate(Date, int) + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Date getNextGivenSecondDate(Date date, int secondBase) { + if (secondBase < 0 || secondBase > 59) + throw new IllegalArgumentException( + "secondBase must be >=0 and <= 59"); + + if (date == null) date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.setLenient(true); + + if (secondBase == 0) { + c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + 1); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + int second = c.get(Calendar.SECOND); + + int arItr = second / secondBase; + + int nextSecondOccurance = secondBase * (arItr + 1); + + if (nextSecondOccurance < 60) { + c.set(Calendar.SECOND, nextSecondOccurance); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } else { + c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + 1); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + } + + /** + *

+ * Get a Date object that represents the given time, on + * today's date. + *

+ * + * @param second + * The value (0-59) to give the seconds field of the date + * @param minute + * The value (0-59) to give the minutes field of the date + * @param hour + * The value (0-23) to give the hours field of the date + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Date getDateOf(int second, int minute, int hour) { + validateSecond(second); + validateMinute(minute); + validateHour(hour); + + Date date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + c.setLenient(true); + + c.set(Calendar.HOUR_OF_DAY, hour); + c.set(Calendar.MINUTE, minute); + c.set(Calendar.SECOND, second); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Get a Date object that represents the given time, on the + * given date. + *

+ * + * @param second + * The value (0-59) to give the seconds field of the date + * @param minute + * The value (0-59) to give the minutes field of the date + * @param hour + * The value (0-23) to give the hours field of the date + * @param dayOfMonth + * The value (1-31) to give the day of month field of the date + * @param month + * The value (1-12) to give the month field of the date + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Date getDateOf(int second, int minute, int hour, + int dayOfMonth, int month) { + validateSecond(second); + validateMinute(minute); + validateHour(hour); + validateDayOfMonth(dayOfMonth); + validateMonth(month); + + Date date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + + c.set(Calendar.MONTH, month - 1); + c.set(Calendar.DAY_OF_MONTH, dayOfMonth); + c.set(Calendar.HOUR_OF_DAY, hour); + c.set(Calendar.MINUTE, minute); + c.set(Calendar.SECOND, second); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + *

+ * Get a Date object that represents the given time, on the + * given date. + *

+ * + * @param second + * The value (0-59) to give the seconds field of the date + * @param minute + * The value (0-59) to give the minutes field of the date + * @param hour + * The value (0-23) to give the hours field of the date + * @param dayOfMonth + * The value (1-31) to give the day of month field of the date + * @param month + * The value (1-12) to give the month field of the date + * @param year + * The value (1970-2099) to give the year field of the date + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static Date getDateOf(int second, int minute, int hour, + int dayOfMonth, int month, int year) { + validateSecond(second); + validateMinute(minute); + validateHour(hour); + validateDayOfMonth(dayOfMonth); + validateMonth(month); + validateYear(year); + + Date date = new Date(); + + Calendar c = Calendar.getInstance(); + c.setTime(date); + + c.set(Calendar.YEAR, year); + c.set(Calendar.MONTH, month - 1); + c.set(Calendar.DAY_OF_MONTH, dayOfMonth); + c.set(Calendar.HOUR_OF_DAY, hour); + c.set(Calendar.MINUTE, minute); + c.set(Calendar.SECOND, second); + c.set(Calendar.MILLISECOND, 0); + + return c.getTime(); + } + + /** + * Returns a list of Dates that are the next fire times of a Trigger. + * The input trigger will be cloned before any work is done, so you need + * not worry about its state being altered by this method. + * + * @param trigg + * The trigger upon which to do the work + * @param cal + * The calendar to apply to the trigger's schedule + * @param numTimes + * The number of next fire times to produce + * @return List of java.util.Date objects + * + * @deprecated use org.quartz.TriggerUtils instead! + * + */ + public static List computeFireTimes(Trigger trigg, org.quartz.Calendar cal, + int numTimes) { + LinkedList lst = new LinkedList(); + + Trigger t = (Trigger) trigg.clone(); + + if (t.getNextFireTime() == null) { + t.computeFirstFireTime(cal); + } + + for (int i = 0; i < numTimes; i++) { + Date d = t.getNextFireTime(); + if (d != null) { + lst.add(d); + t.triggered(cal); + } else + break; + } + + return java.util.Collections.unmodifiableList(lst); + } + + /** + * Returns a list of Dates that are the next fire times of a Trigger + * that fall within the given date range. The input trigger will be cloned + * before any work is done, so you need not worry about its state being + * altered by this method. + * + * @param trigg + * The trigger upon which to do the work + * @param cal + * The calendar to apply to the trigger's schedule + * @param from + * The starting date at which to find fire times + * @param to + * The ending date at which to stop finding fire times + * @return List of java.util.Date objects + * + * @deprecated use org.quartz.TriggerUtils instead! + * + * + */ + public static List computeFireTimesBetween(Trigger trigg, + org.quartz.Calendar cal, Date from, Date to) { + LinkedList lst = new LinkedList(); + + Trigger t = (Trigger) trigg.clone(); + + if (t.getNextFireTime() == null) { + t.computeFirstFireTime(cal); + } + + // TODO: this method could be more efficient by using logic specific + // to the type of trigger ... + while (true) { + Date d = t.getNextFireTime(); + if (d != null) { + if (d.before(from)) { + t.triggered(cal); + continue; + } + if (d.after(to)) break; + lst.add(d); + t.triggered(cal); + } else + break; + } + + return java.util.Collections.unmodifiableList(lst); + } + + /** + * Translate a date & time from a users timezone to the another + * (probably server) timezone to assist in creating a simple trigger with + * the right date & time. + * + * @deprecated use org.quartz.TriggerUtils instead! + */ + public static Date translateTime(Date date, TimeZone src, TimeZone dest) { + + Date newDate = new Date(); + + int offset = (getOffset(date.getTime(), dest) - getOffset(date.getTime(), src)); + + newDate.setTime(date.getTime() - offset); + + return newDate; + } + + /** + * Gets the offset from UT for the given date in the given timezone, + * taking into account daylight savings. + * + *

+ * Equivalent of TimeZone.getOffset(date) in JDK 1.4, but Quartz is trying + * to support JDK 1.3. + *

+ * + * + * @deprecated use org.quartz.TriggerUtils instead! + */ + public static int getOffset(long date, TimeZone tz) { + + if (tz.inDaylightTime(new Date(date))) { + return tz.getRawOffset() + getDSTSavings(tz); + } + + return tz.getRawOffset(); + } + + /** + *

+ * Equivalent of TimeZone.getDSTSavings() in JDK 1.4, but Quartz is trying + * to support JDK 1.3. + *

+ * + * @deprecated use org.quartz.TriggerUtils instead! + */ + public static int getDSTSavings(TimeZone tz) { + + if (tz.useDaylightTime()) { + return 3600000; + } + return 0; + } + +} Index: 3rdParty_sources/quartz/org/quartz/helpers/VersionPrinter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/helpers/VersionPrinter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/helpers/VersionPrinter.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,48 @@ + +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.helpers; + +import org.quartz.core.QuartzScheduler; + +/** + *

+ * Prints the version of Quartz on stdout. + *

+ * + * @author James House + */ +public class VersionPrinter { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static void main(String[] args) { + System.out.println("Quartz version: " + QuartzScheduler.getVersionMajor() + + "." + QuartzScheduler.getVersionMinor() + "." + + QuartzScheduler.getVersionIteration()); + } +} Index: 3rdParty_sources/quartz/org/quartz/helpers/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/helpers/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/helpers/package.html 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,15 @@ + + +Package org.quartz.helpers + + +

Contains helper classes to make working with Quartz easier.

+ +
+
+
+See the Quartz project + at Open Symphony for more information. + + + \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/impl/DirectSchedulerFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/DirectSchedulerFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/DirectSchedulerFactory.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,390 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.SchedulerFactory; +import org.quartz.core.JobRunShellFactory; +import org.quartz.core.QuartzScheduler; +import org.quartz.core.QuartzSchedulerResources; +import org.quartz.core.SchedulingContext; +import org.quartz.simpl.CascadingClassLoadHelper; +import org.quartz.simpl.RAMJobStore; +import org.quartz.simpl.SimpleThreadPool; +import org.quartz.spi.ClassLoadHelper; +import org.quartz.spi.JobStore; +import org.quartz.spi.ThreadPool; + +import java.util.Collection; + +/** + *

+ * A singleton implementation of {@link org.quartz.SchedulerFactory}. + *

+ * + *

+ * Here are some examples of using this class: + *

+ *

+ * To create a scheduler that does not write anything to the database (is not + * persistent), you can call createVolatileScheduler: + * + *

+ *  DirectSchedulerFactory.getInstance().createVolatileScheduler(10); // 10 threads * // don't forget to start the scheduler: DirectSchedulerFactory.getInstance().getScheduler().start();
+ * 
+ * + * + *

+ * Several create methods are provided for convenience. All create methods + * eventually end up calling the create method with all the parameters: + *

+ * + *
+ *  public void createScheduler(String schedulerName, String schedulerInstanceId, ThreadPool threadPool, JobStore jobStore, String rmiRegistryHost, int rmiRegistryPort)
+ * 
+ * + * + *

+ * Here is an example of using this method: + *

+ * * + * *
// create the thread pool SimpleThreadPool threadPool = new SimpleThreadPool(maxThreads, Thread.NORM_PRIORITY); threadPool.initialize(); * // create the job store JobStore jobStore = new RAMJobStore(); jobStore.initialize();
+ * 
+ *  DirectSchedulerFactory.getInstance().createScheduler("My Quartz Scheduler", "My Instance", threadPool, jobStore, "localhost", 1099); * // don't forget to start the scheduler: DirectSchedulerFactory.getInstance().getScheduler("My Quartz Scheduler", "My Instance").start();
+ * 
+ * + * + *

+ * You can also use a JDBCJobStore instead of the RAMJobStore: + *

+ * + *
+ *  DBConnectionManager.getInstance().addConnectionProvider("someDatasource", new JNDIConnectionProvider("someDatasourceJNDIName"));
+ * 
+ *  JDBCJobStore jdbcJobStore = new JDBCJobStore(); jdbcJobStore.setDataSource("someDatasource"); jdbcJobStore.setPostgresStyleBlobs(true); jdbcJobStore.setTablePrefix("QRTZ_"); jdbcJobStore.setInstanceId("My Instance"); jdbcJobStore.initialize();
+ * 
+ * + * @author Mohammad Rezaei + * @author James House + * + * @see JobStore + * @see ThreadPool + */ +public class DirectSchedulerFactory implements SchedulerFactory { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + public static final String DEFAULT_INSTANCE_ID = "SIMPLE_NON_CLUSTERED"; + + public static final String DEFAULT_SCHEDULER_NAME = "SimpleQuartzScheduler"; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private boolean initialized = false; + + private static DirectSchedulerFactory instance = new DirectSchedulerFactory(); + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private Log getLog() { + return LogFactory.getLog(DirectSchedulerFactory.class); + } + + /** + * Constructor + */ + protected DirectSchedulerFactory() { + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static DirectSchedulerFactory getInstance() { + return instance; + } + + /** + * Creates an in memory job store ({@link RAMJobStore}) + * The thread priority is set to Thread.NORM_PRIORITY + * + * @param maxThreads + * The number of threads in the thread pool + * @throws SchedulerException + * if initialization failed. + */ + public void createVolatileScheduler(int maxThreads) + throws SchedulerException { + SimpleThreadPool threadPool = new SimpleThreadPool(maxThreads, + Thread.NORM_PRIORITY); + threadPool.initialize(); + JobStore jobStore = new RAMJobStore(); + this.createScheduler(threadPool, jobStore); + + } + + /** + * @deprecated see correctly spelled method. + * @see #createVolatileScheduler(int) + */ + public void createVolatileSchduler(int maxThreads) + throws SchedulerException { + createVolatileScheduler(maxThreads); + } + + /** + * Creates a proxy to a remote scheduler. This scheduler can be retrieved + * via {@link DirectSchedulerFactory#getScheduler()} + * + * @param rmiHost + * The hostname for remote scheduler + * @param rmiPort + * Port for the remote scheduler. The default RMI port is 1099. + * @throws SchedulerException + * if the remote scheduler could not be reached. + */ + public void createRemoteScheduler(String rmiHost, int rmiPort) + throws SchedulerException { + createRemoteScheduler(DEFAULT_SCHEDULER_NAME, DEFAULT_INSTANCE_ID, + rmiHost, rmiPort); + initialized = true; + } + + /** + * Same as + * {@link DirectSchedulerFactory#createRemoteScheduler(String rmiHost, int rmiPort)}, + * with the addition of specifying the scheduler name and instance ID. This + * scheduler can only be retrieved via + * {@link DirectSchedulerFactory#getScheduler(String)} + * + * @param schedulerName + * The name for the scheduler. + * @param schedulerInstanceId + * The instance ID for the scheduler. + * @param rmiHost + * The hostname for remote scheduler + * @param rmiPort + * Port for the remote scheduler. The default RMI port is 1099. + * @throws SchedulerException + * if the remote scheduler could not be reached. + */ + protected void createRemoteScheduler(String schedulerName, + String schedulerInstanceId, String rmiHost, int rmiPort) + throws SchedulerException { + SchedulingContext schedCtxt = new SchedulingContext(); + schedCtxt.setInstanceId(schedulerInstanceId); + + String uid = QuartzSchedulerResources.getUniqueIdentifier( + schedulerName, schedulerInstanceId); + + RemoteScheduler remoteScheduler = new RemoteScheduler(schedCtxt, uid, + rmiHost, rmiPort); + + SchedulerRepository schedRep = SchedulerRepository.getInstance(); + schedRep.bind(remoteScheduler); + } + + /** + * Creates a scheduler using the specified thread pool and job store. This + * scheduler can be retrieved via + * {@link DirectSchedulerFactory#getScheduler()} + * + * @param threadPool + * The thread pool for executing jobs + * @param jobStore + * The type of job store + * @throws SchedulerException + * if initialization failed + */ + public void createScheduler(ThreadPool threadPool, JobStore jobStore) + throws SchedulerException { + createScheduler(DEFAULT_SCHEDULER_NAME, DEFAULT_INSTANCE_ID, + threadPool, jobStore); + initialized = true; + } + + /** + * Same as + * {@link DirectSchedulerFactory#createScheduler(ThreadPool threadPool, JobStore jobStore)}, + * with the addition of specifying the scheduler name and instance ID. This + * scheduler can only be retrieved via + * {@link DirectSchedulerFactory#getScheduler(String)} + * + * @param schedulerName + * The name for the scheduler. + * @param schedulerInstanceId + * The instance ID for the scheduler. + * @param threadPool + * The thread pool for executing jobs + * @param jobStore + * The type of job store + * @throws SchedulerException + * if initialization failed + */ + public void createScheduler(String schedulerName, + String schedulerInstanceId, ThreadPool threadPool, JobStore jobStore) + throws SchedulerException { + createScheduler(schedulerName, schedulerInstanceId, threadPool, + jobStore, null, 0, -1, -1); + } + + /** + * Creates a scheduler using the specified thread pool and job store and + * binds it to RMI. + * + * @param schedulerName + * The name for the scheduler. + * @param schedulerInstanceId + * The instance ID for the scheduler. + * @param threadPool + * The thread pool for executing jobs + * @param jobStore + * The type of job store + * @param rmiRegistryHost + * The hostname to register this scheduler with for RMI. Can use + * "null" if no RMI is required. + * @param rmiRegistryPort + * The port for RMI. Typically 1099. + * @param idleWaitTime + * The idle wait time in milliseconds. You can specify "-1" for + * the default value, which is currently 30000 ms. + * @throws SchedulerException + * if initialization failed + */ + public void createScheduler(String schedulerName, + String schedulerInstanceId, ThreadPool threadPool, + JobStore jobStore, String rmiRegistryHost, int rmiRegistryPort, + long idleWaitTime, long dbFailureRetryInterval) + throws SchedulerException { + // Currently only one run-shell factory is available... + JobRunShellFactory jrsf = new StdJobRunShellFactory(); + + // Fire everything up + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + SchedulingContext schedCtxt = new SchedulingContext(); + schedCtxt.setInstanceId(schedulerInstanceId); + + QuartzSchedulerResources qrs = new QuartzSchedulerResources(); + + qrs.setName(schedulerName); + qrs.setInstanceId(schedulerInstanceId); + qrs.setJobRunShellFactory(jrsf); + qrs.setThreadPool(threadPool); + qrs.setJobStore(jobStore); + qrs.setRMIRegistryHost(rmiRegistryHost); + qrs.setRMIRegistryPort(rmiRegistryPort); + + QuartzScheduler qs = new QuartzScheduler(qrs, schedCtxt, idleWaitTime, + dbFailureRetryInterval); + + ClassLoadHelper cch = new CascadingClassLoadHelper(); + cch.initialize(); + + jobStore.initialize(cch, qs.getSchedulerSignaler()); + + Scheduler scheduler = new StdScheduler(qs, schedCtxt); + + jrsf.initialize(scheduler, schedCtxt); + + getLog().info("Quartz scheduler '" + scheduler.getSchedulerName()); + + getLog().info("Quartz scheduler version: " + qs.getVersion()); + + SchedulerRepository schedRep = SchedulerRepository.getInstance(); + + qs.addNoGCObject(schedRep); // prevents the repository from being + // garbage collected + + schedRep.bind(scheduler); + } + + /* + * public void registerSchedulerForRmi(String schedulerName, String + * schedulerId, String registryHost, int registryPort) throws + * SchedulerException, RemoteException { QuartzScheduler scheduler = + * (QuartzScheduler) this.getScheduler(); scheduler.bind(registryHost, + * registryPort); } + */ + + /** + *

+ * Returns a handle to the Scheduler produced by this factory. + *

+ * + *

+ * you must call createRemoteScheduler or createScheduler methods before + * calling getScheduler() + *

+ */ + public Scheduler getScheduler() throws SchedulerException { + if (!initialized) { throw new SchedulerException( + "you must call createRemoteScheduler or createScheduler methods before calling getScheduler()"); } + SchedulerRepository schedRep = SchedulerRepository.getInstance(); + + return schedRep.lookup(DEFAULT_SCHEDULER_NAME); + } + + /** + *

+ * Returns a handle to the Scheduler with the given name, if it exists. + *

+ */ + public Scheduler getScheduler(String schedName) throws SchedulerException { + SchedulerRepository schedRep = SchedulerRepository.getInstance(); + + return schedRep.lookup(schedName); + } + + /** + *

+ * Returns a handle to all known Schedulers (made by any + * StdSchedulerFactory instance.). + *

+ */ + public Collection getAllSchedulers() throws SchedulerException { + return SchedulerRepository.getInstance().lookupAll(); + } + +} Index: 3rdParty_sources/quartz/org/quartz/impl/QuartzServer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/QuartzServer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/QuartzServer.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,281 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl; + +import java.io.BufferedReader; +import java.io.InputStreamReader; + +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.SchedulerFactory; +import org.quartz.Trigger; + +/** + *

+ * Instantiates an instance of Quartz Scheduler as a stand-alone program, if + * the scheduler is configured for RMI it will be made available. + *

+ * + *

+ * The main() method of this class currently accepts 0 or 1 arguemtns, if there + * is an argument, and its value is "console", then the program + * will print a short message on the console (std-out) and wait for the user to + * type "exit" - at which time the scheduler will be shutdown. + *

+ * + *

+ * Future versions of this server should allow additional configuration for + * responding to scheduler events by allowing the user to specify {@link org.quartz.JobListener}, + * {@link org.quartz.TriggerListener} and {@link org.quartz.SchedulerListener} + * classes. + *

+ * + *

+ * Please read the Quartz FAQ entries about RMI before asking questions in the + * forums or mail-lists. + *

+ * + * @author James House + */ +public class QuartzServer implements org.quartz.SchedulerListener { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private Scheduler sched = null; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + QuartzServer() { + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public void serve(SchedulerFactory schedFact, boolean console) + throws Exception { + sched = schedFact.getScheduler(); + + sched.start(); + + try { + Thread.sleep(3000l); + } catch (Exception ignore) { + } + + System.out.println("\n*** The scheduler successfully started."); + + if (console) { + System.out.println("\n"); + System.out + .println("The scheduler will now run until you type \"exit\""); + System.out + .println(" If it was configured to export itself via RMI,"); + System.out.println(" then other process may now use it."); + + BufferedReader rdr = new BufferedReader(new InputStreamReader( + System.in)); + + while (true) { + System.out.print("Type 'exit' to shutdown the server: "); + if ("exit".equals(rdr.readLine())) { + break; + } + } + + System.out.println("\n...Shutting down server..."); + + sched.shutdown(true); + } + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * SchedulerListener Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Called by the {@link Scheduler} when a {@link org.quartz.JobDetail} + * is scheduled. + *

+ */ + public void jobScheduled(Trigger trigger) { + } + + /** + *

+ * Called by the {@link Scheduler} when a {@link org.quartz.JobDetail} + * is unscheduled. + *

+ */ + public void jobUnscheduled(String triggerName, String triggerGroup) { + } + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * has reached the condition in which it will never fire again. + *

+ */ + public void triggerFinalized(Trigger trigger) { + } + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * or group of {@link Trigger}s has been paused. + *

+ * + *

+ * If a group was paused, then the triggerName parameter + * will be null. + *

+ */ + public void triggersPaused(String triggerName, String triggerGroup) { + } + + /** + *

+ * Called by the {@link Scheduler} when a {@link Trigger} + * or group of {@link Trigger}s has been un-paused. + *

+ * + *

+ * If a group was resumed, then the triggerName parameter + * will be null. + *

+ */ + public void triggersResumed(String triggerName, String triggerGroup) { + } + + /** + *

+ * Called by the {@link Scheduler} when a {@link org.quartz.JobDetail} + * or group of {@link org.quartz.JobDetail}s has been + * paused. + *

+ * + *

+ * If a group was paused, then the jobName parameter will be + * null. + *

+ */ + public void jobsPaused(String jobName, String jobGroup) { + } + + /** + *

+ * Called by the {@link Scheduler} when a {@link org.quartz.JobDetail} + * or group of {@link org.quartz.JobDetail}s has been + * un-paused. + *

+ * + *

+ * If a group was paused, then the jobName parameter will be + * null. + *

+ */ + public void jobsResumed(String jobName, String jobGroup) { + } + + /** + *

+ * Called by the {@link Scheduler} when a serious error has + * occured within the scheduler - such as repeated failures in the JobStore, + * or the inability to instantiate a Job instance when its + * Trigger has fired. + *

+ * + *

+ * The getErrorCode() method of the given SchedulerException + * can be used to determine more specific information about the type of + * error that was encountered. + *

+ */ + public void schedulerError(String msg, SchedulerException cause) { + System.err.println("*** " + msg); + cause.printStackTrace(); + } + + /** + *

+ * Called by the {@link Scheduler} to inform the listener + * that it has shutdown. + *

+ */ + public void schedulerShutdown() { + System.out.println("\n*** The scheduler is now shutdown."); + sched = null; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Main Method. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static void main(String[] args) throws Exception { + + // //Configure Log4J + // org.apache.log4j.PropertyConfigurator.configure( + // System.getProperty("log4jConfigFile", "log4j.properties")); + + if (System.getSecurityManager() == null) { + System.setSecurityManager(new java.rmi.RMISecurityManager()); + } + + try { + QuartzServer server = new QuartzServer(); + if (args.length == 0) server.serve( + new org.quartz.impl.StdSchedulerFactory(), false); + else if (args.length == 1 && args[0].equalsIgnoreCase("console")) server + .serve(new org.quartz.impl.StdSchedulerFactory(), true); + else { + System.err.println("\nUsage: QuartzServer [console]"); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + +} Index: 3rdParty_sources/quartz/org/quartz/impl/RemoteScheduler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/RemoteScheduler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/RemoteScheduler.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,1091 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl; + +import java.rmi.RemoteException; +import java.rmi.registry.LocateRegistry; +import java.rmi.registry.Registry; +import java.util.Date; +import java.util.List; +import java.util.Set; + +import org.quartz.Calendar; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.JobListener; +import org.quartz.Scheduler; +import org.quartz.SchedulerContext; +import org.quartz.SchedulerException; +import org.quartz.SchedulerListener; +import org.quartz.SchedulerMetaData; +import org.quartz.Trigger; +import org.quartz.TriggerListener; +import org.quartz.UnableToInterruptJobException; +import org.quartz.core.RemotableQuartzScheduler; +import org.quartz.core.SchedulingContext; +import org.quartz.spi.JobFactory; + +/** + *

+ * An implementation of the Scheduler interface that remotely + * proxies all method calls to the equivalent call on a given QuartzScheduler + * instance, via RMI. + *

+ * + * @see org.quartz.Scheduler + * @see org.quartz.core.QuartzScheduler + * @see org.quartz.core.SchedulingContext + * + * @author James House + */ +public class RemoteScheduler implements Scheduler { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private RemotableQuartzScheduler rsched; + + private SchedulingContext schedCtxt; + + private String schedId; + + private String rmiHost; + + private int rmiPort; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Construct a RemoteScheduler instance to proxy the given + * RemoteableQuartzScheduler instance, and with the given + * SchedulingContext. + *

+ */ + public RemoteScheduler(SchedulingContext schedCtxt, String schedId, + String host, int port) { + + this.schedCtxt = schedCtxt; + this.schedId = schedId; + this.rmiHost = host; + this.rmiPort = port; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected RemotableQuartzScheduler getRemoteScheduler() + throws SchedulerException { + if (rsched != null) return rsched; + + try { + Registry registry = LocateRegistry.getRegistry(rmiHost, rmiPort); + + rsched = (RemotableQuartzScheduler) registry.lookup(schedId); + + } catch (Exception e) { + SchedulerException initException = new SchedulerException( + "Could not get handle to remote scheduler: " + + e.getMessage(), e); + initException + .setErrorCode(SchedulerException.ERR_COMMUNICATION_FAILURE); + throw initException; + } + + return rsched; + } + + protected SchedulerException invalidateHandleCreateException(String msg, + Exception cause) { + rsched = null; + SchedulerException ex = new SchedulerException(msg, cause); + ex.setErrorCode(SchedulerException.ERR_COMMUNICATION_FAILURE); + return ex; + } + + /** + *

+ * Returns the name of the Scheduler. + *

+ */ + public String getSchedulerName() throws SchedulerException { + try { + return getRemoteScheduler().getSchedulerName(); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Returns the instance Id of the Scheduler. + *

+ */ + public String getSchedulerInstanceId() throws SchedulerException { + try { + return getRemoteScheduler().getSchedulerInstanceId(); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + public SchedulerMetaData getMetaData() throws SchedulerException { + try { + RemotableQuartzScheduler sched = getRemoteScheduler(); + return new SchedulerMetaData(getSchedulerName(), + getSchedulerInstanceId(), getClass(), true, sched + .runningSince() != null, isPaused(), isShutdown(), + sched.runningSince(), sched.numJobsExecuted(), sched + .getJobStoreClass(), sched.supportsPersistence(), + sched.getThreadPoolClass(), sched.getThreadPoolSize(), + sched.getVersion()); + + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + + } + + /** + *

+ * Returns the SchedulerContext of the Scheduler. + *

+ */ + public SchedulerContext getContext() throws SchedulerException { + try { + return getRemoteScheduler().getSchedulerContext(); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /////////////////////////////////////////////////////////////////////////// + /// + /// Schedululer State Management Methods + /// + /////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void start() throws SchedulerException { + try { + getRemoteScheduler().start(); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void standby() throws SchedulerException { + try { + getRemoteScheduler().standby(); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + * @see org.quartz.Scheduler#pause() + * @deprecated + */ + public void pause() throws SchedulerException { + this.standby(); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean isInStandbyMode() throws SchedulerException { + try { + return getRemoteScheduler().isInStandbyMode(); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + public boolean isPaused() throws SchedulerException { + return this.isInStandbyMode(); + } + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void shutdown() throws SchedulerException { + try { + getRemoteScheduler().shutdown(); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void shutdown(boolean waitForJobsToComplete) + throws SchedulerException { + try { + getRemoteScheduler().shutdown(waitForJobsToComplete); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean isShutdown() throws SchedulerException { + try { + return getRemoteScheduler().isShutdown(); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public List getCurrentlyExecutingJobs() throws SchedulerException { + try { + return getRemoteScheduler().getCurrentlyExecutingJobs(); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /////////////////////////////////////////////////////////////////////////// + /// + /// Scheduling-related Methods + /// + /////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public Date scheduleJob(JobDetail jobDetail, Trigger trigger) + throws SchedulerException { + try { + return getRemoteScheduler().scheduleJob(schedCtxt, jobDetail, + trigger); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public Date scheduleJob(Trigger trigger) throws SchedulerException { + try { + return getRemoteScheduler().scheduleJob(schedCtxt, trigger); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void addJob(JobDetail jobDetail, boolean replace) + throws SchedulerException { + try { + getRemoteScheduler().addJob(schedCtxt, jobDetail, replace); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public boolean deleteJob(String jobName, String groupName) + throws SchedulerException { + try { + return getRemoteScheduler() + .deleteJob(schedCtxt, jobName, groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public boolean unscheduleJob(String triggerName, String groupName) + throws SchedulerException { + try { + return getRemoteScheduler().unscheduleJob(schedCtxt, triggerName, + groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public Date rescheduleJob(String triggerName, + String groupName, Trigger newTrigger) throws SchedulerException { + try { + return getRemoteScheduler().rescheduleJob(schedCtxt, triggerName, + groupName, newTrigger); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void triggerJob(String jobName, String groupName) + throws SchedulerException { + triggerJob(jobName, groupName, null); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void triggerJob(String jobName, String groupName, JobDataMap data) + throws SchedulerException { + try { + getRemoteScheduler().triggerJob(schedCtxt, jobName, groupName, data); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void triggerJobWithVolatileTrigger(String jobName, String groupName) + throws SchedulerException { + triggerJobWithVolatileTrigger(jobName, groupName, null); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void triggerJobWithVolatileTrigger(String jobName, String groupName, JobDataMap data) + throws SchedulerException { + try { + getRemoteScheduler().triggerJobWithVolatileTrigger(schedCtxt, + jobName, groupName, data); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void pauseTrigger(String triggerName, String groupName) + throws SchedulerException { + try { + getRemoteScheduler() + .pauseTrigger(schedCtxt, triggerName, groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void pauseTriggerGroup(String groupName) throws SchedulerException { + try { + getRemoteScheduler().pauseTriggerGroup(schedCtxt, groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void pauseJob(String jobName, String groupName) + throws SchedulerException { + try { + getRemoteScheduler().pauseJob(schedCtxt, jobName, groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void pauseJobGroup(String groupName) throws SchedulerException { + try { + getRemoteScheduler().pauseJobGroup(schedCtxt, groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void resumeTrigger(String triggerName, String groupName) + throws SchedulerException { + try { + getRemoteScheduler().resumeTrigger(schedCtxt, triggerName, + groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void resumeTriggerGroup(String groupName) throws SchedulerException { + try { + getRemoteScheduler().resumeTriggerGroup(schedCtxt, groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void resumeJob(String jobName, String groupName) + throws SchedulerException { + try { + getRemoteScheduler().resumeJob(schedCtxt, jobName, groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void resumeJobGroup(String groupName) throws SchedulerException { + try { + getRemoteScheduler().resumeJobGroup(schedCtxt, groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void pauseAll() throws SchedulerException { + try { + getRemoteScheduler().pauseAll(schedCtxt); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void resumeAll() throws SchedulerException { + try { + getRemoteScheduler().resumeAll(schedCtxt); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public String[] getJobGroupNames() throws SchedulerException { + try { + return getRemoteScheduler().getJobGroupNames(schedCtxt); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public String[] getJobNames(String groupName) throws SchedulerException { + try { + return getRemoteScheduler().getJobNames(schedCtxt, groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public Trigger[] getTriggersOfJob(String jobName, String groupName) + throws SchedulerException { + try { + return getRemoteScheduler().getTriggersOfJob(schedCtxt, jobName, + groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public String[] getTriggerGroupNames() throws SchedulerException { + try { + return getRemoteScheduler().getTriggerGroupNames(schedCtxt); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public String[] getTriggerNames(String groupName) throws SchedulerException { + try { + return getRemoteScheduler().getTriggerNames(schedCtxt, groupName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public JobDetail getJobDetail(String jobName, String jobGroup) + throws SchedulerException { + try { + return getRemoteScheduler().getJobDetail(schedCtxt, jobName, + jobGroup); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public Trigger getTrigger(String triggerName, String triggerGroup) + throws SchedulerException { + try { + return getRemoteScheduler().getTrigger(schedCtxt, triggerName, + triggerGroup); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public int getTriggerState(String triggerName, String triggerGroup) + throws SchedulerException { + try { + return getRemoteScheduler().getTriggerState(schedCtxt, triggerName, + triggerGroup); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void addCalendar(String calName, Calendar calendar, boolean replace, boolean updateTriggers) + throws SchedulerException { + try { + getRemoteScheduler().addCalendar(schedCtxt, calName, calendar, + replace, updateTriggers); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public boolean deleteCalendar(String calName) throws SchedulerException { + try { + return getRemoteScheduler().deleteCalendar(schedCtxt, calName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public Calendar getCalendar(String calName) throws SchedulerException { + try { + return getRemoteScheduler().getCalendar(schedCtxt, calName); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public String[] getCalendarNames() throws SchedulerException { + try { + return getRemoteScheduler().getCalendarNames(schedCtxt); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /////////////////////////////////////////////////////////////////////////// + /// + /// Listener-related Methods + /// + /////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void addGlobalJobListener(JobListener jobListener) + throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void addJobListener(JobListener jobListener) + throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean removeGlobalJobListener(JobListener jobListener) + throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean removeJobListener(String name) throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public List getGlobalJobListeners() throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public Set getJobListenerNames() throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public JobListener getJobListener(String name) throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void addGlobalTriggerListener(TriggerListener triggerListener) + throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void addTriggerListener(TriggerListener triggerListener) + throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean removeGlobalTriggerListener(TriggerListener triggerListener) + throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean removeTriggerListener(String name) throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public List getGlobalTriggerListeners() throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public Set getTriggerListenerNames() throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public TriggerListener getTriggerListener(String name) + throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void addSchedulerListener(SchedulerListener schedulerListener) + throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean removeSchedulerListener(SchedulerListener schedulerListener) + throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public List getSchedulerListeners() throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } + + /** + * @see org.quartz.Scheduler#getPausedTriggerGroups() + */ + public Set getPausedTriggerGroups() throws SchedulerException { + try { + return getRemoteScheduler().getPausedTriggerGroups(schedCtxt); + } catch (RemoteException re) { + throw invalidateHandleCreateException( + "Error communicating with remote scheduler.", re); + } + } + + /** + * @see org.quartz.Scheduler#interrupt(java.lang.String, java.lang.String) + */ + public boolean interrupt(String jobName, String groupName) throws UnableToInterruptJobException { + try { + return getRemoteScheduler().interrupt(schedCtxt, jobName, groupName); + } catch (RemoteException re) { + throw new UnableToInterruptJobException(invalidateHandleCreateException( + "Error communicating with remote scheduler.", re)); + } catch (SchedulerException se) { + throw new UnableToInterruptJobException(se); + } + } + + /** + * @see org.quartz.Scheduler#setJobFactory(org.quartz.spi.JobFactory) + */ + public void setJobFactory(JobFactory factory) throws SchedulerException { + throw new SchedulerException( + "Operation not supported for remote schedulers.", + SchedulerException.ERR_UNSUPPORTED_FUNCTION_IN_THIS_CONFIGURATION); + } +} Index: 3rdParty_sources/quartz/org/quartz/impl/SchedulerRepository.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/SchedulerRepository.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/SchedulerRepository.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,101 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl; + +import java.util.Collection; +import java.util.HashMap; + +import org.quartz.Scheduler; +import org.quartz.SchedulerException; + +/** + *

+ * Holds references to Scheduler instances - ensuring uniqueness, and + * preventing garbage collection, and allowing 'global' lookups - all within a + * ClassLoader space. + *

+ * + * @author James House + */ +public class SchedulerRepository { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private HashMap schedulers; + + private static SchedulerRepository inst; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private SchedulerRepository() { + schedulers = new HashMap(); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static synchronized SchedulerRepository getInstance() { + if (inst == null) inst = new SchedulerRepository(); + + return inst; + } + + public synchronized void bind(Scheduler sched) throws SchedulerException { + + if ((Scheduler) schedulers.get(sched.getSchedulerName()) != null) + throw new SchedulerException("Scheduler with name '" + + sched.getSchedulerName() + "' already exists.", + SchedulerException.ERR_BAD_CONFIGURATION); + + schedulers.put(sched.getSchedulerName(), sched); + } + + public synchronized boolean remove(String schedName) { + return (schedulers.remove(schedName) != null); + } + + public synchronized Scheduler lookup(String schedName) { + return (Scheduler) schedulers.get(schedName); + } + + public synchronized Collection lookupAll() { + return java.util.Collections + .unmodifiableCollection(schedulers.values()); + } + +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/impl/StdJobRunShellFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/StdJobRunShellFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/StdJobRunShellFactory.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,100 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl; + +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.core.JobRunShell; +import org.quartz.core.JobRunShellFactory; +import org.quartz.core.SchedulingContext; + +/** + *

+ * Responsible for creating the instances of {@link org.quartz.core.JobRunShell} + * to be used within the {@link org.quartz.core.QuartzScheduler} + * instance. + *

+ * + *

+ * This implementation does not re-use any objects, it simply makes a new + * JobRunShell each time borrowJobRunShell() is called. + *

+ * + * @author James House + */ +public class StdJobRunShellFactory implements JobRunShellFactory { + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private Scheduler scheduler; + + private SchedulingContext schedCtxt; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Initialize the factory, providing a handle to the Scheduler + * that should be made available within the JobRunShell and + * the JobExecutionCOntext s within it, and a handle to the + * SchedulingContext that the shell will use in its own + * operations with the JobStore. + *

+ */ + public void initialize(Scheduler scheduler, SchedulingContext schedCtxt) { + this.scheduler = scheduler; + this.schedCtxt = schedCtxt; + } + + /** + *

+ * Called by the {@link org.quartz.core.QuartzSchedulerThread} + * to obtain instances of + * {@link org.quartz.core.JobRunShell}. + *

+ */ + public JobRunShell borrowJobRunShell() throws SchedulerException { + return new JobRunShell(this, scheduler, schedCtxt); + } + + /** + *

+ * Called by the {@link org.quartz.core.QuartzSchedulerThread} + * to return instances of + * {@link org.quartz.core.JobRunShell}. + *

+ */ + public void returnJobRunShell(JobRunShell jobRunShell) { + jobRunShell.passivate(); + } + +} Index: 3rdParty_sources/quartz/org/quartz/impl/StdScheduler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/StdScheduler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/StdScheduler.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,776 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl; + +import java.util.Date; +import java.util.List; +import java.util.Set; + +import org.quartz.Calendar; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.JobListener; +import org.quartz.Scheduler; +import org.quartz.SchedulerContext; +import org.quartz.SchedulerException; +import org.quartz.SchedulerListener; +import org.quartz.SchedulerMetaData; +import org.quartz.Trigger; +import org.quartz.TriggerListener; +import org.quartz.UnableToInterruptJobException; +import org.quartz.core.QuartzScheduler; +import org.quartz.core.SchedulingContext; +import org.quartz.spi.JobFactory; + +/** + *

+ * An implementation of the Scheduler interface that directly + * proxies all method calls to the equivalent call on a given QuartzScheduler + * instance. + *

+ * + * @see org.quartz.Scheduler + * @see org.quartz.core.QuartzScheduler + * @see org.quartz.core.SchedulingContext + * + * @author James House + */ +public class StdScheduler implements Scheduler { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private QuartzScheduler sched; + + private SchedulingContext schedCtxt; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Construct a StdScheduler instance to proxy the given + * QuartzScheduler instance, and with the given SchedulingContext. + *

+ */ + public StdScheduler(QuartzScheduler sched, SchedulingContext schedCtxt) { + this.sched = sched; + this.schedCtxt = schedCtxt; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Returns the name of the Scheduler. + *

+ */ + public String getSchedulerName() { + return sched.getSchedulerName(); + } + + /** + *

+ * Returns the instance Id of the Scheduler. + *

+ */ + public String getSchedulerInstanceId() { + return sched.getSchedulerInstanceId(); + } + + public SchedulerMetaData getMetaData() { + return new SchedulerMetaData(getSchedulerName(), + getSchedulerInstanceId(), getClass(), false, sched + .runningSince() != null, isPaused(), isShutdown(), + sched.runningSince(), sched.numJobsExecuted(), sched + .getJobStoreClass(), sched.supportsPersistence(), sched + .getThreadPoolClass(), sched.getThreadPoolSize(), sched + .getVersion()); + + } + + /** + *

+ * Returns the SchedulerContext of the Scheduler. + *

+ */ + public SchedulerContext getContext() throws SchedulerException { + return sched.getSchedulerContext(); + } + + /////////////////////////////////////////////////////////////////////////// + /// + /// Schedululer State Management Methods + /// + /////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void start() throws SchedulerException { + sched.start(); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ * + * @deprecated + * @see standby() + */ + public void pause() { + this.standby(); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void standby() { + sched.standby(); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean isInStandbyMode() { + return sched.isInStandbyMode(); + } + + /** + * @deprecated + */ + public boolean isPaused() { + return isInStandbyMode(); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void shutdown() { + sched.shutdown(); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void shutdown(boolean waitForJobsToComplete) { + sched.shutdown(waitForJobsToComplete); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean isShutdown() { + return sched.isShutdown(); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public List getCurrentlyExecutingJobs() { + return sched.getCurrentlyExecutingJobs(); + } + + /////////////////////////////////////////////////////////////////////////// + /// + /// Scheduling-related Methods + /// + /////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public Date scheduleJob(JobDetail jobDetail, Trigger trigger) + throws SchedulerException { + return sched.scheduleJob(schedCtxt, jobDetail, trigger); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public Date scheduleJob(Trigger trigger) throws SchedulerException { + return sched.scheduleJob(schedCtxt, trigger); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void addJob(JobDetail jobDetail, boolean replace) + throws SchedulerException { + sched.addJob(schedCtxt, jobDetail, replace); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public boolean deleteJob(String jobName, String groupName) + throws SchedulerException { + return sched.deleteJob(schedCtxt, jobName, groupName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public boolean unscheduleJob(String triggerName, String groupName) + throws SchedulerException { + return sched.unscheduleJob(schedCtxt, triggerName, groupName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public Date rescheduleJob(String triggerName, + String groupName, Trigger newTrigger) throws SchedulerException { + return sched.rescheduleJob(schedCtxt, triggerName, groupName, newTrigger); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void triggerJob(String jobName, String groupName) + throws SchedulerException { + triggerJob(jobName, groupName, null); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void triggerJob(String jobName, String groupName, JobDataMap data) + throws SchedulerException { + sched.triggerJob(schedCtxt, jobName, groupName, data); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void triggerJobWithVolatileTrigger(String jobName, String groupName) + throws SchedulerException { + triggerJobWithVolatileTrigger(jobName, groupName, null); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void triggerJobWithVolatileTrigger(String jobName, String groupName, JobDataMap data) + throws SchedulerException { + sched.triggerJobWithVolatileTrigger(schedCtxt, jobName, groupName, data); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void pauseTrigger(String triggerName, String groupName) + throws SchedulerException { + sched.pauseTrigger(schedCtxt, triggerName, groupName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void pauseTriggerGroup(String groupName) throws SchedulerException { + sched.pauseTriggerGroup(schedCtxt, groupName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void pauseJob(String jobName, String groupName) + throws SchedulerException { + sched.pauseJob(schedCtxt, jobName, groupName); + } + + /** + * @see org.quartz.Scheduler#getPausedTriggerGroups() + */ + public Set getPausedTriggerGroups() throws SchedulerException { + return sched.getPausedTriggerGroups(schedCtxt); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void pauseJobGroup(String groupName) throws SchedulerException { + sched.pauseJobGroup(schedCtxt, groupName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void resumeTrigger(String triggerName, String groupName) + throws SchedulerException { + sched.resumeTrigger(schedCtxt, triggerName, groupName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void resumeTriggerGroup(String groupName) throws SchedulerException { + sched.resumeTriggerGroup(schedCtxt, groupName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void resumeJob(String jobName, String groupName) + throws SchedulerException { + sched.resumeJob(schedCtxt, jobName, groupName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void resumeJobGroup(String groupName) throws SchedulerException { + sched.resumeJobGroup(schedCtxt, groupName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void pauseAll() throws SchedulerException { + sched.pauseAll(schedCtxt); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void resumeAll() throws SchedulerException { + sched.resumeAll(schedCtxt); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public String[] getJobGroupNames() throws SchedulerException { + return sched.getJobGroupNames(schedCtxt); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public Trigger[] getTriggersOfJob(String jobName, String groupName) + throws SchedulerException { + return sched.getTriggersOfJob(schedCtxt, jobName, groupName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public String[] getJobNames(String groupName) throws SchedulerException { + return sched.getJobNames(schedCtxt, groupName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public String[] getTriggerGroupNames() throws SchedulerException { + return sched.getTriggerGroupNames(schedCtxt); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public String[] getTriggerNames(String groupName) throws SchedulerException { + return sched.getTriggerNames(schedCtxt, groupName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public JobDetail getJobDetail(String jobName, String jobGroup) + throws SchedulerException { + return sched.getJobDetail(schedCtxt, jobName, jobGroup); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public Trigger getTrigger(String triggerName, String triggerGroup) + throws SchedulerException { + return sched.getTrigger(schedCtxt, triggerName, triggerGroup); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public int getTriggerState(String triggerName, String triggerGroup) + throws SchedulerException { + return sched.getTriggerState(schedCtxt, triggerName, triggerGroup); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public void addCalendar(String calName, Calendar calendar, boolean replace, boolean updateTriggers) + throws SchedulerException { + sched.addCalendar(schedCtxt, calName, calendar, replace, updateTriggers); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public boolean deleteCalendar(String calName) throws SchedulerException { + return sched.deleteCalendar(schedCtxt, calName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public Calendar getCalendar(String calName) throws SchedulerException { + return sched.getCalendar(schedCtxt, calName); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler, + * passing the SchedulingContext associated with this + * instance. + *

+ */ + public String[] getCalendarNames() throws SchedulerException { + return sched.getCalendarNames(schedCtxt); + } + + /////////////////////////////////////////////////////////////////////////// + /// + /// Listener-related Methods + /// + /////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void addGlobalJobListener(JobListener jobListener) { + sched.addGlobalJobListener(jobListener); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void addJobListener(JobListener jobListener) { + sched.addJobListener(jobListener); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean removeGlobalJobListener(JobListener jobListener) { + return sched.removeGlobalJobListener(jobListener); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean removeJobListener(String name) { + return sched.removeJobListener(name); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public List getGlobalJobListeners() { + return sched.getGlobalJobListeners(); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public Set getJobListenerNames() { + return sched.getJobListenerNames(); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public JobListener getJobListener(String name) { + return sched.getJobListener(name); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void addGlobalTriggerListener(TriggerListener triggerListener) { + sched.addGlobalTriggerListener(triggerListener); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void addTriggerListener(TriggerListener triggerListener) { + sched.addTriggerListener(triggerListener); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean removeGlobalTriggerListener(TriggerListener triggerListener) { + return sched.removeGlobalTriggerListener(triggerListener); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean removeTriggerListener(String name) { + return sched.removeTriggerListener(name); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public List getGlobalTriggerListeners() { + return sched.getGlobalTriggerListeners(); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public Set getTriggerListenerNames() { + return sched.getTriggerListenerNames(); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public TriggerListener getTriggerListener(String name) { + return sched.getTriggerListener(name); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public void addSchedulerListener(SchedulerListener schedulerListener) { + sched.addSchedulerListener(schedulerListener); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public boolean removeSchedulerListener(SchedulerListener schedulerListener) { + return sched.removeSchedulerListener(schedulerListener); + } + + /** + *

+ * Calls the equivalent method on the 'proxied' QuartzScheduler. + *

+ */ + public List getSchedulerListeners() { + return sched.getSchedulerListeners(); + } + + public boolean interrupt(String jobName, String groupName) throws UnableToInterruptJobException { + return sched.interrupt(schedCtxt, jobName, groupName); + } + + /** + * @see org.quartz.Scheduler#setJobFactory(org.quartz.spi.JobFactory) + */ + public void setJobFactory(JobFactory factory) throws SchedulerException { + sched.setJobFactory(factory); + } + +} Index: 3rdParty_sources/quartz/org/quartz/impl/StdSchedulerFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/StdSchedulerFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/StdSchedulerFactory.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,1191 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl; + +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.sql.SQLException; +import java.util.Collection; +import java.util.Iterator; +import java.util.Locale; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.JobListener; +import org.quartz.Scheduler; +import org.quartz.SchedulerConfigException; +import org.quartz.SchedulerException; +import org.quartz.SchedulerFactory; +import org.quartz.TriggerListener; +import org.quartz.core.JobRunShellFactory; +import org.quartz.core.QuartzScheduler; +import org.quartz.core.QuartzSchedulerResources; +import org.quartz.core.SchedulingContext; +import org.quartz.ee.jta.JTAJobRunShellFactory; +import org.quartz.ee.jta.UserTransactionHelper; +import org.quartz.impl.jdbcjobstore.JobStoreSupport; +import org.quartz.simpl.RAMJobStore; +import org.quartz.simpl.SimpleThreadPool; +import org.quartz.spi.ClassLoadHelper; +import org.quartz.spi.InstanceIdGenerator; +import org.quartz.spi.JobFactory; +import org.quartz.spi.JobStore; +import org.quartz.spi.SchedulerPlugin; +import org.quartz.spi.ThreadPool; +import org.quartz.utils.ConnectionProvider; +import org.quartz.utils.DBConnectionManager; +import org.quartz.utils.JNDIConnectionProvider; +import org.quartz.utils.PoolingConnectionProvider; +import org.quartz.utils.PropertiesParser; + +/** + *

+ * An implementation of {@link org.quartz.SchedulerFactory} that + * does all of it's work of creating a QuartzScheduler instance + * based on the contenents of a Properties file. + *

+ * + *

+ * By default a properties file named "quartz.properties" is loaded from the + * 'current working directory'. If that fails, then the "quartz.properties" + * file located (as a resource) in the org/quartz package is loaded. If you + * wish to use a file other than these defaults, you must define the system + * property 'org.quartz.properties' to* point to the file you want. + *

+ * + *

+ * See the sample properties files that are distributed with Quartz for + * information about the various settings available within the file. + *

+ * + *

+ * Alternativly, you can explicitly initialize the factory by calling one of + * the initialize(xx) methods before calling getScheduler(). + *

+ * + *

+ * Instances of the specified {@link org.quartz.spi.JobStore}, + * {@link org.quartz.spi.ThreadPool}, classes will be created + * by name, and then any additional properties specified for them in the config + * file will be set on the instance by calling an equivalent 'set' method. For + * example if the properties file contains the property 'org.quartz.jobStore. + * myProp = 10' then after the JobStore class has been instantiated, the method + * 'setMyProp()' will be called on it. Type conversion to primitive Java types + * (int, long, float, double, boolean, and String) are performed before calling + * the propertie's setter method. + *

+ * + * @author James House + * @author Anthony Eden + * @author Mohammad Rezaei + */ +public class StdSchedulerFactory implements SchedulerFactory { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static final String PROPERTIES_FILE = "org.quartz.properties"; + + public static final String PROP_SCHED_INSTANCE_NAME = "org.quartz.scheduler.instanceName"; + + public static final String PROP_SCHED_INSTANCE_ID = "org.quartz.scheduler.instanceId"; + + public static final String PROP_SCHED_INSTANCE_ID_GENERATOR_CLASS = "org.quartz.scheduler.instanceIdGenerator.class"; + + public static final String PROP_SCHED_THREAD_NAME = "org.quartz.scheduler.threadName"; + + public static final String PROP_SCHED_RMI_EXPORT = "org.quartz.scheduler.rmi.export"; + + public static final String PROP_SCHED_RMI_PROXY = "org.quartz.scheduler.rmi.proxy"; + + public static final String PROP_SCHED_RMI_HOST = "org.quartz.scheduler.rmi.registryHost"; + + public static final String PROP_SCHED_RMI_PORT = "org.quartz.scheduler.rmi.registryPort"; + + public static final String PROP_SCHED_RMI_SERVER_PORT = "org.quartz.scheduler.rmi.serverPort"; + + public static final String PROP_SCHED_RMI_CREATE_REGISTRY = "org.quartz.scheduler.rmi.createRegistry"; + + public static final String PROP_SCHED_WRAP_JOB_IN_USER_TX = "org.quartz.scheduler.wrapJobExecutionInUserTransaction"; + + public static final String PROP_SCHED_USER_TX_URL = "org.quartz.scheduler.userTransactionURL"; + + public static final String PROP_SCHED_IDLE_WAIT_TIME = "org.quartz.scheduler.idleWaitTime"; + + public static final String PROP_SCHED_DB_FAILURE_RETRY_INTERVAL = "org.quartz.scheduler.dbFailureRetryInterval"; + + public static final String PROP_SCHED_CLASS_LOAD_HELPER_CLASS = "org.quartz.scheduler.classLoadHelper.class"; + + public static final String PROP_SCHED_JOB_FACTORY_CLASS = "org.quartz.scheduler.jobFactory.class"; + + public static final String PROP_SCHED_JOB_FACTORY_PREFIX = "org.quartz.scheduler.jobFactory"; + + public static final String PROP_SCHED_CONTEXT_PREFIX = "org.quartz.context.key"; + + public static final String PROP_THREAD_POOL_PREFIX = "org.quartz.threadPool"; + + public static final String PROP_THREAD_POOL_CLASS = "org.quartz.threadPool.class"; + + public static final String PROP_JOB_STORE_PREFIX = "org.quartz.jobStore"; + + public static final String PROP_JOB_STORE_CLASS = "org.quartz.jobStore.class"; + + public static final String PROP_JOB_STORE_USE_PROP = "org.quartz.jobStore.useProperties"; + + public static final String PROP_DATASOURCE_PREFIX = "org.quartz.dataSource"; + + public static final String PROP_CONNECTION_PROVIDER_CLASS = "connectionProvider.class"; + + public static final String PROP_DATASOURCE_DRIVER = "driver"; + + public static final String PROP_DATASOURCE_URL = "URL"; + + public static final String PROP_DATASOURCE_USER = "user"; + + public static final String PROP_DATASOURCE_PASSWORD = "password"; + + public static final String PROP_DATASOURCE_MAX_CONNECTIONS = "maxConnections"; + + public static final String PROP_DATASOURCE_VALIDATION_QUERY = "validationQuery"; + + public static final String PROP_DATASOURCE_JNDI_URL = "jndiURL"; + + public static final String PROP_DATASOURCE_JNDI_ALWAYS_LOOKUP = "jndiAlwaysLookup"; + + public static final String PROP_DATASOURCE_JNDI_INITIAL = "java.naming.factory.initial"; + + public static final String PROP_DATASOURCE_JNDI_PROVDER = "java.naming.provider.url"; + + public static final String PROP_DATASOURCE_JNDI_PRINCIPAL = "java.naming.security.principal"; + + public static final String PROP_DATASOURCE_JNDI_CREDENTIALS = "java.naming.security.credentials"; + + public static final String PROP_PLUGIN_PREFIX = "org.quartz.plugin"; + + public static final String PROP_PLUGIN_CLASS = "class"; + + public static final String PROP_JOB_LISTENER_PREFIX = "org.quartz.jobListener"; + + public static final String PROP_TRIGGER_LISTENER_PREFIX = "org.quartz.triggerListener"; + + public static final String PROP_LISTENER_CLASS = "class"; + + public static final String DEFAULT_INSTANCE_ID = "NON_CLUSTERED"; + + public static final String AUTO_GENERATE_INSTANCE_ID = "AUTO"; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private SchedulerException initException = null; + + private String propSrc = null; + + private PropertiesParser cfg; + + // private Scheduler scheduler; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public StdSchedulerFactory() { + } + + public StdSchedulerFactory(Properties props) throws SchedulerException { + initialize(props); + } + + public StdSchedulerFactory(String fileName) throws SchedulerException { + initialize(fileName); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static Log getLog() { + return LogFactory.getLog(StdSchedulerFactory.class); + } + + /** + *

+ * Initialize the {@link org.quartz.SchedulerFactory} with + * the contenents of a Properties file. + *

+ * + *

+ * By default a properties file named "quartz.properties" is loaded from + * the 'current working directory'. If that fails, then the + * "quartz.properties" file located (as a resource) in the org/quartz + * package is loaded. If you wish to use a file other than these defaults, + * you must define the system property 'org.quartz.properties' to point to + * the file you want. + *

+ * + *

+ * System properties (envrionment variables, and -D definitions on the + * command-line when running the JVM) over-ride any properties in the + * loaded file. + *

+ */ + public void initialize() throws SchedulerException { + // short-circuit if already initialized + if (cfg != null) return; + if (initException != null) throw initException; + + String requestedFile = System.getProperty(PROPERTIES_FILE); + String propFileName = requestedFile != null ? requestedFile + : "quartz.properties"; + File propFile = new File(propFileName); + + Properties props = new Properties(); + + if (propFile.exists()) { + try { + if (requestedFile != null) propSrc = "specified file: '" + + requestedFile + "'"; + else + propSrc = "default file in current working dir: 'quartz.properties'"; + + props.load(new BufferedInputStream(new FileInputStream( + propFileName))); + + initialize(overRideWithSysProps(props)); + } catch (IOException ioe) { + initException = new SchedulerException("Properties file: '" + + propFileName + "' could not be read.", ioe); + throw initException; + } + } else if (requestedFile != null) { + InputStream in = + Thread.currentThread().getContextClassLoader().getResourceAsStream(requestedFile); + + if(in == null) { + initException = new SchedulerException("Properties file: '" + + requestedFile + "' could not be found."); + throw initException; + } + + propSrc = "specified file: '" + requestedFile + "' in the class resource path."; + + try { + props.load(new BufferedInputStream(in)); + initialize(overRideWithSysProps(props)); + } catch (IOException ioe) { + initException = new SchedulerException("Properties file: '" + + requestedFile + "' could not be read.", ioe); + throw initException; + } + + } else { + propSrc = "default resource file in Quartz package: 'quartz.properties'"; + + InputStream in = getClass().getClassLoader().getResourceAsStream( + "quartz.properties"); + + if (in == null) + in = getClass().getClassLoader().getResourceAsStream( + "/quartz.properties"); + if (in == null) + in = getClass().getClassLoader().getResourceAsStream( + "org/quartz/quartz.properties"); + if (in == null) { + initException = new SchedulerException( + "Default quartz.properties not found in class path"); + throw initException; + } + try { + props.load(in); + } catch (IOException ioe) { + initException = new SchedulerException( + "Resource properties file: 'org/quartz/quartz.properties' " + + "could not be read from the classpath.", ioe); + throw initException; + } + + initialize(overRideWithSysProps(props)); + } + } + + private Properties overRideWithSysProps(Properties props) { + + Properties sysProps = System.getProperties(); + props.putAll(sysProps); + + return props; + } + + /** + *

+ * Initialize the {@link org.quartz.SchedulerFactory} with + * the contenents of the Properties file with the given + * name. + *

+ */ + public void initialize(String filename) throws SchedulerException { + // short-circuit if already initialized + if (cfg != null) return; + if (initException != null) throw initException; + + InputStream is = null; + Properties props = new Properties(); + + is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename); + + try { + if(is != null) { + is = new BufferedInputStream(is); + propSrc = "the specified file : '" + filename + "' from the class resource path."; + } + else { + is = new BufferedInputStream(new FileInputStream(filename)); + propSrc = "the specified file : '" + filename + "'"; + } + props.load(is); + } catch (IOException ioe) { + initException = new SchedulerException("Properties file: '" + + filename + "' could not be read.", ioe); + throw initException; + } + + initialize(props); + } + + /** + *

+ * Initialize the {@link org.quartz.SchedulerFactory} with + * the contenents of the Properties file opened with the + * given InputStream. + *

+ */ + public void initialize(InputStream propertiesStream) + throws SchedulerException { + // short-circuit if already initialized + if (cfg != null) return; + if (initException != null) throw initException; + + Properties props = new Properties(); + + if (propertiesStream != null) { + try { + props.load(propertiesStream); + propSrc = "an externally opened InputStream."; + } catch (IOException e) { + initException = new SchedulerException( + "Error loading property data from InputStream", e); + throw initException; + } + } else { + initException = new SchedulerException( + "Error loading property data from InputStream - InputStream is null."); + throw initException; + } + + initialize(props); + } + + /** + *

+ * Initialize the {@link org.quartz.SchedulerFactory} with + * the contenents of the given Properties object. + *

+ */ + public void initialize(Properties props) throws SchedulerException { + if (propSrc == null) + propSrc = "an externally provided properties instance."; + + this.cfg = new PropertiesParser(props); + } + + /** + * + */ + private Scheduler instantiate() throws SchedulerException { + if (cfg == null) initialize(); + + if (initException != null) throw initException; + + JobStore js = null; + ThreadPool tp = null; + QuartzScheduler qs = null; + SchedulingContext schedCtxt = null; + DBConnectionManager dbMgr = null; + String instanceIdGeneratorClass = null; + Properties tProps = null; + String userTXLocation = null; + boolean wrapJobInTx = false; + boolean autoId = false; + long idleWaitTime = -1; + long dbFailureRetry = -1; + String classLoadHelperClass; + String jobFactoryClass; + + SchedulerRepository schedRep = SchedulerRepository.getInstance(); + + // Get Scheduler Properties + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + String schedName = cfg.getStringProperty(PROP_SCHED_INSTANCE_NAME, + "QuartzScheduler"); + + String threadName = cfg.getStringProperty(PROP_SCHED_THREAD_NAME, + schedName + "_QuartzSchedulerThread"); + + String schedInstId = cfg.getStringProperty(PROP_SCHED_INSTANCE_ID, + DEFAULT_INSTANCE_ID); + + if (schedInstId.equals(AUTO_GENERATE_INSTANCE_ID)) { + autoId = true; + instanceIdGeneratorClass = cfg.getStringProperty( + PROP_SCHED_INSTANCE_ID_GENERATOR_CLASS, + "org.quartz.simpl.SimpleInstanceIdGenerator"); + } + + userTXLocation = cfg.getStringProperty(PROP_SCHED_USER_TX_URL, + userTXLocation); + if (userTXLocation != null && userTXLocation.trim().length() == 0) + userTXLocation = null; + + classLoadHelperClass = cfg.getStringProperty( + PROP_SCHED_CLASS_LOAD_HELPER_CLASS, + "org.quartz.simpl.CascadingClassLoadHelper"); + wrapJobInTx = cfg.getBooleanProperty(PROP_SCHED_WRAP_JOB_IN_USER_TX, + wrapJobInTx); + + jobFactoryClass = cfg.getStringProperty( + PROP_SCHED_JOB_FACTORY_CLASS, null); + + idleWaitTime = cfg.getLongProperty(PROP_SCHED_IDLE_WAIT_TIME, + idleWaitTime); + dbFailureRetry = cfg.getLongProperty( + PROP_SCHED_DB_FAILURE_RETRY_INTERVAL, dbFailureRetry); + + boolean rmiExport = cfg + .getBooleanProperty(PROP_SCHED_RMI_EXPORT, false); + boolean rmiProxy = cfg.getBooleanProperty(PROP_SCHED_RMI_PROXY, false); + String rmiHost = cfg + .getStringProperty(PROP_SCHED_RMI_HOST, "localhost"); + int rmiPort = cfg.getIntProperty(PROP_SCHED_RMI_PORT, 1099); + int rmiServerPort = cfg.getIntProperty(PROP_SCHED_RMI_SERVER_PORT, -1); + String rmiCreateRegistry = cfg.getStringProperty( + PROP_SCHED_RMI_CREATE_REGISTRY, + QuartzSchedulerResources.CREATE_REGISTRY_NEVER); + + Properties schedCtxtProps = cfg.getPropertyGroup(PROP_SCHED_CONTEXT_PREFIX, true); + + // If Proxying to remote scheduler, short-circuit here... + // ~~~~~~~~~~~~~~~~~~ + if (rmiProxy) { + + if (autoId) + schedInstId = DEFAULT_INSTANCE_ID; + + schedCtxt = new SchedulingContext(); + schedCtxt.setInstanceId(schedInstId); + + String uid = QuartzSchedulerResources.getUniqueIdentifier( + schedName, schedInstId); + + RemoteScheduler remoteScheduler = new RemoteScheduler(schedCtxt, + uid, rmiHost, rmiPort); + + schedRep.bind(remoteScheduler); + + return remoteScheduler; + } + + // Create class load helper + ClassLoadHelper loadHelper = null; + try { + loadHelper = (ClassLoadHelper) loadClass(classLoadHelperClass) + .newInstance(); + } catch (Exception e) { + throw new SchedulerConfigException( + "Unable to instantiate class load helper class: " + + e.getMessage(), e); + } + loadHelper.initialize(); + + JobFactory jobFactory = null; + if(jobFactoryClass != null) { + try { + jobFactory = (JobFactory) loadHelper.loadClass(jobFactoryClass) + .newInstance(); + } catch (Exception e) { + throw new SchedulerConfigException( + "Unable to instantiate JobFactory class: " + + e.getMessage(), e); + } + + tProps = cfg.getPropertyGroup(PROP_SCHED_JOB_FACTORY_PREFIX, true); + try { + setBeanProps(jobFactory, tProps); + } catch (Exception e) { + initException = new SchedulerException("JobFactory class '" + + jobFactoryClass + "' props could not be configured.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + } + + InstanceIdGenerator instanceIdGenerator = null; + if(instanceIdGeneratorClass != null) { + try { + instanceIdGenerator = (InstanceIdGenerator) loadHelper.loadClass(instanceIdGeneratorClass) + .newInstance(); + } catch (Exception e) { + throw new SchedulerConfigException( + "Unable to instantiate InstanceIdGenerator class: " + + e.getMessage(), e); + } + } + + // Get ThreadPool Properties + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + String tpClass = cfg.getStringProperty(PROP_THREAD_POOL_CLASS, null); + + if (tpClass == null) { + initException = new SchedulerException( + "ThreadPool class not specified. ", + SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + + try { + tp = (ThreadPool) loadHelper.loadClass(tpClass).newInstance(); + } catch (Exception e) { + initException = new SchedulerException("ThreadPool class '" + + tpClass + "' could not be instantiated.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + tProps = cfg.getPropertyGroup(PROP_THREAD_POOL_PREFIX, true); + try { + setBeanProps(tp, tProps); + } catch (Exception e) { + initException = new SchedulerException("ThreadPool class '" + + tpClass + "' props could not be configured.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + + // Get JobStore Properties + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + String jsClass = cfg.getStringProperty(PROP_JOB_STORE_CLASS, + RAMJobStore.class.getName()); + + if (jsClass == null) { + initException = new SchedulerException( + "JobStore class not specified. ", + SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + + try { + js = (JobStore) loadHelper.loadClass(jsClass).newInstance(); + } catch (Exception e) { + initException = new SchedulerException("JobStore class '" + jsClass + + "' could not be instantiated.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + tProps = cfg.getPropertyGroup(PROP_JOB_STORE_PREFIX, true); + try { + setBeanProps(js, tProps); + } catch (Exception e) { + initException = new SchedulerException("JobStore class '" + jsClass + + "' props could not be configured.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + + if (js instanceof org.quartz.impl.jdbcjobstore.JobStoreSupport) { + ((org.quartz.impl.jdbcjobstore.JobStoreSupport) js) + .setInstanceId(schedInstId); + ((org.quartz.impl.jdbcjobstore.JobStoreSupport) js) + .setInstanceName(schedName); + } + + // Set up any DataSources + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + String[] dsNames = cfg.getPropertyGroups(PROP_DATASOURCE_PREFIX); + for (int i = 0; i < dsNames.length; i++) { + PropertiesParser pp = new PropertiesParser(cfg.getPropertyGroup( + PROP_DATASOURCE_PREFIX + "." + dsNames[i], true)); + + String cpClass = pp.getStringProperty(PROP_CONNECTION_PROVIDER_CLASS, null); + + // custom connectionProvider... + if(cpClass != null) { + ConnectionProvider cp = null; + try { + cp = (ConnectionProvider) loadHelper.loadClass(cpClass).newInstance(); + } catch (Exception e) { + initException = new SchedulerException("ConnectionProvider class '" + cpClass + + "' could not be instantiated.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + + try { + // remove the class name, so it isn't attempted to be set + pp.getUnderlyingProperties().remove( + PROP_CONNECTION_PROVIDER_CLASS); + + setBeanProps(cp, pp.getUnderlyingProperties()); + } catch (Exception e) { + initException = new SchedulerException("ConnectionProvider class '" + cpClass + + "' props could not be configured.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + + dbMgr = DBConnectionManager.getInstance(); + dbMgr.addConnectionProvider(dsNames[i], cp); + } + else { + String dsDriver = pp + .getStringProperty(PROP_DATASOURCE_DRIVER, null); + String dsURL = pp.getStringProperty(PROP_DATASOURCE_URL, null); + boolean dsAlwaysLookup = pp.getBooleanProperty( + PROP_DATASOURCE_JNDI_ALWAYS_LOOKUP, false); + String dsUser = pp.getStringProperty(PROP_DATASOURCE_USER, ""); + String dsPass = pp.getStringProperty(PROP_DATASOURCE_PASSWORD, ""); + int dsCnt = pp.getIntProperty(PROP_DATASOURCE_MAX_CONNECTIONS, 10); + String dsJndi = pp + .getStringProperty(PROP_DATASOURCE_JNDI_URL, null); + String dsJndiInitial = pp.getStringProperty( + PROP_DATASOURCE_JNDI_INITIAL, null); + String dsJndiProvider = pp.getStringProperty( + PROP_DATASOURCE_JNDI_PROVDER, null); + String dsJndiPrincipal = pp.getStringProperty( + PROP_DATASOURCE_JNDI_PRINCIPAL, null); + String dsJndiCredentials = pp.getStringProperty( + PROP_DATASOURCE_JNDI_CREDENTIALS, null); + String dsValidation = pp.getStringProperty( + PROP_DATASOURCE_VALIDATION_QUERY, null); + + if (dsJndi != null) { + Properties props = null; + if (null != dsJndiInitial || null != dsJndiProvider + || null != dsJndiPrincipal || null != dsJndiCredentials) { + props = new Properties(); + if (dsJndiInitial != null) + props.put(PROP_DATASOURCE_JNDI_INITIAL, + dsJndiInitial); + if (dsJndiProvider != null) + props.put(PROP_DATASOURCE_JNDI_PROVDER, + dsJndiProvider); + if (dsJndiPrincipal != null) + props.put(PROP_DATASOURCE_JNDI_PRINCIPAL, + dsJndiPrincipal); + if (dsJndiCredentials != null) + props.put(PROP_DATASOURCE_JNDI_CREDENTIALS, + dsJndiCredentials); + } + JNDIConnectionProvider cp = new JNDIConnectionProvider(dsJndi, + props, dsAlwaysLookup); + dbMgr = DBConnectionManager.getInstance(); + dbMgr.addConnectionProvider(dsNames[i], cp); + } else { + if (dsDriver == null) { + initException = new SchedulerException( + "Driver not specified for DataSource: " + + dsNames[i]); + throw initException; + } + if (dsURL == null) { + initException = new SchedulerException( + "DB URL not specified for DataSource: " + + dsNames[i]); + throw initException; + } + try { + PoolingConnectionProvider cp = new PoolingConnectionProvider( + dsDriver, dsURL, dsUser, dsPass, dsCnt, + dsValidation); + dbMgr = DBConnectionManager.getInstance(); + dbMgr.addConnectionProvider(dsNames[i], cp); + } catch (SQLException sqle) { + initException = new SchedulerException( + "Could not initialize DataSource: " + dsNames[i], + sqle); + throw initException; + } + } + + } + + } + + // Set up any SchedulerPlugins + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + String[] pluginNames = cfg.getPropertyGroups(PROP_PLUGIN_PREFIX); + SchedulerPlugin[] plugins = new SchedulerPlugin[pluginNames.length]; + for (int i = 0; i < pluginNames.length; i++) { + Properties pp = cfg.getPropertyGroup(PROP_PLUGIN_PREFIX + "." + + pluginNames[i], true); + + String plugInClass = pp.getProperty(PROP_PLUGIN_CLASS, null); + + if (plugInClass == null) { + initException = new SchedulerException( + "SchedulerPlugin class not specified for plugin '" + + pluginNames[i] + "'", + SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + SchedulerPlugin plugin = null; + try { + plugin = (SchedulerPlugin) + loadHelper.loadClass(plugInClass).newInstance(); + } catch (Exception e) { + initException = new SchedulerException( + "SchedulerPlugin class '" + plugInClass + + "' could not be instantiated.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + try { + setBeanProps(plugin, pp); + } catch (Exception e) { + initException = new SchedulerException( + "JobStore SchedulerPlugin '" + plugInClass + + "' props could not be configured.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + plugins[i] = plugin; + } + + // Set up any JobListeners + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Class[] strArg = new Class[] { String.class }; + String[] jobListenerNames = cfg.getPropertyGroups(PROP_JOB_LISTENER_PREFIX); + JobListener[] jobListeners = new JobListener[jobListenerNames.length]; + for (int i = 0; i < jobListenerNames.length; i++) { + Properties lp = cfg.getPropertyGroup(PROP_JOB_LISTENER_PREFIX + "." + + jobListenerNames[i], true); + + String listenerClass = lp.getProperty(PROP_LISTENER_CLASS, null); + + if (listenerClass == null) { + initException = new SchedulerException( + "JobListener class not specified for listener '" + + jobListenerNames[i] + "'", + SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + JobListener listener = null; + try { + listener = (JobListener) + loadHelper.loadClass(listenerClass).newInstance(); + } catch (Exception e) { + initException = new SchedulerException( + "JobListener class '" + listenerClass + + "' could not be instantiated.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + try { + Method nameSetter = listener.getClass().getMethod("setName", strArg); + if(nameSetter != null) + nameSetter.invoke(listener, new Object[] {jobListenerNames[i] } ); + setBeanProps(listener, lp); + } catch (Exception e) { + initException = new SchedulerException( + "JobListener '" + listenerClass + + "' props could not be configured.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + jobListeners[i] = listener; + } + + // Set up any TriggerListeners + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + String[] triggerListenerNames = cfg.getPropertyGroups(PROP_TRIGGER_LISTENER_PREFIX); + TriggerListener[] triggerListeners = new TriggerListener[triggerListenerNames.length]; + for (int i = 0; i < triggerListenerNames.length; i++) { + Properties lp = cfg.getPropertyGroup(PROP_TRIGGER_LISTENER_PREFIX + "." + + triggerListenerNames[i], true); + + String listenerClass = lp.getProperty(PROP_LISTENER_CLASS, null); + + if (listenerClass == null) { + initException = new SchedulerException( + "TriggerListener class not specified for listener '" + + triggerListenerNames[i] + "'", + SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + TriggerListener listener = null; + try { + listener = (TriggerListener) + loadHelper.loadClass(listenerClass).newInstance(); + } catch (Exception e) { + initException = new SchedulerException( + "TriggerListener class '" + listenerClass + + "' could not be instantiated.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + try { + Method nameSetter = listener.getClass().getMethod("setName", strArg); + if(nameSetter != null) + nameSetter.invoke(listener, new Object[] {triggerListenerNames[i] } ); + setBeanProps(listener, lp); + } catch (Exception e) { + initException = new SchedulerException( + "TriggerListener '" + listenerClass + + "' props could not be configured.", e); + initException + .setErrorCode(SchedulerException.ERR_BAD_CONFIGURATION); + throw initException; + } + triggerListeners[i] = listener; + } + + + // Fire everything up + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + JobRunShellFactory jrsf = null; // Create correct run-shell factory... + UserTransactionHelper userTxHelper = null; + + if (wrapJobInTx) + userTxHelper = new UserTransactionHelper(userTXLocation); + + if (wrapJobInTx) jrsf = new JTAJobRunShellFactory(userTxHelper); + else + jrsf = new StdJobRunShellFactory(); + + if (autoId) { + try { + schedInstId = DEFAULT_INSTANCE_ID; + if (js instanceof org.quartz.impl.jdbcjobstore.JobStoreSupport) { + if(((org.quartz.impl.jdbcjobstore.JobStoreSupport) js) + .isClustered()) { + schedInstId = instanceIdGenerator.generateInstanceId(); + } + } + } catch (Exception e) { + getLog().error("Couldn't generate instance Id!", e); + throw new IllegalStateException( + "Cannot run without an instance id."); + } + } + + if (js instanceof JobStoreSupport) { + JobStoreSupport jjs = (JobStoreSupport) js; + jjs.setInstanceId(schedInstId); + jjs.setDbRetryInterval(dbFailureRetry); + } + + QuartzSchedulerResources rsrcs = new QuartzSchedulerResources(); + rsrcs.setName(schedName); + rsrcs.setThreadName(threadName); + rsrcs.setInstanceId(schedInstId); + rsrcs.setJobRunShellFactory(jrsf); + + if (rmiExport) { + rsrcs.setRMIRegistryHost(rmiHost); + rsrcs.setRMIRegistryPort(rmiPort); + rsrcs.setRMIServerPort(rmiServerPort); + rsrcs.setRMICreateRegistryStrategy(rmiCreateRegistry); + } + + rsrcs.setThreadPool(tp); + if(tp instanceof SimpleThreadPool) + ((SimpleThreadPool)tp).setThreadNamePrefix(schedName + "_Worker"); + tp.initialize(); + + rsrcs.setJobStore(js); + + schedCtxt = new SchedulingContext(); + schedCtxt.setInstanceId(rsrcs.getInstanceId()); + + qs = new QuartzScheduler(rsrcs, schedCtxt, idleWaitTime, dbFailureRetry); + + // if(usingJSCMT) + // qs.setSignalOnSchedulingChange(false); // TODO: fixed? (don't need + // this any more?) + + // Create Scheduler ref... + Scheduler scheduler = instantiate(rsrcs, qs); + + // set job factory if specified + if(jobFactory != null) + qs.setJobFactory(jobFactory); + + // add plugins + for (int i = 0; i < plugins.length; i++) { + plugins[i].initialize(pluginNames[i], scheduler); + qs.addSchedulerPlugin(plugins[i]); + } + + // add listeners + for (int i = 0; i < jobListeners.length; i++) { + qs.addGlobalJobListener(jobListeners[i]); + } + for (int i = 0; i < triggerListeners.length; i++) { + qs.addGlobalTriggerListener(triggerListeners[i]); + } + + // set scheduler context data... + Iterator itr = schedCtxtProps.keySet().iterator(); + while(itr.hasNext()) { + String key = (String) itr.next(); + String val = schedCtxtProps.getProperty(key); + + scheduler.getContext().put(key, val); + } + + // fire up job store, and runshell factory + + js.initialize(loadHelper, qs.getSchedulerSignaler()); + + jrsf.initialize(scheduler, schedCtxt); + + getLog().info( + "Quartz scheduler '" + scheduler.getSchedulerName() + + "' initialized from " + propSrc); + + getLog().info("Quartz scheduler version: " + qs.getVersion()); + + // prevents the repository from being garbage collected + qs.addNoGCObject(schedRep); + // prevents the db manager from being garbage collected + if (dbMgr != null) qs.addNoGCObject(dbMgr); + + schedRep.bind(scheduler); + + return scheduler; + } + + protected Scheduler instantiate(QuartzSchedulerResources rsrcs, QuartzScheduler qs) { + SchedulingContext schedCtxt = new SchedulingContext(); + schedCtxt.setInstanceId(rsrcs.getInstanceId()); + + Scheduler scheduler = new StdScheduler(qs, schedCtxt); + return scheduler; + } + + + private void setBeanProps(Object obj, Properties props) + throws NoSuchMethodException, IllegalAccessException, + java.lang.reflect.InvocationTargetException, + IntrospectionException, SchedulerConfigException { + props.remove("class"); + + BeanInfo bi = Introspector.getBeanInfo(obj.getClass()); + PropertyDescriptor[] propDescs = bi.getPropertyDescriptors(); + PropertiesParser pp = new PropertiesParser(props); + + java.util.Enumeration keys = props.keys(); + while (keys.hasMoreElements()) { + String name = (String) keys.nextElement(); + String c = name.substring(0, 1).toUpperCase(Locale.US); + String methName = "set" + c + name.substring(1); + + java.lang.reflect.Method setMeth = getSetMethod(methName, propDescs); + + try { + if (setMeth == null) + throw new NoSuchMethodException( + "No setter for property '" + name + "'"); + + Class[] params = setMeth.getParameterTypes(); + if (params.length != 1) + throw new NoSuchMethodException( + "No 1-argument setter for property '" + name + + "'"); + + if (params[0].equals(int.class)) { + setMeth.invoke(obj, new Object[]{new Integer(pp + .getIntProperty(name))}); + } else if (params[0].equals(long.class)) { + setMeth.invoke(obj, new Object[]{new Long(pp + .getLongProperty(name))}); + } else if (params[0].equals(float.class)) { + setMeth.invoke(obj, new Object[]{new Float(pp + .getFloatProperty(name))}); + } else if (params[0].equals(double.class)) { + setMeth.invoke(obj, new Object[]{new Double(pp + .getDoubleProperty(name))}); + } else if (params[0].equals(boolean.class)) { + setMeth.invoke(obj, new Object[]{new Boolean(pp + .getBooleanProperty(name))}); + } else if (params[0].equals(String.class)) { + setMeth.invoke(obj, + new Object[]{pp.getStringProperty(name)}); + } else + throw new NoSuchMethodException( + "No primitive-type setter for property '" + name + + "'"); + } catch (NumberFormatException nfe) { + throw new SchedulerConfigException("Could not parse property '" + + name + "' into correct data type: " + nfe.toString()); + } + } + } + + private java.lang.reflect.Method getSetMethod(String name, + PropertyDescriptor[] props) { + for (int i = 0; i < props.length; i++) { + java.lang.reflect.Method wMeth = props[i].getWriteMethod(); + + if (wMeth != null && wMeth.getName().equals(name)) return wMeth; + } + + return null; + } + + private Class loadClass(String className) throws ClassNotFoundException { + + try { + return Thread.currentThread().getContextClassLoader().loadClass( + className); + } catch (ClassNotFoundException e) { + return getClass().getClassLoader().loadClass(className); + } + } + + private String getSchedulerName() { + return cfg.getStringProperty(PROP_SCHED_INSTANCE_NAME, + "QuartzScheduler"); + } + + private String getSchedulerInstId() { + return cfg.getStringProperty(PROP_SCHED_INSTANCE_ID, + DEFAULT_INSTANCE_ID); + } + + /** + *

+ * Returns a handle to the Scheduler produced by this factory. + *

+ * + *

+ * If one of the initialize methods has not be previously + * called, then the default (no-arg) initialize() method + * will be called by this method. + *

+ */ + public Scheduler getScheduler() throws SchedulerException { + if (cfg == null) initialize(); + + SchedulerRepository schedRep = SchedulerRepository.getInstance(); + + Scheduler sched = schedRep.lookup(getSchedulerName()); + + if (sched != null) { + if (sched.isShutdown()) schedRep.remove(getSchedulerName()); + else + return sched; + } + + sched = instantiate(); + + return sched; + } + + /** + *

+ * Returns a handle to the default Scheduler, creating it if it does not + * yet exist. + *

+ * + * @see #initialize() + */ + public static Scheduler getDefaultScheduler() throws SchedulerException { + StdSchedulerFactory fact = new StdSchedulerFactory(); + + return fact.getScheduler(); + } + + /** + *

+ * Returns a handle to the Scheduler with the given name, if it exists (if + * it has already been instantiated). + *

+ */ + public Scheduler getScheduler(String schedName) throws SchedulerException { + return SchedulerRepository.getInstance().lookup(schedName); + } + + /** + *

+ * Returns a handle to all known Schedulers (made by any + * StdSchedulerFactory instance.). + *

+ */ + public Collection getAllSchedulers() throws SchedulerException { + return SchedulerRepository.getInstance().lookupAll(); + } + +} Index: 3rdParty_sources/quartz/org/quartz/impl/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/package.html 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,18 @@ + + +Package org.quartz.impl + + +

Contains implementations of the SchedulerFactory, JobStore, ThreadPool, and +other interfaces required by the org.quartz.core.QuartzScheduler.

+ +

Classes in this package may have dependencies on third-party packages.

+ +
+
+
+See the Quartz project + at Open Symphony for more information. + + + Index: 3rdParty_sources/quartz/org/quartz/impl/calendar/AnnualCalendar.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/calendar/AnnualCalendar.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/calendar/AnnualCalendar.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,211 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + * and Juergen Donnerstag (c) 2002, EDS 2002 + */ + +package org.quartz.impl.calendar; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; + +import org.quartz.Calendar; + +/** + *

+ * This implementation of the Calendar excludes a set of days of the year. You + * may use it to exclude bank holidays which are on the same date every year. + *

+ * + * @see org.quartz.Calendar + * @see org.quartz.impl.calendar.BaseCalendar + * + * @author Juergen Donnerstag + */ +public class AnnualCalendar extends BaseCalendar implements Calendar, + Serializable { + + private ArrayList excludeDays = new ArrayList(); + + // true, if excludeDays is sorted + private boolean dataSorted = false; + + /** + *

+ * Constructor + *

+ */ + public AnnualCalendar() { + super(); + } + + /** + *

+ * Constructor + *

+ */ + public AnnualCalendar(Calendar baseCalendar) { + super(baseCalendar); + } + + /** + *

+ * Get the array which defines the exclude-value of each day of month + *

+ */ + public ArrayList getDaysExcluded() { + return excludeDays; + } + + /** + *

+ * Return true, if day is defined to be exluded. + *

+ */ + public boolean isDayExcluded(java.util.Calendar day) { + if (day == null) + throw new IllegalArgumentException( + "Parameter day must not be null"); + + int dmonth = day.get(java.util.Calendar.MONTH); + int dday = day.get(java.util.Calendar.DAY_OF_MONTH); + + if (dataSorted == false) { + Collections.sort(excludeDays, new CalendarComparator()); + dataSorted = true; + } + + Iterator iter = excludeDays.iterator(); + while (iter.hasNext()) { + java.util.Calendar cl = (java.util.Calendar) iter.next(); + + // remember, the list is sorted + if (dmonth < cl.get(java.util.Calendar.MONTH)) return false; + + if (dday != cl.get(java.util.Calendar.DAY_OF_MONTH)) continue; + + if (dmonth != cl.get(java.util.Calendar.MONTH)) continue; + + return true; + } + + return false; + } + + /** + *

+ * Redefine the array of days excluded. The array must of size greater or + * equal 31. + *

+ */ + public void setDaysExcluded(ArrayList days) { + if (days == null) excludeDays = new ArrayList(); + + excludeDays = days; + dataSorted = false; + } + + /** + *

+ * Redefine a certain day to be excluded (true) or included (false). + *

+ */ + public void setDayExcluded(java.util.Calendar day, boolean exclude) { + if (isDayExcluded(day)) return; + + excludeDays.add(day); + dataSorted = false; + } + + /** + *

+ * Determine whether the given time (in milliseconds) is 'included' by the + * Calendar. + *

+ * + *

+ * Note that this Calendar is only has full-day precision. + *

+ */ + public boolean isTimeIncluded(long timeStamp) { + // Test the base calendar first. Only if the base calendar not already + // excludes the time/date, continue evaluating this calendar instance. + if (super.isTimeIncluded(timeStamp) == false) { return false; } + + java.util.Calendar day = getJavaCalendar(timeStamp); + + return !(isDayExcluded(day)); + } + + /** + *

+ * Determine the next time (in milliseconds) that is 'included' by the + * Calendar after the given time. Return the original value if timeStamp is + * included. Return 0 if all days are excluded. + *

+ * + *

+ * Note that this Calendar is only has full-day precision. + *

+ */ + public long getNextIncludedTime(long timeStamp) { + // Call base calendar implementation first + long baseTime = super.getNextIncludedTime(timeStamp); + if ((baseTime > 0) && (baseTime > timeStamp)) timeStamp = baseTime; + + // Get timestamp for 00:00:00 + long newTimeStamp = buildHoliday(timeStamp); + + java.util.Calendar day = getJavaCalendar(newTimeStamp); + if (isDayExcluded(day) == false) return timeStamp; // return the + // original value + + while (isDayExcluded(day) == true) { + day.add(java.util.Calendar.DATE, 1); + } + + return day.getTime().getTime(); + } +} + +class CalendarComparator implements Comparator +{ + + public CalendarComparator() { + + } + + /** + * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) + */ + public int compare(Object arg0, Object arg1) { + java.util.Calendar c1 = (java.util.Calendar) arg0; + java.util.Calendar c2 = (java.util.Calendar) arg1; + + if(c1.before(c2)) + return -1; + else if(c1.after(c2)) + return 1; + else + return 0; + } +} Index: 3rdParty_sources/quartz/org/quartz/impl/calendar/BaseCalendar.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/calendar/BaseCalendar.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/calendar/BaseCalendar.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,201 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + * and Juergen Donnerstag (c) 2002, EDS 2002 + */ + +package org.quartz.impl.calendar; + +import java.io.Serializable; +import java.util.Date; + +import org.quartz.Calendar; + +/** + *

+ * This implementation of the Calendar may be used (you don't have to) as a + * base class for more sophisticated one's. It merely implements the base + * functionality required by each Calendar. + *

+ * + *

+ * Regarded as base functionality is the treatment of base calendars. Base + * calendar allow you to chain (stack) as much calendars as you may need. For + * example to exclude weekends you may use WeeklyCalendar. In order to exclude + * holidays as well you may define a WeeklyCalendar instance to be the base + * calendar for HolidayCalendar instance. + *

+ * + * @see org.quartz.Calendar + * + * @author Juergen Donnerstag + * @author James House + */ +public class BaseCalendar implements Calendar, Serializable { + + //

A optional base calendar.

+ private Calendar baseCalendar; + + private String description; + + /** + *

+ * Default Constructor + *

+ */ + public BaseCalendar() { + } + + /** + *

+ * Constructor + *

+ */ + public BaseCalendar(Calendar baseCalendar) { + setBaseCalendar(baseCalendar); + } + + /** + *

+ * Set a new base calendar or remove the existing one + *

+ */ + public void setBaseCalendar(Calendar baseCalendar) { + this.baseCalendar = baseCalendar; + } + + /** + *

+ * Get the base calendar. Will be null, if not set. + *

+ */ + public Calendar getBaseCalendar() { + return this.baseCalendar; + } + + /** + *

+ * Return the description given to the Calendar instance by + * its creator (if any). + *

+ * + * @return null if no description was set. + */ + public String getDescription() { + return description; + } + + /** + *

+ * Set a description for the Calendar instance - may be + * useful for remembering/displaying the purpose of the calendar, though + * the description has no meaning to Quartz. + *

+ */ + public void setDescription(String description) { + this.description = description; + } + + /** + *

+ * Check if date/time represented by timeStamp is included. If included + * return true. The implementation of BaseCalendar simply calls the base + * calendars isTimeIncluded() method if base calendar is set. + *

+ * + * @see org.quartz.Calendar#isTimeIncluded(long) + */ + public boolean isTimeIncluded(long timeStamp) { + + if (timeStamp <= 0) + throw new IllegalArgumentException( + "timeStamp must be greater 0"); + + if (baseCalendar != null) { + if (baseCalendar.isTimeIncluded(timeStamp) == false) { return false; } + } + + return true; + } + + /** + *

+ * Determine the next time (in milliseconds) that is 'included' by the + * Calendar after the given time. Return the original value if timeStamp is + * included. Return 0 if all days are excluded. + *

+ * + * @see org.quartz.Calendar#getNextIncludedTime(long) + */ + public long getNextIncludedTime(long timeStamp) { + + if (timeStamp <= 0) + throw new IllegalArgumentException( + "timeStamp must be greater 0"); + + if (baseCalendar != null) { return baseCalendar + .getNextIncludedTime(timeStamp); } + + return timeStamp; + } + + /** + *

+ * Utility method. Return the date of excludeDate. The time fraction will + * be reset to 00.00:00. + *

+ */ + static public Date buildHoliday(Date excludedDate) { + java.util.Calendar cl = java.util.Calendar.getInstance(); + java.util.Calendar clEx = java.util.Calendar.getInstance(); + clEx.setTime(excludedDate); + + cl.setLenient(false); + cl.clear(); + cl.set(clEx.get(java.util.Calendar.YEAR), clEx + .get(java.util.Calendar.MONTH), clEx + .get(java.util.Calendar.DATE)); + + return cl.getTime(); + } + + /** + *

+ * Utility method. Return just the date of excludeDate. The time fraction + * will be reset to 00.00:00. + *

+ */ + static public long buildHoliday(long timeStamp) { + return buildHoliday(new Date(timeStamp)).getTime(); + } + + /** + *

+ * Utility method. Return a java.util.Calendar for timeStamp. + *

+ * + * @param timeStamp + * @return Calendar + */ + static public java.util.Calendar getJavaCalendar(long timeStamp) { + java.util.Calendar cl = java.util.Calendar.getInstance(); + cl.setTime(new Date(timeStamp)); + return cl; + } +} Index: 3rdParty_sources/quartz/org/quartz/impl/calendar/CronCalendar.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/calendar/CronCalendar.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/calendar/CronCalendar.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,180 @@ +package org.quartz.impl.calendar; + +import java.text.ParseException; +import java.util.Date; + +import org.quartz.CronExpression; + +/** + * This implementation of the Calendar excludes the set of times expressed by a + * given {@link org.quartz.CronExpression CronExpression}. For example, you + * could use this calendar to exclude all but business hours (8AM - 5PM) every + * day using the expression "* * 0-7,18-24 ? * *". + *

+ * It is important to remember that the cron expression here describes a set of + * times to be excluded from firing. Whereas the cron expression in + * {@link org.quartz.CronTrigger CronTrigger} describes a set of times that can + * be included for firing. Thus, if a CronTrigger has a + * given cron expression and is associated with a CronCalendar with + * the same expression, the calendar will exclude all the times the + * trigger includes, and they will cancel each other out. + * + * @author Aaron Craven + * @version $Revision: 1.1 $ $Date: 2012/08/17 15:10:20 $ + */ +public class CronCalendar extends BaseCalendar { + static final long serialVersionUID = -8172103999750856831L; + + private String name; + CronExpression cronExpression; + + /** + * Create a CronCalendar with the given cron expression and no + * baseCalendar. + * + * @param name the name for the DailyCalendar + * @param expression a String representation of the desired cron expression + */ + public CronCalendar(String name, String expression) + throws ParseException { + super(); + this.name = name; + this.cronExpression = new CronExpression(expression); + } + + /** + * Create a CronCalendar with the given cron exprssion and + * baseCalendar. + * + * @param name the name for the DailyCalendar + * @param baseCalendar the base calendar for this calendar instance – + * see {@link BaseCalendar} for more information on base + * calendar functionality + * @param expression a String representation of the desired cron expression + */ + public CronCalendar(String name, org.quartz.Calendar baseCalendar, + String expression) throws ParseException { + super(baseCalendar); + this.name = name; + this.cronExpression = new CronExpression(expression); + } + + /** + * Returns the name of the CronCalendar + * + * @return the name of the CronCalendar + */ + public String getName() { + return name; + } + + /** + * Determines whether the given time (in milliseconds) is 'included' by the + * BaseCalendar + * + * @param timeInMillis the date/time to test + * @return a boolean indicating whether the specified time is 'included' by + * the CronCalendar + */ + public boolean isTimeIncluded(long timeInMillis) { + if ((getBaseCalendar() != null) && + (getBaseCalendar().isTimeIncluded(timeInMillis) == false)) { + return false; + } + + return (!(cronExpression.isSatisfiedBy(new Date(timeInMillis)))); + } + + /** + * Determines the next time included by the CronCalendar + * after the specified time. + * + * @param timeInMillis the initial date/time after which to find an + * included time + * @return the time in milliseconds representing the next time included + * after the specified time. + */ + public long getNextIncludedTime(long timeInMillis) { + long nextIncludedTime = timeInMillis + 1; //plus on millisecond + + while (!isTimeIncluded(nextIncludedTime)) { + //If the time is in a range excluded by this calendar, we can + // move to the end of the excluded time range and continue testing + // from there. Otherwise, if nextIncludedTime is excluded by the + // baseCalendar, ask it the next time it includes and begin testing + // from there. Failing this, add one millisecond and continue + // testing. + if (cronExpression.isSatisfiedBy(new Date(nextIncludedTime))) { + nextIncludedTime = + cronExpression.getNextValidTimeAfter( + new Date(nextIncludedTime)).getTime(); + } else if ((getBaseCalendar() != null) && + (!getBaseCalendar().isTimeIncluded(nextIncludedTime))){ + nextIncludedTime = + getBaseCalendar().getNextIncludedTime(nextIncludedTime); + } else { + nextIncludedTime++; + } + } + + return nextIncludedTime; + } + + /** + * Returns a string representing the properties of the + * CronCalendar + * + * @return the properteis of the CronCalendar in a String format + */ + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append(getName()); + buffer.append(": base calendar: ["); + if (getBaseCalendar() != null) { + buffer.append(getBaseCalendar().toString()); + } else { + buffer.append("null"); + } + buffer.append("], excluded cron expression: '"); + buffer.append(cronExpression); + buffer.append("'"); + return buffer.toString(); + } + + /** + * Returns the object representation of the cron expression that defines the + * dates and times this calendar excludes. + * + * @return the cron expression + * @see org.quartz.CronExpression + */ + public CronExpression getCronExpression() { + return cronExpression; + } + + /** + * Sets the cron expression for the calendar to a new value + * + * @param expression the new string value to build a cron expression from + * @throws ParseException + * if the string expression cannot be parsed + */ + public void setCronExpression(String expression) throws ParseException { + CronExpression newExp = new CronExpression(expression); + + this.cronExpression = newExp; + } + + /** + * Sets the cron expression for the calendar to a new value + * + * @param expression the new cron expression + */ + public void setCronExpression(CronExpression expression) { + if (expression == null) { + throw new IllegalArgumentException("expression cannot be null"); + } + + this.cronExpression = expression; + } +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/impl/calendar/DailyCalendar.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/calendar/DailyCalendar.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/calendar/DailyCalendar.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,803 @@ +package org.quartz.impl.calendar; + +import java.text.NumberFormat; +import java.util.Calendar; + +/** + * This implementation of the Calendar excludes (or includes - see below) a + * specified time range each day. For example, you could use this calendar to + * exclude business hours (8AM - 5PM) every day. Each DailyCalendar + * only allows a single time range to be specified, and that time range may not + * cross daily boundaries (i.e. you cannot specify a time range from 8PM - 5AM). + * If the property invertTimeRange is false (default), + * the time range defines a range of times in which triggers are not allowed to + * fire. If invertTimeRange is true, the time range + * is inverted – that is, all times outside the defined time range + * are excluded. + *

+ * Note when using DailyCalendar, it behaves on the same principals + * as, for example, {@link org.quartz.impl.calendar.WeeklyCalendar + * WeeklyCalendar}. WeeklyCalendar defines a set of days that are + * excluded every week. Likewise, DailyCalendar defines a + * set of times that are excluded every day. + * + * @author Mike Funk, Aaron Craven + * @version $Revision: 1.1 $ $Date: 2012/08/17 15:10:20 $ + */ +public class DailyCalendar extends BaseCalendar { + private static final String invalidHourOfDay = "Invalid hour of day: "; + private static final String invalidMinute = "Invalid minute: "; + private static final String invalidSecond = "Invalid second: "; + private static final String invalidMillis = "Invalid millis: "; + private static final String invalidTimeRange = "Invalid time range: "; + private static final String separator = " - "; + private static final long oneMillis = 1; + private static final String colon = ":"; + + private String name; + private int rangeStartingHourOfDay; + private int rangeStartingMinute; + private int rangeStartingSecond; + private int rangeStartingMillis; + private int rangeEndingHourOfDay; + private int rangeEndingMinute; + private int rangeEndingSecond; + private int rangeEndingMillis; + + private boolean invertTimeRange = false; + + /** + * Create a DailyCalendar with a time range defined by the + * specified strings and no baseCalendar. + * rangeStartingTime and rangeEndingTime + * must be in the format "HH:MM[:SS[:mmm]]" where: + *

  • HH is the hour of the specified time. The hour should be + * specified using military (24-hour) time and must be in the range + * 0 to 23.
  • + *
  • MM is the minute of the specified time and must be in the range + * 0 to 59.
  • + *
  • SS is the second of the specified time and must be in the range + * 0 to 59.
  • + *
  • mmm is the millisecond of the specified time and must be in the + * range 0 to 999.
  • + *
  • items enclosed in brackets ('[', ']') are optional.
  • + *
  • The time range starting time must be before the time range ending + * time. Note this means that a time range may not cross daily + * boundaries (10PM - 2AM)
  • + *
+ * + * @param name the name for the DailyCalendar + * @param rangeStartingTime a String representing the starting time for the + * time range + * @param rangeEndingTime a String representing the ending time for the + * the time range + */ + public DailyCalendar(String name, + String rangeStartingTime, + String rangeEndingTime) { + super(); + this.name = name; + setTimeRange(rangeStartingTime, rangeEndingTime); + } + + /** + * Create a DailyCalendar with a time range defined by the + * specified strings and the specified baseCalendar. + * rangeStartingTime and rangeEndingTime + * must be in the format "HH:MM[:SS[:mmm]]" where: + *
  • HH is the hour of the specified time. The hour should be + * specified using military (24-hour) time and must be in the range + * 0 to 23.
  • + *
  • MM is the minute of the specified time and must be in the range + * 0 to 59.
  • + *
  • SS is the second of the specified time and must be in the range + * 0 to 59.
  • + *
  • mmm is the millisecond of the specified time and must be in the + * range 0 to 999.
  • + *
  • items enclosed in brackets ('[', ']') are optional.
  • + *
  • The time range starting time must be before the time range ending + * time. Note this means that a time range may not cross daily + * boundaries (10PM - 2AM)
  • + *
+ * + * @param name the name for the DailyCalendar + * @param baseCalendar the base calendar for this calendar instance + * – see {@link BaseCalendar} for more + * information on base calendar functionality + * @param rangeStartingTime a String representing the starting time for the + * time range + * @param rangeEndingTime a String representing the ending time for the + * time range + */ + public DailyCalendar(String name, + org.quartz.Calendar baseCalendar, + String rangeStartingTime, + String rangeEndingTime) { + super(baseCalendar); + this.name = name; + setTimeRange(rangeStartingTime, rangeEndingTime); + } + + /** + * Create a DailyCalendar with a time range defined by the + * specified values and no baseCalendar. Values are subject to + * the following validations: + *
  • Hours must be in the range 0-23 and are expressed using military + * (24-hour) time.
  • + *
  • Minutes must be in the range 0-59
  • + *
  • Seconds must be in the range 0-59
  • + *
  • Milliseconds must be in the range 0-999
  • + *
  • The time range starting time must be before the time range ending + * time. Note this means that a time range may not cross daily + * boundaries (10PM - 2AM)
  • + *
+ * + * @param name the name for the DailyCalendar + * @param rangeStartingHourOfDay the hour of the start of the time range + * @param rangeStartingMinute the minute of the start of the time range + * @param rangeStartingSecond the second of the start of the time range + * @param rangeStartingMillis the millisecond of the start of the time + * range + * @param rangeEndingHourOfDay the hour of the end of the time range + * @param rangeEndingMinute the minute of the end of the time range + * @param rangeEndingSecond the second of the end of the time range + * @param rangeEndingMillis the millisecond of the start of the time + * range + */ + public DailyCalendar(String name, + int rangeStartingHourOfDay, + int rangeStartingMinute, + int rangeStartingSecond, + int rangeStartingMillis, + int rangeEndingHourOfDay, + int rangeEndingMinute, + int rangeEndingSecond, + int rangeEndingMillis) { + super(); + this.name = name; + setTimeRange(rangeStartingHourOfDay, + rangeStartingMinute, + rangeStartingSecond, + rangeStartingMillis, + rangeEndingHourOfDay, + rangeEndingMinute, + rangeEndingSecond, + rangeEndingMillis); + } + + /** + * Create a DailyCalendar with a time range defined by the + * specified values and the specified baseCalendar. Values are + * subject to the following validations: + *
  • Hours must be in the range 0-23 and are expressed using military + * (24-hour) time.
  • + *
  • Minutes must be in the range 0-59
  • + *
  • Seconds must be in the range 0-59
  • + *
  • Milliseconds must be in the range 0-999
  • + *
  • The time range starting time must be before the time range ending + * time. Note this means that a time range may not cross daily + * boundaries (10PM - 2AM)
  • + *
+ * + * @param name the name for the + * DailyCalendar + * @param baseCalendar the base calendar for this calendar + * instance – see + * {@link BaseCalendar} for more + * information on base calendar + * functionality + * @param rangeStartingHourOfDay the hour of the start of the time range + * @param rangeStartingMinute the minute of the start of the time range + * @param rangeStartingSecond the second of the start of the time range + * @param rangeStartingMillis the millisecond of the start of the time + * range + * @param rangeEndingHourOfDay the hour of the end of the time range + * @param rangeEndingMinute the minute of the end of the time range + * @param rangeEndingSecond the second of the end of the time range + * @param rangeEndingMillis the millisecond of the start of the time + * range + */ + public DailyCalendar(String name, + org.quartz.Calendar baseCalendar, + int rangeStartingHourOfDay, + int rangeStartingMinute, + int rangeStartingSecond, + int rangeStartingMillis, + int rangeEndingHourOfDay, + int rangeEndingMinute, + int rangeEndingSecond, + int rangeEndingMillis) { + super(baseCalendar); + this.name = name; + setTimeRange(rangeStartingHourOfDay, + rangeStartingMinute, + rangeStartingSecond, + rangeStartingMillis, + rangeEndingHourOfDay, + rangeEndingMinute, + rangeEndingSecond, + rangeEndingMillis); + } + + /** + * Create a DailyCalendar with a time range defined by the + * specified java.util.Calendars and no + * baseCalendar. The Calendars are subject to the following + * considerations: + *
  • Only the time-of-day fields of the specified Calendars will be + * used (the date fields will be ignored)
  • + *
  • The starting time must be before the ending time of the defined + * time range. Note this means that a time range may not cross + * daily boundaries (10PM - 2AM). (because only time fields are + * are used, it is possible for two Calendars to represent a valid + * time range and + * rangeStartingCalendar.after(rangeEndingCalendar) == + * true)
  • + *
+ * + * @param name the name for the DailyCalendar + * @param rangeStartingCalendar a java.util.Calendar representing the + * starting time for the time range + * @param rangeEndingCalendar a java.util.Calendar representing the ending + * time for the time range + */ + public DailyCalendar(String name, + Calendar rangeStartingCalendar, + Calendar rangeEndingCalendar) { + super(); + this.name = name; + setTimeRange(rangeStartingCalendar, rangeEndingCalendar); + } + + /** + * Create a DailyCalendar with a time range defined by the + * specified java.util.Calendars and the specified + * baseCalendar. The Calendars are subject to the following + * considerations: + *
  • Only the time-of-day fields of the specified Calendars will be + * used (the date fields will be ignored)
  • + *
  • The starting time must be before the ending time of the defined + * time range. Note this means that a time range may not cross + * daily boundaries (10PM - 2AM). (because only time fields are + * are used, it is possible for two Calendars to represent a valid + * time range and + * rangeStartingCalendar.after(rangeEndingCalendar) == + * true)
  • + *
+ * + * @param name the name for the DailyCalendar + * @param baseCalendar the base calendar for this calendar instance + * – see {@link BaseCalendar} for more + * information on base calendar functionality + * @param rangeStartingCalendar a java.util.Calendar representing the + * starting time for the time range + * @param rangeEndingCalendar a java.util.Calendar representing the ending + * time for the time range + */ + public DailyCalendar(String name, + org.quartz.Calendar baseCalendar, + Calendar rangeStartingCalendar, + Calendar rangeEndingCalendar) { + super(baseCalendar); + this.name = name; + setTimeRange(rangeStartingCalendar, rangeEndingCalendar); + } + + /** + * Create a DailyCalendar with a time range defined by the + * specified values and no baseCalendar. The values are + * subject to the following considerations: + *
  • Only the time-of-day portion of the specified values will be + * used
  • + *
  • The starting time must be before the ending time of the defined + * time range. Note this means that a time range may not cross + * daily boundaries (10PM - 2AM). (because only time value are + * are used, it is possible for the two values to represent a valid + * time range and rangeStartingTime > + * rangeEndingTime)
  • + *
+ * + * @param name the name for the + * DailyCalendar + * @param rangeStartingTimeInMillis a long representing the starting time + * for the time range + * @param rangeEndingTimeInMillis a long representing the ending time for + * the time range + */ + public DailyCalendar(String name, + long rangeStartingTimeInMillis, + long rangeEndingTimeInMillis) { + super(); + this.name = name; + setTimeRange(rangeStartingTimeInMillis, + rangeEndingTimeInMillis); + } + + /** + * Create a DailyCalendar with a time range defined by the + * specified values and the specified baseCalendar. The values + * are subject to the following considerations: + *
  • Only the time-of-day portion of the specified values will be + * used
  • + *
  • The starting time must be before the ending time of the defined + * time range. Note this means that a time range may not cross + * daily boundaries (10PM - 2AM). (because only time value are + * are used, it is possible for the two values to represent a valid + * time range and rangeStartingTime > + * rangeEndingTime)
  • + *
+ * + * @param name the name for the + * DailyCalendar + * @param baseCalendar the base calendar for this calendar + * instance – see {@link + * BaseCalendar} for more information on + * base calendar functionality + * @param rangeStartingTimeInMillis a long representing the starting time + * for the time range + * @param rangeEndingTimeInMillis a long representing the ending time for + * the time range + */ + public DailyCalendar(String name, + org.quartz.Calendar baseCalendar, + long rangeStartingTimeInMillis, + long rangeEndingTimeInMillis) { + super(baseCalendar); + this.name = name; + setTimeRange(rangeStartingTimeInMillis, + rangeEndingTimeInMillis); + } + + /** + * Returns the name of the DailyCalendar + * + * @return the name of the DailyCalendar + */ + public String getName() { + return name; + } + + /** + * Determines whether the given time (in milliseconds) is 'included' by the + * BaseCalendar + * + * @param timeInMillis the date/time to test + * @return a boolean indicating whether the specified time is 'included' by + * the BaseCalendar + */ + public boolean isTimeIncluded(long timeInMillis) { + if ((getBaseCalendar() != null) && + (getBaseCalendar().isTimeIncluded(timeInMillis) == false)) { + return false; + } + + long startOfDayInMillis = getStartOfDayInMillis(timeInMillis); + long endOfDayInMillis = getEndOfDayInMillis(timeInMillis); + long timeRangeStartingTimeInMillis = + getTimeRangeStartingTimeInMillis(timeInMillis); + long timeRangeEndingTimeInMillis = + getTimeRangeEndingTimeInMillis(timeInMillis); + if (!invertTimeRange) { + if ((timeInMillis > startOfDayInMillis && + timeInMillis < timeRangeStartingTimeInMillis) || + (timeInMillis > timeRangeEndingTimeInMillis && + timeInMillis < endOfDayInMillis)) { + + return true; + } else { + return false; + } + } else { + if ((timeInMillis >= timeRangeStartingTimeInMillis) && + (timeInMillis <= timeRangeEndingTimeInMillis)) { + return true; + } else { + return false; + } + } + } + + /** + * Determines the next time included by the DailyCalendar + * after the specified time. + * + * @param timeInMillis the initial date/time after which to find an + * included time + * @return the time in milliseconds representing the next time included + * after the specified time. + */ + public long getNextIncludedTime(long timeInMillis) { + long nextIncludedTime = timeInMillis + oneMillis; + + while (!isTimeIncluded(nextIncludedTime)) { + if (!invertTimeRange) { + //If the time is in a range excluded by this calendar, we can + // move to the end of the excluded time range and continue + // testing from there. Otherwise, if nextIncludedTime is + // excluded by the baseCalendar, ask it the next time it + // includes and begin testing from there. Failing this, add one + // millisecond and continue testing. + if ((nextIncludedTime >= + getTimeRangeStartingTimeInMillis(nextIncludedTime)) && + (nextIncludedTime <= + getTimeRangeEndingTimeInMillis(nextIncludedTime))) { + + nextIncludedTime = + getTimeRangeEndingTimeInMillis(nextIncludedTime) + + oneMillis; + } else if ((getBaseCalendar() != null) && + (!getBaseCalendar().isTimeIncluded(nextIncludedTime))){ + nextIncludedTime = + getBaseCalendar().getNextIncludedTime(nextIncludedTime); + } else { + nextIncludedTime++; + } + } else { + //If the time is in a range excluded by this calendar, we can + // move to the end of the excluded time range and continue + // testing from there. Otherwise, if nextIncludedTime is + // excluded by the baseCalendar, ask it the next time it + // includes and begin testing from there. Failing this, add one + // millisecond and continue testing. + if (nextIncludedTime < + getTimeRangeStartingTimeInMillis(nextIncludedTime)) { + nextIncludedTime = + getTimeRangeStartingTimeInMillis(nextIncludedTime); + } else if (nextIncludedTime > + getTimeRangeEndingTimeInMillis(nextIncludedTime)) { + //(move to start of next day) + nextIncludedTime = getEndOfDayInMillis(nextIncludedTime); + nextIncludedTime += 1l; + } else if ((getBaseCalendar() != null) && + (!getBaseCalendar().isTimeIncluded(nextIncludedTime))){ + nextIncludedTime = + getBaseCalendar().getNextIncludedTime(nextIncludedTime); + } else { + nextIncludedTime++; + } + } + } + + return nextIncludedTime; + } + + /** + * Returns the start time of the time range (in milliseconds) of the day + * specified in timeInMillis + * + * @param timeInMillis a time containing the desired date for the starting + * time of the time range. + * @return a date/time (in milliseconds) representing the start time of the + * time range for the specified date. + */ + public long getTimeRangeStartingTimeInMillis(long timeInMillis) { + Calendar rangeStartingTime = Calendar.getInstance(); + rangeStartingTime.setTimeInMillis(timeInMillis); + rangeStartingTime.set(Calendar.HOUR_OF_DAY, rangeStartingHourOfDay); + rangeStartingTime.set(Calendar.MINUTE, rangeStartingMinute); + rangeStartingTime.set(Calendar.SECOND, rangeStartingSecond); + rangeStartingTime.set(Calendar.MILLISECOND, rangeStartingMillis); + return rangeStartingTime.getTimeInMillis(); + } + + /** + * Returns the end time of the time range (in milliseconds) of the day + * specified in timeInMillis + * + * @param timeInMillis a time containing the desired date for the ending + * time of the time range. + * @return a date/time (in milliseconds) representing the end time of the + * time range for the specified date. + */ + public long getTimeRangeEndingTimeInMillis(long timeInMillis) { + Calendar rangeEndingTime = Calendar.getInstance(); + rangeEndingTime.setTimeInMillis(timeInMillis); + rangeEndingTime.set(Calendar.HOUR_OF_DAY, rangeEndingHourOfDay); + rangeEndingTime.set(Calendar.MINUTE, rangeEndingMinute); + rangeEndingTime.set(Calendar.SECOND, rangeEndingSecond); + rangeEndingTime.set(Calendar.MILLISECOND, rangeEndingMillis); + return rangeEndingTime.getTimeInMillis(); + } + + /** + * Indicates whether the time range represents an inverted time range (see + * class description). + * + * @return a boolean indicating whether the time range is inverted + */ + public boolean getInvertTimeRange() { + return invertTimeRange; + } + + /** + * Indicates whether the time range represents an inverted time range (see + * class description). + * + * @param flag the new value for the invertTimeRange flag. + */ + public void setInvertTimeRange(boolean flag) { + this.invertTimeRange = flag; + } + + /** + * Returns a string representing the properties of the + * DailyCalendar + * + * @return the properteis of the DailyCalendar in a String format + */ + public String toString() { + long todayInMillis = Calendar.getInstance().getTimeInMillis(); + NumberFormat numberFormatter = NumberFormat.getNumberInstance(); + numberFormatter.setMaximumFractionDigits(0); + numberFormatter.setMinimumIntegerDigits(2); + StringBuffer buffer = new StringBuffer(); + buffer.append(getName()); + buffer.append(": base calendar: ["); + if (getBaseCalendar() != null) { + buffer.append(getBaseCalendar().toString()); + } else { + buffer.append("null"); + } + buffer.append("], time range: '"); + buffer.append(numberFormatter.format(rangeStartingHourOfDay)); + buffer.append(":"); + buffer.append(numberFormatter.format(rangeStartingMinute)); + buffer.append(":"); + buffer.append(numberFormatter.format(rangeStartingSecond)); + buffer.append(":"); + numberFormatter.setMinimumIntegerDigits(3); + buffer.append(numberFormatter.format(rangeStartingMillis)); + numberFormatter.setMinimumIntegerDigits(2); + buffer.append(" - "); + buffer.append(numberFormatter.format(rangeEndingHourOfDay)); + buffer.append(":"); + buffer.append(numberFormatter.format(rangeEndingMinute)); + buffer.append(":"); + buffer.append(numberFormatter.format(rangeEndingSecond)); + buffer.append(":"); + numberFormatter.setMinimumIntegerDigits(3); + buffer.append(numberFormatter.format(rangeEndingMillis)); + buffer.append("', inverted: " + + Boolean.toString(invertTimeRange) + "]"); + return buffer.toString(); + } + + /** + * Sets the time range for the DailyCalendar to the times + * represented in the specified Strings. + * + * @param rangeStartingTimeString a String representing the start time of + * the time range + * @param rangeEndingTimeString a String representing the end time of the + * excluded time range + */ + private void setTimeRange(String rangeStartingTimeString, + String rangeEndingTimeString) { + String[] rangeStartingTime; + int rangeStartingHourOfDay; + int rangeStartingMinute; + int rangeStartingSecond; + int rangeStartingMillis; + + String[] rangeEndingTime; + int rangeEndingHourOfDay; + int rangeEndingMinute; + int rangeEndingSecond; + int rangeEndingMillis; + + rangeStartingTime = rangeStartingTimeString.split(colon); + + if ((rangeStartingTime.length < 2) || (rangeStartingTime.length > 4)) { + throw new IllegalArgumentException("Invalid time string '" + + rangeStartingTimeString + "'"); + } + + rangeStartingHourOfDay = Integer.parseInt(rangeStartingTime[0]); + rangeStartingMinute = Integer.parseInt(rangeStartingTime[1]); + if (rangeStartingTime.length > 2) { + rangeStartingSecond = Integer.parseInt(rangeStartingTime[2]); + } else { + rangeStartingSecond = 0; + } + if (rangeStartingTime.length == 4) { + rangeStartingMillis = Integer.parseInt(rangeStartingTime[3]); + } else { + rangeStartingMillis = 0; + } + + rangeEndingTime = rangeEndingTimeString.split(colon); + + if ((rangeEndingTime.length < 2) || (rangeEndingTime.length > 4)) { + throw new IllegalArgumentException("Invalid time string '" + + rangeEndingTimeString + "'"); + } + + rangeEndingHourOfDay = Integer.parseInt(rangeEndingTime[0]); + rangeEndingMinute = Integer.parseInt(rangeEndingTime[1]); + if (rangeEndingTime.length > 2) { + rangeEndingSecond = Integer.parseInt(rangeEndingTime[2]); + } else { + rangeEndingSecond = 0; + } + if (rangeEndingTime.length == 4) { + rangeEndingMillis = Integer.parseInt(rangeEndingTime[3]); + } else { + rangeEndingMillis = 0; + } + + setTimeRange(rangeStartingHourOfDay, + rangeStartingMinute, + rangeStartingSecond, + rangeStartingMillis, + rangeEndingHourOfDay, + rangeEndingMinute, + rangeEndingSecond, + rangeEndingMillis); + } + + /** + * Sets the time range for the DailyCalendar to the times + * represented in the specified values. + * + * @param rangeStartingHourOfDay the hour of the start of the time range + * @param rangeStartingMinute the minute of the start of the time range + * @param rangeStartingSecond the second of the start of the time range + * @param rangeStartingMillis the millisecond of the start of the time + * range + * @param rangeEndingHourOfDay the hour of the end of the time range + * @param rangeEndingMinute the minute of the end of the time range + * @param rangeEndingSecond the second of the end of the time range + * @param rangeEndingMillis the millisecond of the start of the time + * range + */ + private void setTimeRange(int rangeStartingHourOfDay, + int rangeStartingMinute, + int rangeStartingSecond, + int rangeStartingMillis, + int rangeEndingHourOfDay, + int rangeEndingMinute, + int rangeEndingSecond, + int rangeEndingMillis) { + validate(rangeStartingHourOfDay, + rangeStartingMinute, + rangeStartingSecond, + rangeStartingMillis); + + validate(rangeEndingHourOfDay, + rangeEndingMinute, + rangeEndingSecond, + rangeEndingMillis); + + Calendar startCal = Calendar.getInstance(); + startCal.set(Calendar.HOUR_OF_DAY, rangeStartingHourOfDay); + startCal.set(Calendar.MINUTE, rangeStartingMinute); + startCal.set(Calendar.SECOND, rangeStartingSecond); + startCal.set(Calendar.MILLISECOND, rangeStartingMillis); + + Calendar endCal = Calendar.getInstance(); + endCal.set(Calendar.HOUR_OF_DAY, rangeEndingHourOfDay); + endCal.set(Calendar.MINUTE, rangeEndingMinute); + endCal.set(Calendar.SECOND, rangeEndingSecond); + endCal.set(Calendar.MILLISECOND, rangeEndingMillis); + + if (!startCal.before(endCal)) { + throw new IllegalArgumentException(invalidTimeRange + + rangeStartingHourOfDay + ":" + + rangeStartingMinute + ":" + + rangeStartingSecond + ":" + + rangeStartingMillis + separator + + rangeEndingHourOfDay + ":" + + rangeEndingMinute + ":" + + rangeEndingSecond + ":" + + rangeEndingMillis); + } + + this.rangeStartingHourOfDay = rangeStartingHourOfDay; + this.rangeStartingMinute = rangeStartingMinute; + this.rangeStartingSecond = rangeStartingSecond; + this.rangeStartingMillis = rangeStartingMillis; + this.rangeEndingHourOfDay = rangeEndingHourOfDay; + this.rangeEndingMinute = rangeEndingMinute; + this.rangeEndingSecond = rangeEndingSecond; + this.rangeEndingMillis = rangeEndingMillis; + } + + /** + * Sets the time range for the DailyCalendar to the times + * represented in the specified java.util.Calendars. + * + * @param rangeStartingCalendar a Calendar containing the start time for + * the DailyCalendar + * @param rangeEndingCalendar a Calendar containing the end time for + * the DailyCalendar + */ + private void setTimeRange(Calendar rangeStartingCalendar, + Calendar rangeEndingCalendar) { + setTimeRange( + rangeStartingCalendar.get(Calendar.HOUR_OF_DAY), + rangeStartingCalendar.get(Calendar.MINUTE), + rangeStartingCalendar.get(Calendar.SECOND), + rangeStartingCalendar.get(Calendar.MILLISECOND), + rangeEndingCalendar.get(Calendar.HOUR_OF_DAY), + rangeEndingCalendar.get(Calendar.MINUTE), + rangeEndingCalendar.get(Calendar.SECOND), + rangeEndingCalendar.get(Calendar.MILLISECOND)); + } + + /** + * Sets the time range for the DailyCalendar to the times + * represented in the specified values. + * + * @param rangeStartingTime the starting time (in milliseconds) for the + * time range + * @param rangeEndingTime the ending time (in milliseconds) for the time + * range + */ + private void setTimeRange(long rangeStartingTime, + long rangeEndingTime) { + Calendar startCal = Calendar.getInstance(); + Calendar endCal = Calendar.getInstance(); + startCal.setTimeInMillis(rangeStartingTime); + endCal.setTimeInMillis(rangeEndingTime); + + setTimeRange(startCal, endCal); + } + + /** + * Returns the start of the given day in milliseconds + * + * @param timeInMillis a time containing the desired date for the + * start-of-day time. + * @return the start of the given day in milliseconds + */ + private long getStartOfDayInMillis(long timeInMillis) { + Calendar startOfDay = Calendar.getInstance(); + startOfDay.setTimeInMillis(timeInMillis); + startOfDay.set(Calendar.HOUR_OF_DAY, 0); + startOfDay.set(Calendar.MINUTE, 0); + startOfDay.set(Calendar.SECOND, 0); + startOfDay.set(Calendar.MILLISECOND, 0); + return startOfDay.getTimeInMillis(); + } + + /** + * Returns the end of the given day in milliseconds + * + * @param timeInMillis a time containing the desired date for the + * end-of-day time. + * @return the end of the given day in milliseconds + */ + private long getEndOfDayInMillis(long timeInMillis) { + Calendar endOfDay = Calendar.getInstance(); + endOfDay.setTimeInMillis(timeInMillis); + endOfDay.set(Calendar.HOUR_OF_DAY, 23); + endOfDay.set(Calendar.MINUTE, 59); + endOfDay.set(Calendar.SECOND, 59); + endOfDay.set(Calendar.MILLISECOND, 999); + return endOfDay.getTimeInMillis(); + } + + /** + * Checks the specified values for validity as a set of time values. + * + * @param hourOfDay the hour of the time to check (in military (24-hour) + * time) + * @param minute the minute of the time to check + * @param second the second of the time to check + * @param millis the millisecond of the time to check + */ + private void validate(int hourOfDay, int minute, int second, int millis) { + if (hourOfDay < 0 || hourOfDay > 23) { + throw new IllegalArgumentException(invalidHourOfDay + hourOfDay); + } + if (minute < 0 || minute > 59) { + throw new IllegalArgumentException(invalidMinute + minute); + } + if (second < 0 || second > 59) { + throw new IllegalArgumentException(invalidSecond + second); + } + if (millis < 0 || millis > 999) { + throw new IllegalArgumentException(invalidMillis + millis); + } + } +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/impl/calendar/HolidayCalendar.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/calendar/HolidayCalendar.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/calendar/HolidayCalendar.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,140 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.calendar; + +import java.io.Serializable; +import java.util.Collections; +import java.util.Date; +import java.util.SortedSet; +import java.util.TreeSet; + +import org.quartz.Calendar; + +/** + *

+ * This implementation of the Calendar stores a list of holidays (full days + * that are excluded from scheduling). + *

+ * + *

+ * The implementation DOES take the year into consideration, so if you want to + * exclude July 4th for the next 10 years, you need to add 10 entries to the + * exclude list. + *

+ * + * @author Sharada Jambula + * @author Juergen Donnerstag + */ +public class HolidayCalendar extends BaseCalendar implements Calendar, + Serializable { + + // A sorted set to store the holidays + private TreeSet dates = new TreeSet(); + + /** + * Constructor + */ + public HolidayCalendar() { + } + + /** + * Constructor + */ + public HolidayCalendar(Calendar baseCalendar) { + setBaseCalendar(baseCalendar); + } + + /** + *

+ * Determine whether the given time (in milliseconds) is 'included' by the + * Calendar. + *

+ * + *

+ * Note that this Calendar is only has full-day precision. + *

+ */ + public boolean isTimeIncluded(long timeStamp) { + if (super.isTimeIncluded(timeStamp) == false) return false; + + Date lookFor = buildHoliday(new Date(timeStamp)); + + return !(dates.contains(lookFor)); + } + + /** + *

+ * Determine the next time (in milliseconds) that is 'included' by the + * Calendar after the given time. + *

+ * + *

+ * Note that this Calendar is only has full-day precision. + *

+ */ + public long getNextIncludedTime(long timeStamp) { + + // Call base calendar implementation first + long baseTime = super.getNextIncludedTime(timeStamp); + if ((baseTime > 0) && (baseTime > timeStamp)) timeStamp = baseTime; + + // Get timestamp for 00:00:00 + long newTimeStamp = buildHoliday(timeStamp); + + java.util.Calendar day = getJavaCalendar(newTimeStamp); + while (isTimeIncluded(day.getTime().getTime()) == false) { + day.add(java.util.Calendar.DATE, 1); + } + + return day.getTime().getTime(); + } + + /** + *

+ * Add the given Date to the list of excluded days. Only the month, day and + * year of the returned dates are significant. + *

+ */ + public void addExcludedDate(Date excludedDate) { + Date date = buildHoliday(excludedDate); + /* + * System.err.println( "HolidayCalendar.add(): date=" + + * excludedDate.toLocaleString()); + */ + this.dates.add(date); + } + + public void removeExcludedDate(Date dateToRemove) { + Date date = buildHoliday(dateToRemove); + dates.remove(date); + } + + /** + *

+ * Returns a SortedSet of Dates representing the excluded + * days. Only the month, day and year of the returned dates are + * significant. + *

+ */ + public SortedSet getExcludedDates() { + return Collections.unmodifiableSortedSet(dates); + } +} Index: 3rdParty_sources/quartz/org/quartz/impl/calendar/MonthlyCalendar.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/calendar/MonthlyCalendar.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/calendar/MonthlyCalendar.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,196 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + * and Juergen Donnerstag (c) 2002, EDS 2002 + */ + +package org.quartz.impl.calendar; + +import java.io.Serializable; +import java.util.Date; + +import org.quartz.Calendar; + +/** + *

+ * This implementation of the Calendar excludes a set of days of the month. You + * may use it to exclude every 1. of each month for example. But you may define + * any day of a month. + *

+ * + * @see org.quartz.Calendar + * @see org.quartz.impl.calendar.BaseCalendar + * + * @author Juergen Donnerstag + */ +public class MonthlyCalendar extends BaseCalendar implements Calendar, + Serializable { + + // An array to store a months days which are to be excluded. + // java.util.Calendar.get( ) as index. + private boolean[] excludeDays = new boolean[31]; + + // Will be set to true, if all week days are excluded + private boolean excludeAll = false; + + /** + *

+ * Constructor + *

+ */ + public MonthlyCalendar() { + super(); + init(); + } + + /** + *

+ * Constructor + *

+ */ + public MonthlyCalendar(Calendar baseCalendar) { + super(baseCalendar); + init(); + } + + /** + *

+ * Initialize internal variables + *

+ */ + private void init() { + // all days are included by default + excludeAll = areAllDaysExcluded(); + } + + /** + *

+ * Get the array which defines the exclude-value of each day of month + *

+ */ + public boolean[] getDaysExcluded() { + return excludeDays; + } + + /** + *

+ * Return true, if mday is defined to be exluded. + *

+ */ + public boolean isDayExcluded(int day) { + return excludeDays[day - 1]; + } + + /** + *

+ * Redefine the array of days excluded. The array must of size greater or + * equal 31. + *

+ */ + public void setDaysExcluded(boolean[] days) { + if (days == null) return; + + excludeDays = days; + excludeAll = areAllDaysExcluded(); + } + + /** + *

+ * Redefine a certain day of the month to be excluded (true) or included + * (false). + *

+ */ + public void setDayExcluded(int day, boolean exclude) { + excludeDays[day] = exclude; + excludeAll = areAllDaysExcluded(); + } + + /** + *

+ * Check if all days are excluded. That is no day is included. + *

+ * + * @return boolean + */ + public boolean areAllDaysExcluded() { + for (int i = 1; i <= 31; i++) { + if (isDayExcluded(i) == false) return false; + } + + return true; + } + + /** + *

+ * Determine whether the given time (in milliseconds) is 'included' by the + * Calendar. + *

+ * + *

+ * Note that this Calendar is only has full-day precision. + *

+ */ + public boolean isTimeIncluded(long timeStamp) { + if (excludeAll == true) return false; + + // Test the base calendar first. Only if the base calendar not already + // excludes the time/date, continue evaluating this calendar instance. + if (super.isTimeIncluded(timeStamp) == false) { return false; } + + java.util.Calendar cl = java.util.Calendar.getInstance(); + cl.setTime(new Date(timeStamp)); + int day = cl.get(java.util.Calendar.DAY_OF_MONTH); + + return !(isDayExcluded(day)); + } + + /** + *

+ * Determine the next time (in milliseconds) that is 'included' by the + * Calendar after the given time. Return the original value if timeStamp is + * included. Return 0 if all days are excluded. + *

+ * + *

+ * Note that this Calendar is only has full-day precision. + *

+ */ + public long getNextIncludedTime(long timeStamp) { + if (excludeAll == true) return 0; + + // Call base calendar implementation first + long baseTime = super.getNextIncludedTime(timeStamp); + if ((baseTime > 0) && (baseTime > timeStamp)) timeStamp = baseTime; + + // Get timestamp for 00:00:00 + long newTimeStamp = buildHoliday(timeStamp); + + java.util.Calendar cl = getJavaCalendar(newTimeStamp); + int day = cl.get(java.util.Calendar.DAY_OF_MONTH); + + if (!isDayExcluded(day)) return timeStamp; // return the original value + + while (isDayExcluded(day) == true) { + cl.add(java.util.Calendar.DATE, 1); + day = cl.get(java.util.Calendar.DAY_OF_WEEK); + } + + return cl.getTime().getTime(); + } +} Index: 3rdParty_sources/quartz/org/quartz/impl/calendar/WeeklyCalendar.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/calendar/WeeklyCalendar.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/calendar/WeeklyCalendar.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,211 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + * and Juergen Donnerstag (c) 2002, EDS 2002 + */ + +package org.quartz.impl.calendar; + +import java.io.Serializable; +import java.util.Date; + +import org.quartz.Calendar; + +/** + *

+ * This implementation of the Calendar excludes a set of days of the week. You + * may use it to exclude weekends for example. But you may define any day of + * the week. + *

+ * + * @see org.quartz.Calendar + * @see org.quartz.impl.calendar.BaseCalendar + * + * @author Juergen Donnerstag + */ +public class WeeklyCalendar extends BaseCalendar implements Calendar, + Serializable { + + // An array to store the week days which are to be excluded. + // java.util.Calendar.MONDAY etc. are used as index. + private boolean[] excludeDays = new boolean[8]; + + // Will be set to true, if all week days are excluded + private boolean excludeAll = false; + + /** + *

+ * Constructor + *

+ */ + public WeeklyCalendar() { + super(); + init(); + } + + /** + *

+ * Constructor + *

+ */ + public WeeklyCalendar(Calendar baseCalendar) { + super(baseCalendar); + init(); + } + + /** + *

+ * Initialize internal variables + *

+ */ + private void init() { + excludeDays[java.util.Calendar.SUNDAY] = true; + excludeDays[java.util.Calendar.SATURDAY] = true; + excludeAll = areAllDaysExcluded(); + } + + /** + *

+ * Get the array with the week days + *

+ */ + public boolean[] getDaysExcluded() { + return excludeDays; + } + + /** + *

+ * Return true, if wday (see Calendar.get()) is defined to be exluded. E. g. + * saturday and sunday. + *

+ */ + public boolean isDayExcluded(int wday) { + return excludeDays[wday]; + } + + /** + *

+ * Redefine the array of days excluded. The array must of size greater or + * equal 8. java.util.Calendar's constants like MONDAY should be used as + * index. A value of true is regarded as: exclude it. + *

+ */ + public void setDaysExcluded(boolean[] weekDays) { + if (weekDays == null) return; + + excludeDays = weekDays; + excludeAll = areAllDaysExcluded(); + } + + /** + *

+ * Redefine a certain day of the week to be excluded (true) or included + * (false). Use java.util.Calendar's constants like MONDAY to determine the + * wday. + *

+ */ + public void setDayExcluded(int wday, boolean exclude) { + excludeDays[wday] = exclude; + excludeAll = areAllDaysExcluded(); + } + + /** + *

+ * Check if all week days are excluded. That is no day is included. + *

+ * + * @return boolean + */ + public boolean areAllDaysExcluded() { + if (isDayExcluded(java.util.Calendar.SUNDAY) == false) return false; + + if (isDayExcluded(java.util.Calendar.MONDAY) == false) return false; + + if (isDayExcluded(java.util.Calendar.TUESDAY) == false) return false; + + if (isDayExcluded(java.util.Calendar.WEDNESDAY) == false) return false; + + if (isDayExcluded(java.util.Calendar.THURSDAY) == false) return false; + + if (isDayExcluded(java.util.Calendar.FRIDAY) == false) return false; + + if (isDayExcluded(java.util.Calendar.SATURDAY) == false) return false; + + return true; + } + + /** + *

+ * Determine whether the given time (in milliseconds) is 'included' by the + * Calendar. + *

+ * + *

+ * Note that this Calendar is only has full-day precision. + *

+ */ + public boolean isTimeIncluded(long timeStamp) { + if (excludeAll == true) return false; + + // Test the base calendar first. Only if the base calendar not already + // excludes the time/date, continue evaluating this calendar instance. + if (super.isTimeIncluded(timeStamp) == false) { return false; } + + java.util.Calendar cl = java.util.Calendar.getInstance(); + cl.setTime(new Date(timeStamp)); + int wday = cl.get(java.util.Calendar.DAY_OF_WEEK); + + return !(isDayExcluded(wday)); + } + + /** + *

+ * Determine the next time (in milliseconds) that is 'included' by the + * Calendar after the given time. Return the original value if timeStamp is + * included. Return 0 if all days are excluded. + *

+ * + *

+ * Note that this Calendar is only has full-day precision. + *

+ */ + public long getNextIncludedTime(long timeStamp) { + if (excludeAll == true) return 0; + + // Call base calendar implementation first + long baseTime = super.getNextIncludedTime(timeStamp); + if ((baseTime > 0) && (baseTime > timeStamp)) timeStamp = baseTime; + + // Get timestamp for 00:00:00 + long newTimeStamp = buildHoliday(timeStamp); + + java.util.Calendar cl = getJavaCalendar(newTimeStamp); + int wday = cl.get(java.util.Calendar.DAY_OF_WEEK); + + if (!isDayExcluded(wday)) return timeStamp; // return the original + // value + + while (isDayExcluded(wday) == true) { + cl.add(java.util.Calendar.DATE, 1); + wday = cl.get(java.util.Calendar.DAY_OF_WEEK); + } + + return cl.getTime().getTime(); + } +} Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/CloudscapeDelegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/CloudscapeDelegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/CloudscapeDelegate.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,114 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ + +package org.quartz.impl.jdbcjobstore; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.apache.commons.logging.Log; + +/** + *

+ * This is a driver delegate for the Cloudscape database, not surprisingly, + * it is known to work with Derby as well. + *

+ * + * @author James House + * @author Sridhar Jawaharlal, Srinivas Venkatarangaiah + */ +public class CloudscapeDelegate extends StdJDBCDelegate { + /** + *

+ * Create new CloudscapeDelegate instance. + *

+ * + * @param logger + * the logger to use during execution + * @param tablePrefix + * the prefix of all table names + */ + public CloudscapeDelegate(Log log, String tablePrefix, String instanceId) { + super(log, tablePrefix, instanceId); + } + + /** + *

+ * Create new CloudscapeDelegate instance. + *

+ * + * @param logger + * the logger to use during execution + * @param tablePrefix + * the prefix of all table names + * @param useProperties + * useProperties flag + */ + public CloudscapeDelegate(Log log, String tablePrefix, String instanceId, + Boolean useProperties) { + super(log, tablePrefix, instanceId, useProperties); + } + + //--------------------------------------------------------------------------- + // protected methods that can be overridden by subclasses + //--------------------------------------------------------------------------- + + /** + *

+ * This method should be overridden by any delegate subclasses that need + * special handling for BLOBs. The default implementation uses standard + * JDBC java.sql.Blob operations. + *

+ * + * @param rs + * the result set, already queued to the correct row + * @param colName + * the column name for the BLOB + * @return the deserialized Object from the ResultSet BLOB + * @throws ClassNotFoundException + * if a class found during deserialization cannot be found + * @throws IOException + * if deserialization causes an error + */ + protected Object getObjectFromBlob(ResultSet rs, String colName) + throws ClassNotFoundException, IOException, SQLException + { + Object obj = null; + + byte[] inputBytes = rs.getBytes(colName); + + if (null != inputBytes) { + ByteArrayInputStream bais = new + ByteArrayInputStream(inputBytes); + + ObjectInputStream in = new ObjectInputStream(bais); + obj = in.readObject(); + in.close(); + } + + return obj; + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/Constants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/Constants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/Constants.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,188 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ + +package org.quartz.impl.jdbcjobstore; + +/** + *

+ * This interface can be implemented by any {@link + * org.quartz.impl.jdbcjobstore.DriverDelegate} + * class that needs to use the constants contained herein. + *

+ * + * @author Jeffrey Wescott + * @author James House + */ +public interface Constants { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + // Table names + public static final String TABLE_JOB_DETAILS = "JOB_DETAILS"; + + public static final String TABLE_TRIGGERS = "TRIGGERS"; + + public static final String TABLE_SIMPLE_TRIGGERS = "SIMPLE_TRIGGERS"; + + public static final String TABLE_CRON_TRIGGERS = "CRON_TRIGGERS"; + + public static final String TABLE_BLOB_TRIGGERS = "BLOB_TRIGGERS"; + + public static final String TABLE_FIRED_TRIGGERS = "FIRED_TRIGGERS"; + + public static final String TABLE_JOB_LISTENERS = "JOB_LISTENERS"; + + public static final String TABLE_TRIGGER_LISTENERS = "TRIGGER_LISTENERS"; + + public static final String TABLE_CALENDARS = "CALENDARS"; + + public static final String TABLE_PAUSED_TRIGGERS = "PAUSED_TRIGGER_GRPS"; + + public static final String TABLE_LOCKS = "LOCKS"; + + public static final String TABLE_SCHEDULER_STATE = "SCHEDULER_STATE"; + + // TABLE_JOB_DETAILS columns names + public static final String COL_JOB_NAME = "JOB_NAME"; + + public static final String COL_JOB_GROUP = "JOB_GROUP"; + + public static final String COL_IS_DURABLE = "IS_DURABLE"; + + public static final String COL_IS_VOLATILE = "IS_VOLATILE"; + + public static final String COL_IS_STATEFUL = "IS_STATEFUL"; + + public static final String COL_REQUESTS_RECOVERY = "REQUESTS_RECOVERY"; + + public static final String COL_JOB_DATAMAP = "JOB_DATA"; + + public static final String COL_JOB_CLASS = "JOB_CLASS_NAME"; + + public static final String COL_DESCRIPTION = "DESCRIPTION"; + + // TABLE_JOB_LISTENERS columns names + public static final String COL_JOB_LISTENER = "JOB_LISTENER"; + + // TABLE_TRIGGERS columns names + public static final String COL_TRIGGER_NAME = "TRIGGER_NAME"; + + public static final String COL_TRIGGER_GROUP = "TRIGGER_GROUP"; + + public static final String COL_NEXT_FIRE_TIME = "NEXT_FIRE_TIME"; + + public static final String COL_PREV_FIRE_TIME = "PREV_FIRE_TIME"; + + public static final String COL_TRIGGER_STATE = "TRIGGER_STATE"; + + public static final String COL_TRIGGER_TYPE = "TRIGGER_TYPE"; + + public static final String COL_START_TIME = "START_TIME"; + + public static final String COL_END_TIME = "END_TIME"; + + public static final String COL_MISFIRE_INSTRUCTION = "MISFIRE_INSTR"; + + public static final String ALIAS_COL_NEXT_FIRE_TIME = "ALIAS_NXT_FR_TM"; + + // TABLE_SIMPLE_TRIGGERS columns names + public static final String COL_REPEAT_COUNT = "REPEAT_COUNT"; + + public static final String COL_REPEAT_INTERVAL = "REPEAT_INTERVAL"; + + public static final String COL_TIMES_TRIGGERED = "TIMES_TRIGGERED"; + + // TABLE_CRON_TRIGGERS columns names + public static final String COL_CRON_EXPRESSION = "CRON_EXPRESSION"; + + // TABLE_BLOB_TRIGGERS columns names + public static final String COL_BLOB = "BLOB_DATA"; + + public static final String COL_TIME_ZONE_ID = "TIME_ZONE_ID"; + + // TABLE_TRIGGER_LISTENERS + public static final String COL_TRIGGER_LISTENER = "TRIGGER_LISTENER"; + + // TABLE_FIRED_TRIGGERS columns names + public static final String COL_INSTANCE_NAME = "INSTANCE_NAME"; + + public static final String COL_FIRED_TIME = "FIRED_TIME"; + + public static final String COL_ENTRY_ID = "ENTRY_ID"; + + public static final String COL_ENTRY_STATE = "STATE"; + + // TABLE_CALENDARS columns names + public static final String COL_CALENDAR_NAME = "CALENDAR_NAME"; + + public static final String COL_CALENDAR = "CALENDAR"; + + // TABLE_LOCKS columns names + public static final String COL_LOCK_NAME = "LOCK_NAME"; + + // TABLE_LOCKS columns names + public static final String COL_LAST_CHECKIN_TIME = "LAST_CHECKIN_TIME"; + + public static final String COL_CHECKIN_INTERVAL = "CHECKIN_INTERVAL"; + + public static final String COL_RECOVERER = "RECOVERER"; + + // MISC CONSTANTS + public static final String DEFAULT_TABLE_PREFIX = "QRTZ_"; + + // STATES + public final static String STATE_WAITING = "WAITING"; + + public final static String STATE_ACQUIRED = "ACQUIRED"; + + public final static String STATE_EXECUTING = "EXECUTING"; + + public final static String STATE_COMPLETE = "COMPLETE"; + + public final static String STATE_BLOCKED = "BLOCKED"; + + public final static String STATE_ERROR = "ERROR"; + + public final static String STATE_PAUSED = "PAUSED"; + + public final static String STATE_PAUSED_BLOCKED = "PAUSED_BLOCKED"; + + public final static String STATE_DELETED = "DELETED"; + + public final static String STATE_MISFIRED = "MISFIRED"; + + public final static String ALL_GROUPS_PAUSED = "_$_ALL_GROUPS_PAUSED_$_"; + + // TRIGGER TYPES + public final static String TTYPE_SIMPLE = "SIMPLE"; + + public final static String TTYPE_CRON = "CRON"; + + public final static String TTYPE_BLOB = "BLOB"; +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/DB2v6Delegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/DB2v6Delegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/DB2v6Delegate.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,152 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import org.apache.commons.logging.Log; + +/** + * Quartz JDBC delegate for DB2 v6 databases. select count(name) + * had to be replaced with select count(*). + * + * @author Martin Renner + * @author James House + */ +public class DB2v6Delegate extends StdJDBCDelegate { + public static final String SELECT_NUM_JOBS = "SELECT COUNT(*) FROM " + + TABLE_PREFIX_SUBST + TABLE_JOB_DETAILS; + + public static final String SELECT_NUM_TRIGGERS_FOR_JOB = "SELECT COUNT(*) FROM " + + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + + " WHERE " + + COL_JOB_NAME + + " = ? AND " + COL_JOB_GROUP + " = ?"; + + public static final String SELECT_NUM_TRIGGERS = "SELECT COUNT(*) FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS; + + public static final String SELECT_NUM_CALENDARS = "SELECT COUNT(*) FROM " + + TABLE_PREFIX_SUBST + TABLE_CALENDARS; + + public DB2v6Delegate(Log logger, String tablePrefix, String instanceId) { + super(logger, tablePrefix, instanceId); + } + + public DB2v6Delegate(Log logger, String tablePrefix, String instanceId, + Boolean useProperties) { + super(logger, tablePrefix, instanceId, useProperties); + } + + public int selectNumJobs(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + int count = 0; + ps = conn.prepareStatement(rtp(SELECT_NUM_JOBS)); + rs = ps.executeQuery(); + + if (rs.next()) { + count = rs.getInt(1); + } + + return count; + } finally { + close(ps); + } + } + + public int selectNumTriggersForJob(Connection conn, String jobName, + String groupName) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_NUM_TRIGGERS_FOR_JOB)); + ps.setString(1, jobName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + if (rs.next()) { + return rs.getInt(1); + } else { + return 0; + } + } finally { + close(ps); + } + } + + public int selectNumTriggers(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + int count = 0; + ps = conn.prepareStatement(rtp(SELECT_NUM_TRIGGERS)); + rs = ps.executeQuery(); + + if (rs.next()) { + count = rs.getInt(1); + } + + return count; + } finally { + close(ps); + } + } + + public int selectNumCalendars(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + int count = 0; + ps = conn.prepareStatement(rtp(SELECT_NUM_CALENDARS)); + rs = ps.executeQuery(); + + if (rs.next()) { + count = rs.getInt(1); + } + + return count; + } finally { + close(ps); + } + } + + private void close(Statement stmt) { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException ignore) { + } + } + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/DB2v7Delegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/DB2v7Delegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/DB2v7Delegate.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,550 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; + +import org.quartz.impl.jdbcjobstore.StdJDBCDelegate; +import org.apache.commons.logging.Log; +import org.quartz.Calendar; +import org.quartz.CronTrigger; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.Scheduler; +import org.quartz.SimpleTrigger; +import org.quartz.Trigger; +import org.quartz.utils.Key; + +/** + * Quartz JDBC delegate for DB2 v7 databases. + * + * @author Blair Jensen + */ +public class DB2v7Delegate extends StdJDBCDelegate { + + public DB2v7Delegate(Log logger, String tablePrefix, String instanceId) { + super(logger, tablePrefix, instanceId); + } + + public DB2v7Delegate(Log log, String tablePrefix, String instanceId, + Boolean useProperties) { + super(log, tablePrefix, instanceId, useProperties); + } + + public Trigger[] selectTriggersForRecoveringJobs(Connection conn) + throws SQLException, IOException, ClassNotFoundException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn + .prepareStatement(rtp(SELECT_INSTANCES_RECOVERABLE_FIRED_TRIGGERS)); + ps.setString(1, instanceId); + ps.setString(2, "1"); + //ps.setBoolean(2, true); + rs = ps.executeQuery(); + + long dumId = System.currentTimeMillis(); + ArrayList list = new ArrayList(); + while (rs.next()) { + String jobName = rs.getString(COL_JOB_NAME); + String jobGroup = rs.getString(COL_JOB_GROUP); + String trigName = rs.getString(COL_TRIGGER_NAME); + String trigGroup = rs.getString(COL_TRIGGER_GROUP); + long firedTime = rs.getLong(COL_FIRED_TIME); + SimpleTrigger rcvryTrig = new SimpleTrigger("recover_" + + instanceId + "_" + String.valueOf(dumId++), + Scheduler.DEFAULT_RECOVERY_GROUP, new Date(firedTime)); + rcvryTrig.setJobName(jobName); + rcvryTrig.setJobGroup(jobGroup); + rcvryTrig + .setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW); + + JobDataMap jd = selectTriggerJobDataMap(conn, trigName, trigGroup); + jd.put("QRTZ_FAILED_JOB_ORIG_TRIGGER_NAME", trigName); + jd.put("QRTZ_FAILED_JOB_ORIG_TRIGGER_GROUP", trigGroup); + jd.put("QRTZ_FAILED_JOB_ORIG_TRIGGER_FIRETIME_IN_MILLISECONDS_AS_STRING", String.valueOf(firedTime)); + rcvryTrig.setJobDataMap(jd); + + list.add(rcvryTrig); + } + Object[] oArr = list.toArray(); + Trigger[] tArr = new Trigger[oArr.length]; + System.arraycopy(oArr, 0, tArr, 0, oArr.length); + return tArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int insertJobDetail(Connection conn, JobDetail job) + throws IOException, SQLException { + ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + + ps = conn.prepareStatement(rtp(INSERT_JOB_DETAIL)); + ps.setString(1, job.getName()); + ps.setString(2, job.getGroup()); + ps.setString(3, job.getDescription()); + ps.setString(4, job.getJobClass().getName()); + ps.setString(5, toBooleanIntString(job.isDurable())); + ps.setString(6, toBooleanIntString(job.isVolatile())); + ps.setString(7, toBooleanIntString(job.isStateful())); + ps.setString(8, toBooleanIntString(job.requestsRecovery())); + //ps.setBoolean (5, job.isDurable()); + //ps.setBoolean (6, job.isVolatile()); + //ps.setBoolean (7, job.isStateful()); + //ps.setBoolean (8, job.requestsRecovery()); + ps.setObject(9, baos.toByteArray(), java.sql.Types.BLOB); + //ps.setBytes (9, baos.toByteArray()); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + String[] jobListeners = job.getJobListenerNames(); + for (int i = 0; jobListeners != null && i < jobListeners.length; i++) + insertJobListener(conn, job, jobListeners[i]); + } + + return insertResult; + } + + public int updateJobDetail(Connection conn, JobDetail job) + throws IOException, SQLException { + ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + ps = conn.prepareStatement(rtp(UPDATE_JOB_DETAIL)); + ps.setString(1, job.getDescription()); + ps.setString(2, job.getJobClass().getName()); + ps.setString(3, toBooleanIntString(job.isDurable())); + ps.setString(4, toBooleanIntString(job.isVolatile())); + ps.setString(5, toBooleanIntString(job.isStateful())); + ps.setString(6, toBooleanIntString(job.requestsRecovery())); + //ps.setBoolean (3, job.isDurable()); + //ps.setBoolean (4, job.isVolatile()); + //ps.setBoolean (5, job.isStateful()); + //ps.setBoolean (6, job.requestsRecovery()); + ps.setObject(7, baos.toByteArray(), java.sql.Types.BLOB); + //ps.setBytes (7, baos.toByteArray()); + ps.setString(8, job.getName()); + ps.setString(9, job.getGroup()); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + deleteJobListeners(conn, job.getName(), job.getGroup()); + + String[] jobListeners = job.getJobListenerNames(); + for (int i = 0; jobListeners != null && i < jobListeners.length; i++) + insertJobListener(conn, job, jobListeners[i]); + } + + return insertResult; + } + + public int insertTrigger(Connection conn, Trigger trigger, String state, + JobDetail jobDetail) throws SQLException, IOException { + + ByteArrayOutputStream baos = serializeJobData(trigger.getJobDataMap()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + ps = conn.prepareStatement(rtp(INSERT_TRIGGER)); + ps.setString(1, trigger.getName()); + ps.setString(2, trigger.getGroup()); + ps.setString(3, trigger.getJobName()); + ps.setString(4, trigger.getJobGroup()); + ps.setString(5, toBooleanIntString(trigger.isVolatile())); + //ps.setBoolean(5, trigger.isVolatile()); + ps.setString(6, trigger.getDescription()); + ps.setBigDecimal(7, new BigDecimal(String.valueOf(trigger + .getNextFireTime().getTime()))); + long prevFireTime = -1; + if (trigger.getPreviousFireTime() != null) { + prevFireTime = trigger.getPreviousFireTime().getTime(); + } + ps.setBigDecimal(8, new BigDecimal(String.valueOf(prevFireTime))); + ps.setString(9, state); + if (trigger instanceof SimpleTrigger) { + ps.setString(10, TTYPE_SIMPLE); + } else if (trigger instanceof CronTrigger) { + ps.setString(10, TTYPE_CRON); + } else { // (trigger instanceof BlobTrigger) + ps.setString(10, TTYPE_BLOB); + } + ps.setBigDecimal(11, new BigDecimal(String.valueOf(trigger + .getStartTime().getTime()))); + long endTime = 0; + if (trigger.getEndTime() != null) { + endTime = trigger.getEndTime().getTime(); + } + ps.setBigDecimal(12, new BigDecimal(String.valueOf(endTime))); + ps.setString(13, trigger.getCalendarName()); + ps.setInt(14, trigger.getMisfireInstruction()); + ps.setObject(15, baos.toByteArray(), java.sql.Types.BLOB); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + String[] trigListeners = trigger.getTriggerListenerNames(); + for (int i = 0; trigListeners != null && i < trigListeners.length; i++) + insertTriggerListener(conn, trigger, trigListeners[i]); + } + + return insertResult; + } + + public int updateTrigger(Connection conn, Trigger trigger, String state, + JobDetail jobDetail) throws SQLException, IOException { + ByteArrayOutputStream baos = serializeJobData(trigger.getJobDataMap()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + ps = conn.prepareStatement(rtp(UPDATE_TRIGGER)); + ps.setString(1, trigger.getJobName()); + ps.setString(2, trigger.getJobGroup()); + ps.setString(3, toBooleanIntString(trigger.isVolatile())); + //ps.setBoolean(3, trigger.isVolatile()); + ps.setString(4, trigger.getDescription()); + long nextFireTime = -1; + if (trigger.getNextFireTime() != null) { + nextFireTime = trigger.getNextFireTime().getTime(); + } + ps.setBigDecimal(5, new BigDecimal(String.valueOf(nextFireTime))); + long prevFireTime = -1; + if (trigger.getPreviousFireTime() != null) { + prevFireTime = trigger.getPreviousFireTime().getTime(); + } + ps.setBigDecimal(6, new BigDecimal(String.valueOf(prevFireTime))); + ps.setString(7, state); + if (trigger instanceof SimpleTrigger) { + // updateSimpleTrigger(conn, (SimpleTrigger)trigger); + ps.setString(8, TTYPE_SIMPLE); + } else if (trigger instanceof CronTrigger) { + // updateCronTrigger(conn, (CronTrigger)trigger); + ps.setString(8, TTYPE_CRON); + } else { + // updateBlobTrigger(conn, trigger); + ps.setString(8, TTYPE_BLOB); + } + ps.setBigDecimal(9, new BigDecimal(String.valueOf(trigger + .getStartTime().getTime()))); + long endTime = 0; + if (trigger.getEndTime() != null) { + endTime = trigger.getEndTime().getTime(); + } + ps.setBigDecimal(10, new BigDecimal(String.valueOf(endTime))); + ps.setString(11, trigger.getCalendarName()); + ps.setInt(12, trigger.getMisfireInstruction()); + ps.setObject(13, baos.toByteArray(), java.sql.Types.BLOB); + ps.setString(14, trigger.getName()); + ps.setString(15, trigger.getGroup()); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + deleteTriggerListeners(conn, trigger.getName(), trigger.getGroup()); + + String[] trigListeners = trigger.getTriggerListenerNames(); + for (int i = 0; trigListeners != null && i < trigListeners.length; i++) + insertTriggerListener(conn, trigger, trigListeners[i]); + } + + return insertResult; + } + + public int insertFiredTrigger(Connection conn, Trigger trigger, + String state, JobDetail job) throws SQLException { + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(rtp(INSERT_FIRED_TRIGGER)); + ps.setString(1, trigger.getFireInstanceId()); + ps.setString(2, trigger.getName()); + ps.setString(3, trigger.getGroup()); + ps.setString(4, toBooleanIntString(trigger.isVolatile())); + //ps.setBoolean(4, trigger.isVolatile()); + ps.setString(5, instanceId); + ps.setBigDecimal(6, new BigDecimal(String.valueOf(trigger + .getNextFireTime().getTime()))); + ps.setString(7, state); + if (job != null) { + ps.setString(8, trigger.getJobName()); + ps.setString(9, trigger.getJobGroup()); + ps.setString(10, toBooleanIntString(job.isStateful())); + ps.setString(11, toBooleanIntString(job.requestsRecovery())); + //ps.setBoolean(10, job.isStateful()); + //ps.setBoolean(11, job.requestsRecovery()); + } else { + ps.setString(8, null); + ps.setString(9, null); + ps.setString(10, "0"); + ps.setString(11, "0"); + //ps.setBoolean(10, false); + //ps.setBoolean(11, false); + } + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int updateJobData(Connection conn, JobDetail job) + throws IOException, SQLException { + ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap()); + + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_JOB_DATA)); + ps.setObject(1, baos.toByteArray(), java.sql.Types.BLOB); + //ps.setBytes(1, baos.toByteArray()); + ps.setString(2, job.getName()); + ps.setString(3, job.getGroup()); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int insertCalendar(Connection conn, String calendarName, + Calendar calendar) throws IOException, SQLException { + ByteArrayOutputStream baos = serializeObject(calendar); + + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(INSERT_CALENDAR)); + ps.setString(1, calendarName); + ps.setObject(2, baos.toByteArray(), java.sql.Types.BLOB); + //ps.setBytes(2, baos.toByteArray()); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int updateCalendar(Connection conn, String calendarName, + Calendar calendar) throws IOException, SQLException { + ByteArrayOutputStream baos = serializeObject(calendar); + + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_CALENDAR)); + ps.setString(1, calendarName); + ps.setObject(2, baos.toByteArray(), java.sql.Types.BLOB); + //ps.setBytes(2, baos.toByteArray()); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int deleteVolatileFiredTriggers(Connection conn) throws SQLException { + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(rtp(DELETE_VOLATILE_FIRED_TRIGGERS)); + ps.setString(1, "1"); + //ps.setBoolean(1, true); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public Key[] selectVolatileTriggers(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_VOLATILE_TRIGGERS)); + ps.setString(1, "1"); + //ps.setBoolean(1, true); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + String triggerName = rs.getString(COL_TRIGGER_NAME); + String groupName = rs.getString(COL_TRIGGER_GROUP); + list.add(new Key(triggerName, groupName)); + } + Object[] oArr = list.toArray(); + Key[] kArr = new Key[oArr.length]; + System.arraycopy(oArr, 0, kArr, 0, oArr.length); + return kArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public Key[] selectVolatileJobs(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_VOLATILE_JOBS)); + ps.setString(1, "1"); + //ps.setBoolean(1, true); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + String triggerName = rs.getString(COL_JOB_NAME); + String groupName = rs.getString(COL_JOB_GROUP); + list.add(new Key(triggerName, groupName)); + } + Object[] oArr = list.toArray(); + Key[] kArr = new Key[oArr.length]; + System.arraycopy(oArr, 0, kArr, 0, oArr.length); + return kArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + private static String toBooleanIntString(boolean theBoolean) { + if (String.valueOf(theBoolean).equals("true")) { + return "1"; + } else { + return "0"; + } + } + +} Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/DB2v8Delegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/DB2v8Delegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/DB2v8Delegate.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,551 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ +package org.quartz.impl.jdbcjobstore; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; + +import org.apache.commons.logging.Log; +import org.quartz.Calendar; +import org.quartz.CronTrigger; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.Scheduler; +import org.quartz.SimpleTrigger; +import org.quartz.Trigger; +import org.quartz.utils.Key; + +/** + * Quartz JDBC delegate for DB2 v8 databases. + * + * @author Blair Jensen + */ +public class DB2v8Delegate extends StdJDBCDelegate { + + public DB2v8Delegate(Log logger, String tablePrefix, String instanceId) { + super(logger, tablePrefix, instanceId); + } + + public DB2v8Delegate(Log log, String tablePrefix, String instanceId, + Boolean useProperties) { + super(log, tablePrefix, instanceId, useProperties); + } + + public Trigger[] selectTriggersForRecoveringJobs(Connection conn) + throws SQLException, IOException, ClassNotFoundException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn + .prepareStatement(rtp(SELECT_INSTANCES_RECOVERABLE_FIRED_TRIGGERS)); + ps.setString(1, instanceId); + ps.setInt(2, 1); + //ps.setBoolean(2, true); + rs = ps.executeQuery(); + + long dumId = System.currentTimeMillis(); + ArrayList list = new ArrayList(); + while (rs.next()) { + String jobName = rs.getString(COL_JOB_NAME); + String jobGroup = rs.getString(COL_JOB_GROUP); + String trigName = rs.getString(COL_TRIGGER_NAME); + String trigGroup = rs.getString(COL_TRIGGER_GROUP); + long firedTime = rs.getLong(COL_FIRED_TIME); + SimpleTrigger rcvryTrig = new SimpleTrigger("recover_" + + instanceId + "_" + String.valueOf(dumId++), + Scheduler.DEFAULT_RECOVERY_GROUP, new Date(firedTime)); + rcvryTrig.setJobName(jobName); + rcvryTrig.setJobGroup(jobGroup); + rcvryTrig + .setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW); + + JobDataMap jd = selectTriggerJobDataMap(conn, trigName, trigGroup); + jd.put("QRTZ_FAILED_JOB_ORIG_TRIGGER_NAME", trigName); + jd.put("QRTZ_FAILED_JOB_ORIG_TRIGGER_GROUP", trigGroup); + jd.put("QRTZ_FAILED_JOB_ORIG_TRIGGER_FIRETIME_IN_MILLISECONDS_AS_STRING", String.valueOf(firedTime)); + rcvryTrig.setJobDataMap(jd); + + list.add(rcvryTrig); + } + Object[] oArr = list.toArray(); + Trigger[] tArr = new Trigger[oArr.length]; + System.arraycopy(oArr, 0, tArr, 0, oArr.length); + return tArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int insertJobDetail(Connection conn, JobDetail job) + throws IOException, SQLException { + ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + + ps = conn.prepareStatement(rtp(INSERT_JOB_DETAIL)); + ps.setString(1, job.getName()); + ps.setString(2, job.getGroup()); + ps.setString(3, job.getDescription()); + ps.setString(4, job.getJobClass().getName()); + ps.setInt(5, toBooleanInt(job.isDurable())); + ps.setInt(6, toBooleanInt(job.isVolatile())); + ps.setInt(7, toBooleanInt(job.isStateful())); + ps.setInt(8, toBooleanInt(job.requestsRecovery())); + //ps.setBoolean (5, job.isDurable()); + //ps.setBoolean (6, job.isVolatile()); + //ps.setBoolean (7, job.isStateful()); + //ps.setBoolean (8, job.requestsRecovery()); + ps.setBytes(9, baos.toByteArray()); + //ps.setObject(9, baos.toByteArray(), Types.BLOB); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + String[] jobListeners = job.getJobListenerNames(); + for (int i = 0; jobListeners != null && i < jobListeners.length; i++) + insertJobListener(conn, job, jobListeners[i]); + } + + return insertResult; + } + + public int updateJobDetail(Connection conn, JobDetail job) + throws IOException, SQLException { + ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + ps = conn.prepareStatement(rtp(UPDATE_JOB_DETAIL)); + ps.setString(1, job.getDescription()); + ps.setString(2, job.getJobClass().getName()); + ps.setInt(3, toBooleanInt(job.isDurable())); + ps.setInt(4, toBooleanInt(job.isVolatile())); + ps.setInt(5, toBooleanInt(job.isStateful())); + ps.setInt(6, toBooleanInt(job.requestsRecovery())); + //ps.setBoolean (3, job.isDurable()); + //ps.setBoolean (4, job.isVolatile()); + //ps.setBoolean (5, job.isStateful()); + //ps.setBoolean (6, job.requestsRecovery()); + ps.setBytes (7, baos.toByteArray()); + //ps.setObject(7, baos.toByteArray(), java.sql.Types.BLOB); + ps.setString(8, job.getName()); + ps.setString(9, job.getGroup()); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + deleteJobListeners(conn, job.getName(), job.getGroup()); + + String[] jobListeners = job.getJobListenerNames(); + for (int i = 0; jobListeners != null && i < jobListeners.length; i++) + insertJobListener(conn, job, jobListeners[i]); + } + + return insertResult; + } + + public int insertTrigger(Connection conn, Trigger trigger, String state, + JobDetail jobDetail) throws SQLException, IOException { + ByteArrayOutputStream baos = serializeJobData(trigger.getJobDataMap()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + ps = conn.prepareStatement(rtp(INSERT_TRIGGER)); + ps.setString(1, trigger.getName()); + ps.setString(2, trigger.getGroup()); + ps.setString(3, trigger.getJobName()); + ps.setString(4, trigger.getJobGroup()); + ps.setInt(5, toBooleanInt(trigger.isVolatile())); + //ps.setBoolean(5, trigger.isVolatile()); + ps.setString(6, trigger.getDescription()); + ps.setBigDecimal(7, new BigDecimal(String.valueOf(trigger + .getNextFireTime().getTime()))); + long prevFireTime = -1; + if (trigger.getPreviousFireTime() != null) { + prevFireTime = trigger.getPreviousFireTime().getTime(); + } + ps.setBigDecimal(8, new BigDecimal(String.valueOf(prevFireTime))); + ps.setString(9, state); + if (trigger instanceof SimpleTrigger) { + ps.setString(10, TTYPE_SIMPLE); + } else if (trigger instanceof CronTrigger) { + ps.setString(10, TTYPE_CRON); + } else { // (trigger instanceof BlobTrigger) + ps.setString(10, TTYPE_BLOB); + } + ps.setBigDecimal(11, new BigDecimal(String.valueOf(trigger + .getStartTime().getTime()))); + long endTime = 0; + if (trigger.getEndTime() != null) { + endTime = trigger.getEndTime().getTime(); + } + ps.setBigDecimal(12, new BigDecimal(String.valueOf(endTime))); + ps.setString(13, trigger.getCalendarName()); + ps.setInt(14, trigger.getMisfireInstruction()); + ps.setBytes(15, baos.toByteArray()); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + String[] trigListeners = trigger.getTriggerListenerNames(); + for (int i = 0; trigListeners != null && i < trigListeners.length; i++) + insertTriggerListener(conn, trigger, trigListeners[i]); + } + + return insertResult; + } + + public int updateTrigger(Connection conn, Trigger trigger, String state, + JobDetail jobDetail) throws SQLException, IOException { + ByteArrayOutputStream baos = serializeJobData(trigger.getJobDataMap()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + ps = conn.prepareStatement(rtp(UPDATE_TRIGGER)); + ps.setString(1, trigger.getJobName()); + ps.setString(2, trigger.getJobGroup()); + ps.setInt(3, toBooleanInt(trigger.isVolatile())); + //ps.setBoolean(3, trigger.isVolatile()); + ps.setString(4, trigger.getDescription()); + long nextFireTime = -1; + if (trigger.getNextFireTime() != null) { + nextFireTime = trigger.getNextFireTime().getTime(); + } + ps.setBigDecimal(5, new BigDecimal(String.valueOf(nextFireTime))); + long prevFireTime = -1; + if (trigger.getPreviousFireTime() != null) { + prevFireTime = trigger.getPreviousFireTime().getTime(); + } + ps.setBigDecimal(6, new BigDecimal(String.valueOf(prevFireTime))); + ps.setString(7, state); + if (trigger instanceof SimpleTrigger) { + // updateSimpleTrigger(conn, (SimpleTrigger)trigger); + ps.setString(8, TTYPE_SIMPLE); + } else if (trigger instanceof CronTrigger) { + // updateCronTrigger(conn, (CronTrigger)trigger); + ps.setString(8, TTYPE_CRON); + } else { + // updateBlobTrigger(conn, trigger); + ps.setString(8, TTYPE_BLOB); + } + ps.setBigDecimal(9, new BigDecimal(String.valueOf(trigger + .getStartTime().getTime()))); + long endTime = 0; + if (trigger.getEndTime() != null) { + endTime = trigger.getEndTime().getTime(); + } + ps.setBigDecimal(10, new BigDecimal(String.valueOf(endTime))); + ps.setString(11, trigger.getCalendarName()); + ps.setInt(12, trigger.getMisfireInstruction()); + ps.setBytes (13, baos.toByteArray()); + ps.setString(14, trigger.getName()); + ps.setString(15, trigger.getGroup()); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + deleteTriggerListeners(conn, trigger.getName(), trigger.getGroup()); + + String[] trigListeners = trigger.getTriggerListenerNames(); + for (int i = 0; trigListeners != null && i < trigListeners.length; i++) + insertTriggerListener(conn, trigger, trigListeners[i]); + } + + return insertResult; + } + + public int insertFiredTrigger(Connection conn, Trigger trigger, + String state, JobDetail job) throws SQLException { + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(rtp(INSERT_FIRED_TRIGGER)); + ps.setString(1, trigger.getFireInstanceId()); + ps.setString(2, trigger.getName()); + ps.setString(3, trigger.getGroup()); + ps.setInt(4, toBooleanInt(trigger.isVolatile())); + //ps.setBoolean(4, trigger.isVolatile()); + ps.setString(5, instanceId); + ps.setBigDecimal(6, new BigDecimal(String.valueOf(trigger + .getNextFireTime().getTime()))); + ps.setString(7, state); + if (job != null) { + ps.setString(8, trigger.getJobName()); + ps.setString(9, trigger.getJobGroup()); + ps.setInt(10, toBooleanInt(job.isStateful())); + ps.setInt(11, toBooleanInt(job.requestsRecovery())); + //ps.setBoolean(10, job.isStateful()); + //ps.setBoolean(11, job.requestsRecovery()); + } else { + ps.setString(8, null); + ps.setString(9, null); + ps.setInt(10, 0); + ps.setInt(11, 0); + //ps.setBoolean(10, false); + //ps.setBoolean(11, false); + } + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int updateJobData(Connection conn, JobDetail job) + throws IOException, SQLException { + ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap()); + + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_JOB_DATA)); + ps.setBytes(1, baos.toByteArray()); + //ps.setObject(1, baos.toByteArray(), java.sql.Types.BLOB); + ps.setString(2, job.getName()); + ps.setString(3, job.getGroup()); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int insertCalendar(Connection conn, String calendarName, + Calendar calendar) throws IOException, SQLException { + ByteArrayOutputStream baos = serializeObject(calendar); + + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(INSERT_CALENDAR)); + ps.setString(1, calendarName); + ps.setBytes(2, baos.toByteArray()); + //ps.setObject(2, baos.toByteArray(), java.sql.Types.BLOB); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int updateCalendar(Connection conn, String calendarName, + Calendar calendar) throws IOException, SQLException { + ByteArrayOutputStream baos = serializeObject(calendar); + + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_CALENDAR)); + ps.setBytes(1, baos.toByteArray()); + ps.setString(2, calendarName); + //ps.setObject(2, calendar, java.sql.Types.BLOB); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int deleteVolatileFiredTriggers(Connection conn) throws SQLException { + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(rtp(DELETE_VOLATILE_FIRED_TRIGGERS)); + ps.setInt(1, 1); + //ps.setBoolean(1, true); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public Key[] selectVolatileTriggers(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_VOLATILE_TRIGGERS)); + ps.setInt(1, 1); // boolean true + //ps.setBoolean(1, true); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + String triggerName = rs.getString(COL_TRIGGER_NAME); + String groupName = rs.getString(COL_TRIGGER_GROUP); + list.add(new Key(triggerName, groupName)); + } + Object[] oArr = list.toArray(); + Key[] kArr = new Key[oArr.length]; + System.arraycopy(oArr, 0, kArr, 0, oArr.length); + return kArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public Key[] selectVolatileJobs(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_VOLATILE_JOBS)); + ps.setInt(1, 1); + //ps.setBoolean(1, true); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + String triggerName = rs.getString(COL_JOB_NAME); + String groupName = rs.getString(COL_JOB_GROUP); + list.add(new Key(triggerName, groupName)); + } + Object[] oArr = list.toArray(); + Key[] kArr = new Key[oArr.length]; + System.arraycopy(oArr, 0, kArr, 0, oArr.length); + return kArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + +// private static String toBooleanIntString(boolean theBoolean) { +// if (String.valueOf(theBoolean).equals("true")) { +// return "1"; +// } else { +// return "0"; +// } +// } +// + private static int toBooleanInt(boolean theBoolean) { + if (String.valueOf(theBoolean).equals("true")) { + return 1; + } else { + return 0; + } + } +} Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/DriverDelegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/DriverDelegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/DriverDelegate.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,1371 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Set; + +import org.quartz.Calendar; +import org.quartz.CronTrigger; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.SimpleTrigger; +import org.quartz.Trigger; +import org.quartz.spi.ClassLoadHelper; +import org.quartz.utils.Key; +import org.quartz.utils.TriggerStatus; + +/** + *

+ * This is the base interface for all driver delegate classes. + *

+ * + *

+ * This interface is very similar to the {@link + * org.quartz.spi.JobStore} + * interface except each method has an additional {@link java.sql.Connection} + * parameter. + *

+ * + *

+ * Unless a database driver has some extremely-DB-specific + * requirements, any DriverDelegate implementation classes should extend the + * {@link org.quartz.impl.jdbcjobstore.StdJDBCDelegate} class. + *

+ * + * @author Jeffrey Wescott + * @author James House + */ +public interface DriverDelegate { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + //--------------------------------------------------------------------------- + // startup / recovery + //--------------------------------------------------------------------------- + /** + *

+ * Update all triggers having one of the two given states, to the given new + * state. + *

+ * + * @param conn + * the DB Connection + * @param newState + * the new state for the triggers + * @param oldState1 + * the first old state to update + * @param oldState2 + * the second old state to update + * @return number of rows updated + */ + public int updateTriggerStatesFromOtherStates(Connection conn, + String newState, String oldState1, String oldState2) + throws SQLException; + + /** + *

+ * Get the names of all of the triggers that have misfired - according to + * the given timestamp. + *

+ * + * @param conn + * the DB Connection + * @return an array of {@link + * org.quartz.utils.Key} objects + */ + public Key[] selectMisfiredTriggers(Connection conn, long ts) + throws SQLException; + + /** + *

+ * Get the names of all of the triggers in the given state that have + * misfired - according to the given timestamp. + *

+ * + * @param conn + * the DB Connection + * @return an array of {@link + * org.quartz.utils.Key} objects + */ + public Key[] selectMisfiredTriggersInState(Connection conn, String state, + long ts) throws SQLException; + + /** + *

+ * Get the names of all of the triggers in the given group and state that + * have misfired - according to the given timestamp. + *

+ * + * @param conn + * the DB Connection + * @return an array of {@link + * org.quartz.utils.Key} objects + */ + public Key[] selectMisfiredTriggersInGroupInState(Connection conn, + String groupName, String state, long ts) throws SQLException; + + /** + *

+ * Select all of the triggers for jobs that are requesting recovery. The + * returned trigger objects will have unique "recoverXXX" trigger names and + * will be in the {@link + * org.quartz.Scheduler}.DEFAULT_RECOVERY_GROUP + * trigger group. + *

+ * + *

+ * In order to preserve the ordering of the triggers, the fire time will be + * set from the COL_FIRED_TIME column in the TABLE_FIRED_TRIGGERS + * table. The caller is responsible for calling computeFirstFireTime + * on each returned trigger. It is also up to the caller to insert the + * returned triggers to ensure that they are fired. + *

+ * + * @param conn + * the DB Connection + * @return an array of {@link org.quartz.Trigger} objects + */ + public Trigger[] selectTriggersForRecoveringJobs(Connection conn) + throws SQLException, IOException, ClassNotFoundException; + + /** + *

+ * Delete all fired triggers. + *

+ * + * @param conn + * the DB Connection + * @return the number of rows deleted + */ + public int deleteFiredTriggers(Connection conn) throws SQLException; + + /** + *

+ * Delete all fired triggers of the given instance. + *

+ * + * @param conn + * the DB Connection + * @return the number of rows deleted + */ + public int deleteFiredTriggers(Connection conn, String instanceId) + throws SQLException; + + /** + *

+ * Delete all volatile fired triggers. + *

+ * + * @param conn + * the DB Connection + * @return the number of rows deleted + */ + public int deleteVolatileFiredTriggers(Connection conn) throws SQLException; + + /** + *

+ * Get the names of all of the triggers that are volatile. + *

+ * + * @param conn + * the DB Connection + * @return an array of {@link + * org.quartz.utils.Key} objects + */ + public Key[] selectVolatileTriggers(Connection conn) throws SQLException; + + /** + *

+ * Get the names of all of the jobs that are volatile. + *

+ * + * @param conn + * the DB Connection + * @return an array of {@link + * org.quartz.utils.Key} objects + */ + public Key[] selectVolatileJobs(Connection conn) throws SQLException; + + //--------------------------------------------------------------------------- + // jobs + //--------------------------------------------------------------------------- + + /** + *

+ * Insert the job detail record. + *

+ * + * @param conn + * the DB Connection + * @param job + * the job to insert + * @return number of rows inserted + * @throws IOException + * if there were problems serializing the JobDataMap + */ + public int insertJobDetail(Connection conn, JobDetail job) + throws IOException, SQLException; + + /** + *

+ * Update the job detail record. + *

+ * + * @param conn + * the DB Connection + * @param job + * the job to update + * @return number of rows updated + * @throws IOException + * if there were problems serializing the JobDataMap + */ + public int updateJobDetail(Connection conn, JobDetail job) + throws IOException, SQLException; + + /** + *

+ * Get the names of all of the triggers associated with the given job. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the job name + * @param groupName + * the job group + * @return an array of {@link + * org.quartz.utils.Key} objects + */ + public Key[] selectTriggerNamesForJob(Connection conn, String jobName, + String groupName) throws SQLException; + + /** + *

+ * Delete all job listeners for the given job. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @return the number of rows deleted + */ + public int deleteJobListeners(Connection conn, String jobName, + String groupName) throws SQLException; + + /** + *

+ * Delete the job detail record for the given job. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @return the number of rows deleted + */ + public int deleteJobDetail(Connection conn, String jobName, String groupName) + throws SQLException; + + /** + *

+ * Check whether or not the given job is stateful. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @return true if the job exists and is stateful, false otherwise + */ + public boolean isJobStateful(Connection conn, String jobName, + String groupName) throws SQLException; + + /** + *

+ * Check whether or not the given job exists. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @return true if the job exists, false otherwise + */ + public boolean jobExists(Connection conn, String jobName, String groupName) + throws SQLException; + + /** + *

+ * Update the job data map for the given job. + *

+ * + * @param conn + * the DB Connection + * @param job + * the job to update + * @return the number of rows updated + * @throws IOException + * if there were problems serializing the JobDataMap + */ + public int updateJobData(Connection conn, JobDetail job) + throws IOException, SQLException; + + /** + *

+ * Associate a listener with a job. + *

+ * + * @param conn + * the DB Connection + * @param job + * the job to associate with the listener + * @param listener + * the listener to insert + * @return the number of rows inserted + */ + public int insertJobListener(Connection conn, JobDetail job, String listener) + throws SQLException; + + /** + *

+ * Get all of the listeners for a given job. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the job name whose listeners are wanted + * @param groupName + * the group containing the job + * @return array of String listener names + */ + public String[] selectJobListeners(Connection conn, String jobName, + String groupName) throws SQLException; + + /** + *

+ * Select the JobDetail object for a given job name / group name. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the job name whose listeners are wanted + * @param groupName + * the group containing the job + * @return the populated JobDetail object + * @throws ClassNotFoundException + * if a class found during deserialization cannot be found or if + * the job class could not be found + * @throws IOException + * if deserialization causes an error + */ + public JobDetail selectJobDetail(Connection conn, String jobName, + String groupName, ClassLoadHelper loadHelper) + throws ClassNotFoundException, IOException, SQLException; + + /** + *

+ * Select the total number of jobs stored. + *

+ * + * @param conn + * the DB Connection + * @return the total number of jobs stored + */ + public int selectNumJobs(Connection conn) throws SQLException; + + /** + *

+ * Select all of the job group names that are stored. + *

+ * + * @param conn + * the DB Connection + * @return an array of String group names + */ + public String[] selectJobGroups(Connection conn) throws SQLException; + + /** + *

+ * Select all of the jobs contained in a given group. + *

+ * + * @param conn + * the DB Connection + * @param groupName + * the group containing the jobs + * @return an array of String job names + */ + public String[] selectJobsInGroup(Connection conn, String groupName) + throws SQLException; + + //--------------------------------------------------------------------------- + // triggers + //--------------------------------------------------------------------------- + + /** + *

+ * Insert the base trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @param state + * the state that the trigger should be stored in + * @return the number of rows inserted + */ + public int insertTrigger(Connection conn, Trigger trigger, String state, + JobDetail jobDetail) throws SQLException, IOException; + + /** + *

+ * Insert the simple trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @return the number of rows inserted + */ + public int insertSimpleTrigger(Connection conn, SimpleTrigger trigger) + throws SQLException; + + /** + *

+ * Insert the blob trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @return the number of rows inserted + */ + public int insertBlobTrigger(Connection conn, Trigger trigger) + throws SQLException, IOException; + + /** + *

+ * Insert the cron trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @return the number of rows inserted + */ + public int insertCronTrigger(Connection conn, CronTrigger trigger) + throws SQLException; + + /** + *

+ * Update the base trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @param state + * the state that the trigger should be stored in + * @return the number of rows updated + */ + public int updateTrigger(Connection conn, Trigger trigger, String state, + JobDetail jobDetail) throws SQLException, IOException; + + /** + *

+ * Update the simple trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @return the number of rows updated + */ + public int updateSimpleTrigger(Connection conn, SimpleTrigger trigger) + throws SQLException; + + /** + *

+ * Update the cron trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @return the number of rows updated + */ + public int updateCronTrigger(Connection conn, CronTrigger trigger) + throws SQLException; + + /** + *

+ * Update the blob trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @return the number of rows updated + */ + public int updateBlobTrigger(Connection conn, Trigger trigger) + throws SQLException, IOException; + + /** + *

+ * Check whether or not a trigger exists. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the number of rows updated + */ + public boolean triggerExists(Connection conn, String triggerName, + String groupName) throws SQLException; + + /** + *

+ * Update the state for a given trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @param state + * the new state for the trigger + * @return the number of rows updated + */ + public int updateTriggerState(Connection conn, String triggerName, + String groupName, String state) throws SQLException; + + /** + *

+ * Update the given trigger to the given new state, if it is in the given + * old state. + *

+ * + * @param conn + * the DB connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @param newState + * the new state for the trigger + * @param oldState + * the old state the trigger must be in + * @return int the number of rows updated + * @throws SQLException + */ + public int updateTriggerStateFromOtherState(Connection conn, + String triggerName, String groupName, String newState, + String oldState) throws SQLException; + + /** + *

+ * Update the given trigger to the given new state, if it is one of the + * given old states. + *

+ * + * @param conn + * the DB connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @param newState + * the new state for the trigger + * @param oldState1 + * one of the old state the trigger must be in + * @param oldState2 + * one of the old state the trigger must be in + * @param oldState3 + * one of the old state the trigger must be in + * @return int the number of rows updated + * @throws SQLException + */ + public int updateTriggerStateFromOtherStates(Connection conn, + String triggerName, String groupName, String newState, + String oldState1, String oldState2, String oldState3) + throws SQLException; + + /** + *

+ * Update the all triggers to the given new state, if they are in one of + * the given old states AND its next fire time is before the given time. + *

+ * + * @param conn + * the DB connection + * @param newState + * the new state for the trigger + * @param oldState1 + * one of the old state the trigger must be in + * @param oldState2 + * one of the old state the trigger must be in + * @param time + * the time before which the trigger's next fire time must be + * @return int the number of rows updated + * @throws SQLException + */ + public int updateTriggerStateFromOtherStatesBeforeTime(Connection conn, + String newState, String oldState1, String oldState2, long time) + throws SQLException; + + /** + *

+ * Update all triggers in the given group to the given new state, if they + * are in one of the given old states. + *

+ * + * @param conn + * the DB connection + * @param groupName + * the group containing the trigger + * @param newState + * the new state for the trigger + * @param oldState1 + * one of the old state the trigger must be in + * @param oldState2 + * one of the old state the trigger must be in + * @param oldState3 + * one of the old state the trigger must be in + * @return int the number of rows updated + * @throws SQLException + */ + public int updateTriggerGroupStateFromOtherStates(Connection conn, + String groupName, String newState, String oldState1, + String oldState2, String oldState3) throws SQLException; + + /** + *

+ * Update all of the triggers of the given group to the given new state, if + * they are in the given old state. + *

+ * + * @param conn + * the DB connection + * @param groupName + * the group containing the triggers + * @param newState + * the new state for the trigger group + * @param oldState + * the old state the triggers must be in + * @return int the number of rows updated + * @throws SQLException + */ + public int updateTriggerGroupStateFromOtherState(Connection conn, + String groupName, String newState, String oldState) + throws SQLException; + + /** + *

+ * Update the states of all triggers associated with the given job. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @param state + * the new state for the triggers + * @return the number of rows updated + */ + public int updateTriggerStatesForJob(Connection conn, String jobName, + String groupName, String state) throws SQLException; + + /** + *

+ * Update the states of any triggers associated with the given job, that + * are the given current state. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @param state + * the new state for the triggers + * @param oldState + * the old state of the triggers + * @return the number of rows updated + */ + public int updateTriggerStatesForJobFromOtherState(Connection conn, + String jobName, String groupName, String state, String oldState) + throws SQLException; + + /** + *

+ * Delete all of the listeners associated with a given trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger whose listeners will be deleted + * @param groupName + * the name of the group containing the trigger + * @return the number of rows deleted + */ + public int deleteTriggerListeners(Connection conn, String triggerName, + String groupName) throws SQLException; + + /** + *

+ * Associate a listener with the given trigger. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger + * @param listener + * the name of the listener to associate with the trigger + * @return the number of rows inserted + */ + public int insertTriggerListener(Connection conn, Trigger trigger, + String listener) throws SQLException; + + /** + *

+ * Select the listeners associated with a given trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return array of String trigger listener names + */ + public String[] selectTriggerListeners(Connection conn, String triggerName, + String groupName) throws SQLException; + + /** + *

+ * Delete the simple trigger data for a trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the number of rows deleted + */ + public int deleteSimpleTrigger(Connection conn, String triggerName, + String groupName) throws SQLException; + + /** + *

+ * Delete the BLOB trigger data for a trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the number of rows deleted + */ + public int deleteBlobTrigger(Connection conn, String triggerName, + String groupName) throws SQLException; + + /** + *

+ * Delete the cron trigger data for a trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the number of rows deleted + */ + public int deleteCronTrigger(Connection conn, String triggerName, + String groupName) throws SQLException; + + /** + *

+ * Delete the base trigger data for a trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the number of rows deleted + */ + public int deleteTrigger(Connection conn, String triggerName, + String groupName) throws SQLException; + + /** + *

+ * Select the number of triggers associated with a given job. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @return the number of triggers for the given job + */ + public int selectNumTriggersForJob(Connection conn, String jobName, + String groupName) throws SQLException; + + /** + *

+ * Select the job to which the trigger is associated. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the {@link org.quartz.JobDetail} object + * associated with the given trigger + */ + public JobDetail selectJobForTrigger(Connection conn, String triggerName, + String groupName, ClassLoadHelper loadHelper) + throws ClassNotFoundException, SQLException; + + /** + *

+ * Select the stateful jobs which are referenced by triggers in the given + * trigger group. + *

+ * + * @param conn + * the DB Connection + * @param groupName + * the trigger group + * @return a List of Keys to jobs. + */ + public List selectStatefulJobsOfTriggerGroup(Connection conn, + String groupName) throws SQLException; + + /** + *

+ * Select the triggers for a job + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return an array of (@link org.quartz.Trigger) objects + * associated with a given job. + * @throws SQLException + */ + public Trigger[] selectTriggersForJob(Connection conn, String jobName, + String groupName) throws SQLException, ClassNotFoundException, + IOException; + + /** + *

+ * Select the triggers for a calendar + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return an array of (@link org.quartz.Trigger) objects + * associated with a given job. + * @throws SQLException + */ + public Trigger[] selectTriggersForCalendar(Connection conn, String calName) + throws SQLException, ClassNotFoundException, IOException; + /** + *

+ * Select a trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the {@link org.quartz.Trigger} object + */ + public Trigger selectTrigger(Connection conn, String triggerName, + String groupName) throws SQLException, ClassNotFoundException, + IOException; + + /** + *

+ * Select a trigger's JobDataMap. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the {@link org.quartz.JobDataMap} of the Trigger, + * never null, but possibly empty. + */ + public JobDataMap selectTriggerJobDataMap(Connection conn, String triggerName, + String groupName) throws SQLException, ClassNotFoundException, + IOException; + + /** + *

+ * Select a trigger' state value. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the {@link org.quartz.Trigger} object + */ + public String selectTriggerState(Connection conn, String triggerName, + String groupName) throws SQLException; + + /** + *

+ * Select a trigger' status (state & next fire time). + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return a TriggerStatus object, or null + */ + public TriggerStatus selectTriggerStatus(Connection conn, + String triggerName, String groupName) throws SQLException; + + /** + *

+ * Select the total number of triggers stored. + *

+ * + * @param conn + * the DB Connection + * @return the total number of triggers stored + */ + public int selectNumTriggers(Connection conn) throws SQLException; + + /** + *

+ * Select all of the trigger group names that are stored. + *

+ * + * @param conn + * the DB Connection + * @return an array of String group names + */ + public String[] selectTriggerGroups(Connection conn) throws SQLException; + + /** + *

+ * Select all of the triggers contained in a given group. + *

+ * + * @param conn + * the DB Connection + * @param groupName + * the group containing the triggers + * @return an array of String trigger names + */ + public String[] selectTriggersInGroup(Connection conn, String groupName) + throws SQLException; + + /** + *

+ * Select all of the triggers in a given state. + *

+ * + * @param conn + * the DB Connection + * @param state + * the state the triggers must be in + * @return an array of trigger Key s + */ + public Key[] selectTriggersInState(Connection conn, String state) + throws SQLException; + + public int insertPausedTriggerGroup(Connection conn, String groupName) + throws SQLException; + + public int deletePausedTriggerGroup(Connection conn, String groupName) + throws SQLException; + + public int deleteAllPausedTriggerGroups(Connection conn) + throws SQLException; + + public boolean isTriggerGroupPaused(Connection conn, String groupName) + throws SQLException; + + public Set selectPausedTriggerGroups(Connection conn) + throws SQLException; + + public boolean isExistingTriggerGroup(Connection conn, String groupName) + throws SQLException; + + //--------------------------------------------------------------------------- + // calendars + //--------------------------------------------------------------------------- + + /** + *

+ * Insert a new calendar. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name for the new calendar + * @param calendar + * the calendar + * @return the number of rows inserted + * @throws IOException + * if there were problems serializing the calendar + */ + public int insertCalendar(Connection conn, String calendarName, + Calendar calendar) throws IOException, SQLException; + + /** + *

+ * Update a calendar. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name for the new calendar + * @param calendar + * the calendar + * @return the number of rows updated + * @throws IOException + * if there were problems serializing the calendar + */ + public int updateCalendar(Connection conn, String calendarName, + Calendar calendar) throws IOException, SQLException; + + /** + *

+ * Check whether or not a calendar exists. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name of the calendar + * @return true if the trigger exists, false otherwise + */ + public boolean calendarExists(Connection conn, String calendarName) + throws SQLException; + + /** + *

+ * Select a calendar. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name of the calendar + * @return the Calendar + * @throws ClassNotFoundException + * if a class found during deserialization cannot be found be + * found + * @throws IOException + * if there were problems deserializing the calendar + */ + public Calendar selectCalendar(Connection conn, String calendarName) + throws ClassNotFoundException, IOException, SQLException; + + /** + *

+ * Check whether or not a calendar is referenced by any triggers. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name of the calendar + * @return true if any triggers reference the calendar, false otherwise + */ + public boolean calendarIsReferenced(Connection conn, String calendarName) + throws SQLException; + + /** + *

+ * Delete a calendar. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name of the trigger + * @return the number of rows deleted + */ + public int deleteCalendar(Connection conn, String calendarName) + throws SQLException; + + /** + *

+ * Select the total number of calendars stored. + *

+ * + * @param conn + * the DB Connection + * @return the total number of calendars stored + */ + public int selectNumCalendars(Connection conn) throws SQLException; + + /** + *

+ * Select all of the stored calendars. + *

+ * + * @param conn + * the DB Connection + * @return an array of String calendar names + */ + public String[] selectCalendars(Connection conn) throws SQLException; + + //--------------------------------------------------------------------------- + // trigger firing + //--------------------------------------------------------------------------- + + /** + *

+ * Select the next time that a trigger will be fired. + *

+ * + * @param conn + * the DB Connection + * @return the next fire time, or 0 if no trigger will be fired + */ + public long selectNextFireTime(Connection conn) throws SQLException; + + /** + *

+ * Select the trigger that will be fired at the given fire time. + *

+ * + * @param conn + * the DB Connection + * @param fireTime + * the time that the trigger will be fired + * @return a {@link org.quartz.utils.Key} representing the + * trigger that will be fired at the given fire time, or null if no + * trigger will be fired at that time + */ + public Key selectTriggerForFireTime(Connection conn, long fireTime) + throws SQLException; + + /** + *

+ * Insert a fired trigger. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger + * @param state + * the state that the trigger should be stored in + * @return the number of rows inserted + */ + public int insertFiredTrigger(Connection conn, Trigger trigger, + String state, JobDetail jobDetail) throws SQLException; + + /** + *

+ * Select the states of all fired-trigger records for a given trigger, or + * trigger group if trigger name is null. + *

+ * + * @return a List of FiredTriggerRecord objects. + */ + public List selectFiredTriggerRecords(Connection conn, String triggerName, + String groupName) throws SQLException; + + /** + *

+ * Select the states of all fired-trigger records for a given job, or job + * group if job name is null. + *

+ * + * @return a List of FiredTriggerRecord objects. + */ + public List selectFiredTriggerRecordsByJob(Connection conn, String jobName, + String groupName) throws SQLException; + + /** + *

+ * Select the states of all fired-trigger records for a given scheduler + * instance. + *

+ * + * @return a List of FiredTriggerRecord objects. + */ + public List selectInstancesFiredTriggerRecords(Connection conn, + String instanceName) throws SQLException; + + /** + *

+ * Delete a fired trigger. + *

+ * + * @param conn + * the DB Connection + * @param entryId + * the fired trigger entry to delete + * @return the number of rows deleted + */ + public int deleteFiredTrigger(Connection conn, String entryId) + throws SQLException; + + /** + *

+ * Get the number instances of the identified job currently executing. + *

+ * + * @param conn + * the DB Connection + * @return the number instances of the identified job currently executing. + */ + public int selectJobExecutionCount(Connection conn, String jobName, + String jobGroup) throws SQLException; + + /** + *

+ * Insert a scheduler-instance state record. + *

+ * + * @param conn + * the DB Connection + * @return the number of inserted rows. + */ + public int insertSchedulerState(Connection conn, String instanceId, + long checkInTime, long interval, String recoverer) + throws SQLException; + + /** + *

+ * Delete a scheduler-instance state record. + *

+ * + * @param conn + * the DB Connection + * @return the number of deleted rows. + */ + public int deleteSchedulerState(Connection conn, String instanceId) + throws SQLException; + + + /** + *

+ * Update a scheduler-instance state record. + *

+ * + * @param conn + * the DB Connection + * @return the number of updated rows. + */ + public int updateSchedulerState(Connection conn, String instanceId, long checkInTime, String recoverer) + throws SQLException; + + /** + *

+ * A List of all current SchedulerStateRecords. + *

+ * + *

+ * If instanceId is not null, then only the record for the identified + * instance will be returned. + *

+ * + * @param conn + * the DB Connection + */ + public List selectSchedulerStateRecords(Connection conn, String instanceId) // TODO: this method would be more handy if it returned a map. + throws SQLException; + +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/FiredTriggerRecord.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/FiredTriggerRecord.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/FiredTriggerRecord.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,142 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import org.quartz.utils.Key; + +/** + *

+ * Conveys the state of a fired-trigger record. + *

+ * + * @author James House + */ +public class FiredTriggerRecord implements java.io.Serializable { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private String fireInstanceId; + + private long fireTimestamp; + + private String schedulerInstanceId; + + private Key triggerKey; + + private String fireInstanceState; + + private boolean triggerIsVolatile; + + private Key jobKey; + + private boolean jobIsStateful; + + private boolean jobRequestsRecovery; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public String getFireInstanceId() { + return fireInstanceId; + } + + public long getFireTimestamp() { + return fireTimestamp; + } + + public boolean isJobIsStateful() { + return jobIsStateful; + } + + public Key getJobKey() { + return jobKey; + } + + public String getSchedulerInstanceId() { + return schedulerInstanceId; + } + + public Key getTriggerKey() { + return triggerKey; + } + + public String getFireInstanceState() { + return fireInstanceState; + } + + public void setFireInstanceId(String string) { + fireInstanceId = string; + } + + public void setFireTimestamp(long l) { + fireTimestamp = l; + } + + public void setJobIsStateful(boolean b) { + jobIsStateful = b; + } + + public void setJobKey(Key key) { + jobKey = key; + } + + public void setSchedulerInstanceId(String string) { + schedulerInstanceId = string; + } + + public void setTriggerKey(Key key) { + triggerKey = key; + } + + public void setFireInstanceState(String string) { + fireInstanceState = string; + } + + public boolean isJobRequestsRecovery() { + return jobRequestsRecovery; + } + + public boolean isTriggerIsVolatile() { + return triggerIsVolatile; + } + + public void setJobRequestsRecovery(boolean b) { + jobRequestsRecovery = b; + } + + public void setTriggerIsVolatile(boolean b) { + triggerIsVolatile = b; + } + +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/HSQLDBDelegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/HSQLDBDelegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/HSQLDBDelegate.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,116 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.apache.commons.logging.Log; + +/** + *

+ * This is a driver delegate for the HSQLDB database. + *

+ * + * @author James House + * @author Jeffrey Wescott + */ +public class HSQLDBDelegate extends StdJDBCDelegate { + /** + *

+ * Create new HSQLDBDelegate instance. + *

+ * + * @param logger + * the logger to use during execution + * @param tablePrefix + * the prefix of all table names + */ + public HSQLDBDelegate(Log log, String tablePrefix, String instanceId) { + super(log, tablePrefix, instanceId); + } + + /** + *

+ * Create new MSSQLDelegate instance. + *

+ * + * @param logger + * the logger to use during execution + * @param tablePrefix + * the prefix of all table names + * @param useProperties + * use java.util.Properties for storage + */ + public HSQLDBDelegate(Log log, String tablePrefix, String instanceId, + Boolean useProperties) { + super(log, tablePrefix, instanceId, useProperties); + } + + //--------------------------------------------------------------------------- + // protected methods that can be overridden by subclasses + //--------------------------------------------------------------------------- + + /** + *

+ * This method should be overridden by any delegate subclasses that need + * special handling for BLOBs. The default implementation uses standard + * JDBC java.sql.Blob operations. + *

+ * + * @param rs + * the result set, already queued to the correct row + * @param colName + * the column name for the BLOB + * @return the deserialized Object from the ResultSet BLOB + * @throws ClassNotFoundException + * if a class found during deserialization cannot be found + * @throws IOException + * if deserialization causes an error + */ + protected Object getObjectFromBlob(ResultSet rs, String colName) + throws ClassNotFoundException, IOException, SQLException { + InputStream binaryInput = rs.getBinaryStream(colName); + + if(binaryInput == null) + return null; + + ObjectInputStream in = new ObjectInputStream(binaryInput); + Object obj = in.readObject(); + in.close(); + + return obj; + } + + protected Object getJobDetailFromBlob(ResultSet rs, String colName) + throws ClassNotFoundException, IOException, SQLException { + if (canUseProperties()) { + InputStream binaryInput = rs.getBinaryStream(colName); + return binaryInput; + } + return getObjectFromBlob(rs, colName); + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/InvalidConfigurationException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/InvalidConfigurationException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/InvalidConfigurationException.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +/** + *

+ * Exception class for when a driver delegate cannot be found for a given + * configuration, or lack thereof. + *

+ * + * @author Jeffrey Wescott + */ +public class InvalidConfigurationException extends Exception { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public InvalidConfigurationException(String msg) { + super(msg); + } + + public InvalidConfigurationException() { + super(); + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/JobStoreCMT.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/JobStoreCMT.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/JobStoreCMT.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,1469 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Set; + +import org.quartz.Calendar; +import org.quartz.JobDetail; +import org.quartz.JobPersistenceException; +import org.quartz.ObjectAlreadyExistsException; +import org.quartz.SchedulerConfigException; +import org.quartz.SchedulerException; +import org.quartz.Trigger; +import org.quartz.core.SchedulingContext; +import org.quartz.spi.ClassLoadHelper; +import org.quartz.spi.SchedulerSignaler; +import org.quartz.spi.TriggerFiredBundle; +import org.quartz.utils.DBConnectionManager; + +/** + *

+ * JobStoreCMT is meant to be used in an application-server + * environment that provides container-managed-transactions. No commit / + * rollback will be1 handled by this class. + *

+ * + *

+ * If you need commit / rollback, use {@link + * org.quartz.impl.jdbcjobstore.JobStoreTX} + * instead. + *

+ * + * @author Jeffrey Wescott + * @author James House + * @author Srinivas Venkatarangaiah + * + */ +public class JobStoreCMT extends JobStoreSupport { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected String nonManagedTxDsName; + + // Great name huh? + protected boolean dontSetNonManagedTXConnectionAutoCommitFalse = false; + + + protected boolean setTxIsolationLevelReadCommitted = false; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Set the name of the DataSource that should be used for + * performing database functions. + *

+ */ + public void setNonManagedTXDataSource(String nonManagedTxDsName) { + this.nonManagedTxDsName = nonManagedTxDsName; + } + + /** + *

+ * Get the name of the DataSource that should be used for + * performing database functions. + *

+ */ + public String getNonManagedTXDataSource() { + return nonManagedTxDsName; + } + + public boolean isDontSetNonManagedTXConnectionAutoCommitFalse() { + return dontSetNonManagedTXConnectionAutoCommitFalse; + } + + /** + * Don't call set autocommit(false) on connections obtained from the + * DataSource. This can be helpfull in a few situations, such as if you + * have a driver that complains if it is called when it is already off. + * + * @param b + */ + public void setDontSetNonManagedTXConnectionAutoCommitFalse(boolean b) { + dontSetNonManagedTXConnectionAutoCommitFalse = b; + } + + + public boolean isTxIsolationLevelReadCommitted() { + return setTxIsolationLevelReadCommitted; + } + + /** + * Set the transaction isolation level of DB connections to sequential. + * + * @param b + */ + public void setTxIsolationLevelReadCommitted(boolean b) { + setTxIsolationLevelReadCommitted = b; + } + + + public void initialize(ClassLoadHelper loadHelper, + SchedulerSignaler signaler) throws SchedulerConfigException { + + if (nonManagedTxDsName == null) + throw new SchedulerConfigException( + "Non-ManagedTX DataSource name not set!"); + + setUseDBLocks(true); // *must* use DB locks with CMT... + + super.initialize(loadHelper, signaler); + + getLog().info("JobStoreCMT initialized."); + } + + public void shutdown() { + + super.shutdown(); + + try { + DBConnectionManager.getInstance().shutdown(getNonManagedTXDataSource()); + } catch (SQLException sqle) { + getLog().warn("Database connection shutdown unsuccessful.", sqle); + } + } + + + //--------------------------------------------------------------------------- + // JobStoreSupport methods + //--------------------------------------------------------------------------- + + /** + *

+ * Recover any failed or misfired jobs and clean up the data store as + * appropriate. + *

+ * + * @throws JobPersistenceException + * if jobs could not be recovered + */ + protected void recoverJobs() throws JobPersistenceException { + Connection conn = null; + + boolean transOwner = false; + + try { + conn = getNonManagedTXConnection(); + + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + recoverJobs(conn); + + conn.commit(); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } catch (Exception e) { + rollbackConnection(conn); + throw new JobPersistenceException("Error recovering jobs: " + + e.getMessage(), e); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + protected void cleanVolatileTriggerAndJobs() throws JobPersistenceException { + Connection conn = null; + + boolean transOwner = false; + + try { + conn = getNonManagedTXConnection(); + + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + cleanVolatileTriggerAndJobs(conn); + + conn.commit(); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } catch (Exception e) { + rollbackConnection(conn); + throw new JobPersistenceException("Error cleaning volatile data: " + + e.getMessage(), e); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + //--------------------------------------------------------------------------- + // job / trigger storage methods + //--------------------------------------------------------------------------- + + /** + *

+ * Store the given {@link org.quartz.JobDetail} and {@link org.quartz.Trigger}. + *

+ * + * @param newJob + * The JobDetail to be stored. + * @param newTrigger + * The Trigger to be stored. + * @throws ObjectAlreadyExistsException + * if a Job with the same name/group already + * exists. + */ + public void storeJobAndTrigger(SchedulingContext ctxt, JobDetail newJob, + Trigger newTrigger) throws ObjectAlreadyExistsException, + JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + if(isLockOnInsert()) { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + } + + if (newJob.isVolatile() && !newTrigger.isVolatile()) { + JobPersistenceException jpe = new JobPersistenceException( + "Cannot associate non-volatile " + + "trigger with a volatile job!"); + jpe.setErrorCode(SchedulerException.ERR_CLIENT_ERROR); + throw jpe; + } + + storeJob(conn, ctxt, newJob, false); + storeTrigger(conn, ctxt, newTrigger, newJob, false, + Constants.STATE_WAITING, false, false); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Store the given {@link org.quartz.JobDetail}. + *

+ * + * @param newJob + * The JobDetail to be stored. + * @param replaceExisting + * If true, any Job existing in the + * JobStore with the same name & group should be + * over-written. + * @throws ObjectAlreadyExistsException + * if a Job with the same name/group already + * exists, and replaceExisting is set to false. + */ + public void storeJob(SchedulingContext ctxt, JobDetail newJob, + boolean replaceExisting) throws ObjectAlreadyExistsException, + JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + if(isLockOnInsert() || replaceExisting) { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + } + + storeJob(conn, ctxt, newJob, replaceExisting); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Remove (delete) the {@link org.quartz.Job} with the given + * name, and any {@link org.quartz.Trigger} s that reference + * it. + *

+ * + *

+ * If removal of the Job results in an empty group, the + * group should be removed from the JobStore's list of + * known group names. + *

+ * + * @param jobName + * The name of the Job to be removed. + * @param groupName + * The group name of the Job to be removed. + * @return true if a Job with the given name & + * group was found and removed from the store. + */ + public boolean removeJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + return removeJob(conn, ctxt, jobName, groupName, true); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Retrieve the {@link org.quartz.JobDetail} for the given + * {@link org.quartz.Job}. + *

+ * + * @param jobName + * The name of the Job to be retrieved. + * @param groupName + * The group name of the Job to be retrieved. + * @return The desired Job, or null if there is no match. + */ + public JobDetail retrieveJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return retrieveJob(conn, ctxt, jobName, groupName); + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Store the given {@link org.quartz.Trigger}. + *

+ * + * @param newTrigger + * The Trigger to be stored. + * @param replaceExisting + * If true, any Trigger existing in + * the JobStore with the same name & group should + * be over-written. + * @throws ObjectAlreadyExistsException + * if a Trigger with the same name/group already + * exists, and replaceExisting is set to false. + */ + public void storeTrigger(SchedulingContext ctxt, Trigger newTrigger, + boolean replaceExisting) throws ObjectAlreadyExistsException, + JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + if(isLockOnInsert() || replaceExisting) { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + } + + storeTrigger(conn, ctxt, newTrigger, null, replaceExisting, + STATE_WAITING, false, false); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Remove (delete) the {@link org.quartz.Trigger} with the + * given name. + *

+ * + *

+ * If removal of the Trigger results in an empty group, the + * group should be removed from the JobStore's list of + * known group names. + *

+ * + *

+ * If removal of the Trigger results in an 'orphaned' Job + * that is not 'durable', then the Job should be deleted + * also. + *

+ * + * @param triggerName + * The name of the Trigger to be removed. + * @param groupName + * The group name of the Trigger to be removed. + * @return true if a Trigger with the given + * name & group was found and removed from the store. + */ + public boolean removeTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + + return removeTrigger(conn, ctxt, triggerName, groupName); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + + /** + * @see org.quartz.spi.JobStore#replaceTrigger(org.quartz.core.SchedulingContext, java.lang.String, java.lang.String, org.quartz.Trigger) + */ + public boolean replaceTrigger(SchedulingContext ctxt, String triggerName, String groupName, Trigger newTrigger) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + + return replaceTrigger(conn, ctxt, triggerName, groupName, newTrigger); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Retrieve the given {@link org.quartz.Trigger}. + *

+ * + * @param triggerName + * The name of the Trigger to be retrieved. + * @param groupName + * The group name of the Trigger to be retrieved. + * @return The desired Trigger, or null if there is no + * match. + */ + public Trigger retrieveTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return retrieveTrigger(conn, ctxt, triggerName, groupName); + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Store the given {@link org.quartz.Calendar}. + *

+ * + * @param calName + * The name of the calendar. + * @param calendar + * The Calendar to be stored. + * @param replaceExisting + * If true, any Calendar existing + * in the JobStore with the same name & group + * should be over-written. + * @throws ObjectAlreadyExistsException + * if a Calendar with the same name already + * exists, and replaceExisting is set to false. + */ + public void storeCalendar(SchedulingContext ctxt, String calName, + Calendar calendar, boolean replaceExisting, boolean updateTriggers) + throws ObjectAlreadyExistsException, JobPersistenceException { + Connection conn = getConnection(); + boolean lockOwner = false; + try { + if(isLockOnInsert() || updateTriggers) { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + lockOwner = true; + } + + storeCalendar(conn, ctxt, calName, calendar, replaceExisting, updateTriggers); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, lockOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Remove (delete) the {@link org.quartz.Calendar} with the + * given name. + *

+ * + *

+ * If removal of the Calendar would result in + * s pointing to non-existent calendars, then a + * JobPersistenceException will be thrown.

+ * * + * @param calName The name of the Calendar to be removed. + * @return true if a Calendar with the given name + * was found and removed from the store. + */ + public boolean removeCalendar(SchedulingContext ctxt, String calName) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean lockOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_CALENDAR_ACCESS); + lockOwner = true; + + return removeCalendar(conn, ctxt, calName); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, lockOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Retrieve the given {@link org.quartz.Trigger}. + *

+ * + * @param calName + * The name of the Calendar to be retrieved. + * @return The desired Calendar, or null if there is no + * match. + */ + public Calendar retrieveCalendar(SchedulingContext ctxt, String calName) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return retrieveCalendar(conn, ctxt, calName); + } finally { + closeConnection(conn); + } + } + + //--------------------------------------------------------------------------- + // informational methods + //--------------------------------------------------------------------------- + + /** + *

+ * Get the number of {@link org.quartz.Job} s that are + * stored in the JobStore. + *

+ */ + public int getNumberOfJobs(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return getNumberOfJobs(conn, ctxt); + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the number of {@link org.quartz.Trigger} s that are + * stored in the JobsStore. + *

+ */ + public int getNumberOfTriggers(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return getNumberOfTriggers(conn, ctxt); + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the number of {@link org.quartz.Calendar} s that are + * stored in the JobsStore. + *

+ */ + public int getNumberOfCalendars(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return getNumberOfCalendars(conn, ctxt); + } finally { + closeConnection(conn); + } + } + + public Set getPausedTriggerGroups(SchedulingContext ctxt) + throws JobPersistenceException { + + Connection conn = getConnection(); + try { + // no locks necessary for read... + Set groups = getPausedTriggerGroups(conn, ctxt); + return groups; + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Job} s that + * have the given group name. + *

+ * + *

+ * If there are no jobs in the given group name, the result should be a + * zero-length array (not null). + *

+ */ + public String[] getJobNames(SchedulingContext ctxt, String groupName) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return getJobNames(conn, ctxt, groupName); + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Trigger} s + * that have the given group name. + *

+ * + *

+ * If there are no triggers in the given group name, the result should be a + * zero-length array (not null). + *

+ */ + public String[] getTriggerNames(SchedulingContext ctxt, String groupName) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return getTriggerNames(conn, ctxt, groupName); + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Job} + * groups. + *

+ * + *

+ * If there are no known group names, the result should be a zero-length + * array (not null). + *

+ */ + public String[] getJobGroupNames(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return getJobGroupNames(conn, ctxt); + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Trigger} + * groups. + *

+ * + *

+ * If there are no known group names, the result should be a zero-length + * array (not null). + *

+ */ + public String[] getTriggerGroupNames(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return getTriggerGroupNames(conn, ctxt); + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Calendar} s + * in the JobStore. + *

+ * + *

+ * If there are no Calendars in the given group name, the result should be + * a zero-length array (not null). + *

+ */ + public String[] getCalendarNames(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return getCalendarNames(conn, ctxt); + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get all of the Triggers that are associated to the given Job. + *

+ * + *

+ * If there are no matches, a zero-length array should be returned. + *

+ */ + public Trigger[] getTriggersForJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return getTriggersForJob(conn, ctxt, jobName, groupName); + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the current state of the identified {@link Trigger}. + *

+ * + * @see Trigger#STATE_NORMAL + * @see Trigger#STATE_PAUSED + * @see Trigger#STATE_COMPLETE + * @see Trigger#STATE_ERROR + * @see Trigger#STATE_NONE + */ + public int getTriggerState(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return getTriggerState(conn, ctxt, triggerName, groupName); + } finally { + closeConnection(conn); + } + } + + //--------------------------------------------------------------------------- + // trigger state manipulation methods + //--------------------------------------------------------------------------- + + /** + *

+ * Pause the {@link org.quartz.Trigger} with the given name. + *

+ * + * @see #resumeTrigger(SchedulingContext, String, String) + */ + public void pauseTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + pauseTrigger(conn, ctxt, triggerName, groupName); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Pause all of the {@link org.quartz.Trigger}s in the + * given group. + *

+ * + * @see #resumeTriggerGroup(SchedulingContext, String) + */ + public void pauseTriggerGroup(SchedulingContext ctxt, String groupName) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + pauseTriggerGroup(conn, ctxt, groupName); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Pause the {@link org.quartz.Job} with the given name - by + * pausing all of its current Triggers. + *

+ * + * @see #resumeJob(SchedulingContext, String, String) + */ + public void pauseJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + Trigger[] triggers = getTriggersForJob(conn, ctxt, jobName, + groupName); + for (int j = 0; j < triggers.length; j++) { + pauseTrigger(conn, ctxt, triggers[j].getName(), triggers[j] + .getGroup()); + } + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Pause all of the {@link org.quartz.Job}s in the given + * group - by pausing all of their Triggers. + *

+ * + * @see #resumeJobGroup(SchedulingContext, String) + */ + public void pauseJobGroup(SchedulingContext ctxt, String groupName) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + String[] jobNames = getJobNames(conn, ctxt, groupName); + + for (int i = 0; i < jobNames.length; i++) { + Trigger[] triggers = getTriggersForJob(conn, ctxt, jobNames[i], + groupName); + for (int j = 0; j < triggers.length; j++) { + pauseTrigger(conn, ctxt, triggers[j].getName(), triggers[j] + .getGroup()); + } + } + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Resume (un-pause) the {@link org.quartz.Trigger} with the + * given name. + *

+ * + *

+ * If the Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseTrigger(SchedulingContext, String, String) + */ + public void resumeTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + resumeTrigger(conn, ctxt, triggerName, groupName); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Resume (un-pause) all of the {@link org.quartz.Trigger}s + * in the given group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseTriggerGroup(SchedulingContext, String) + */ + public void resumeTriggerGroup(SchedulingContext ctxt, String groupName) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + resumeTriggerGroup(conn, ctxt, groupName); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Resume (un-pause) the {@link org.quartz.Job} with the + * given name. + *

+ * + *

+ * If any of the Job'sTrigger s missed one + * or more fire-times, then the Trigger's misfire + * instruction will be applied. + *

+ * + * @see #pauseJob(SchedulingContext, String, String) + */ + public void resumeJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + Trigger[] triggers = getTriggersForJob(conn, ctxt, jobName, + groupName); + for (int j = 0; j < triggers.length; j++) { + resumeTrigger(conn, ctxt, triggers[j].getName(), triggers[j] + .getGroup()); + } + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Resume (un-pause) all of the {@link org.quartz.Job}s in + * the given group. + *

+ * + *

+ * If any of the Job s had Trigger s that + * missed one or more fire-times, then the Trigger's + * misfire instruction will be applied. + *

+ * + * @see #pauseJobGroup(SchedulingContext, String) + */ + public void resumeJobGroup(SchedulingContext ctxt, String groupName) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + String[] jobNames = getJobNames(conn, ctxt, groupName); + + for (int i = 0; i < jobNames.length; i++) { + Trigger[] triggers = getTriggersForJob(conn, ctxt, jobNames[i], + groupName); + for (int j = 0; j < triggers.length; j++) { + resumeTrigger(conn, ctxt, triggers[j].getName(), + triggers[j].getGroup()); + } + } + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Pause all triggers - equivalent of calling pauseTriggerGroup(group) + * on every group. + *

+ * + *

+ * When resumeAll() is called (to un-pause), trigger misfire + * instructions WILL be applied. + *

+ * + * @see #resumeAll(SchedulingContext) + * @see #pauseTriggerGroup(SchedulingContext, String) + */ + public void pauseAll(SchedulingContext ctxt) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + pauseAll(conn, ctxt); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Resume (un-pause) all triggers - equivalent of calling resumeTriggerGroup(group) + * on every group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseAll(SchedulingContext) + */ + public void resumeAll(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + resumeAll(conn, ctxt); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + //--------------------------------------------------------------------------- + // trigger firing methods + //--------------------------------------------------------------------------- + + /** + *

+ * Get a handle to the next trigger to be fired, and mark it as 'reserved' + * by the calling scheduler. + *

+ * + * @see #releaseAcquiredTrigger(SchedulingContext, Trigger) + */ + public Trigger acquireNextTrigger(SchedulingContext ctxt, long noLaterThan) + throws JobPersistenceException { + Connection conn = null; + boolean transOwner = false; + + try { + conn = getNonManagedTXConnection(); + + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + Trigger trigger = acquireNextTrigger(conn, ctxt, noLaterThan); + + conn.commit(); + return trigger; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } catch (Exception e) { + rollbackConnection(conn); + throw new JobPersistenceException( + "Error acquiring next firable trigger: " + e.getMessage(), + e); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Inform the JobStore that the scheduler no longer plans to + * fire the given Trigger, that it had previously acquired + * (reserved). + *

+ */ + public void releaseAcquiredTrigger(SchedulingContext ctxt, Trigger trigger) + throws JobPersistenceException { + Connection conn = null; + boolean transOwner = false; + + try { + conn = getNonManagedTXConnection(); + + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + releaseAcquiredTrigger(conn, ctxt, trigger); + conn.commit(); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } catch (Exception e) { + rollbackConnection(conn); + throw new JobPersistenceException( + "Error releasing acquired trigger: " + e.getMessage(), e); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Inform the JobStore that the scheduler is now firing the + * given Trigger (executing its associated Job), + * that it had previously acquired (reserved). + *

+ * + * @return null if the trigger or it's job or calendar no longer exist, or + * if the trigger was not successfully put into the 'executing' + * state. + */ + public TriggerFiredBundle triggerFired(SchedulingContext ctxt, + Trigger trigger) throws JobPersistenceException { + Connection conn = null; + boolean transOwner = false; + + try { + conn = getNonManagedTXConnection(); + + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + TriggerFiredBundle tfb = null; + JobPersistenceException err = null; + try { + tfb = triggerFired(conn, ctxt, trigger); + } catch (JobPersistenceException jpe) { + if (jpe.getErrorCode() != SchedulerException.ERR_PERSISTENCE_JOB_DOES_NOT_EXIST) + throw jpe; + err = jpe; + } + + if (err != null) throw err; + + conn.commit(); + return tfb; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } catch (Exception e) { + rollbackConnection(conn); + throw new JobPersistenceException("TX failure: " + e.getMessage(), + e); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Inform the JobStore that the scheduler has completed the + * firing of the given Trigger (and the execution its + * associated Job), and that the {@link org.quartz.JobDataMap} + * in the given JobDetail should be updated if the Job + * is stateful. + *

+ */ + public void triggeredJobComplete(SchedulingContext ctxt, Trigger trigger, + JobDetail jobDetail, int triggerInstCode) + throws JobPersistenceException { + Connection conn = null; + boolean transOwner = false; + + try { + conn = getNonManagedTXConnection(); + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + triggeredJobComplete(conn, ctxt, trigger, jobDetail, + triggerInstCode); + + conn.commit(); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } catch (Exception e) { + rollbackConnection(conn); + throw new JobPersistenceException("TX failure: " + e.getMessage(), + e); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + protected boolean doRecoverMisfires() throws JobPersistenceException { + Connection conn = null; + boolean transOwner = false; + boolean moreToDo = false; + + try { + conn = getNonManagedTXConnection(); + + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + + try { + moreToDo = recoverMisfiredJobs(conn, false); + } catch (Exception e) { + throw new JobPersistenceException(e.getMessage(), e); + } + + conn.commit(); + + return moreToDo; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } catch (Exception e) { + rollbackConnection(conn); + throw new JobPersistenceException("TX failure: " + e.getMessage(), + e); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + + } + + protected boolean doCheckin() throws JobPersistenceException { + Connection conn = null; + + boolean transOwner = false; + boolean transStateOwner = false; + boolean recovered = false; + + try { + conn = getNonManagedTXConnection(); + + // Other than the first time, always checkin first to make sure there is + // work to be done before we aquire / the lock (since that is expensive, + // and is almost never necessary) + List failedRecords = (firstCheckIn) ? null : clusterCheckIn(conn); + + if (firstCheckIn || (failedRecords.size() > 0)) { + getLockHandler().obtainLock(conn, LOCK_STATE_ACCESS); + transStateOwner = true; + + // Now that we own the lock, make sure we still have work to do. + // The first time through, we also need to make sure we update/create our state record + failedRecords = (firstCheckIn) ? clusterCheckIn(conn) : findFailedInstances(conn); + + if (failedRecords.size() > 0) { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + transOwner = true; + + clusterRecover(conn, failedRecords); + recovered = true; + } + } + conn.commit(); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } catch (Exception e) { + rollbackConnection(conn); + throw new JobPersistenceException("TX failure: " + e.getMessage(), + e); + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + try { + releaseLock(conn, LOCK_STATE_ACCESS, transStateOwner); + } finally { + closeConnection(conn); + } + } + } + + firstCheckIn = false; + + return recovered; + } + + //--------------------------------------------------------------------------- + // private helpers + //--------------------------------------------------------------------------- + + + protected Connection getNonManagedTXConnection() + throws JobPersistenceException { + try { + Connection conn = DBConnectionManager.getInstance().getConnection( + getNonManagedTXDataSource()); + + if (conn == null) { throw new SQLException( + "Could not get connection from DataSource '" + + getNonManagedTXDataSource() + "'"); } + + try { + if (!isDontSetNonManagedTXConnectionAutoCommitFalse()) + conn.setAutoCommit(false); + + if (isTxIsolationLevelReadCommitted()) + conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); + } catch (SQLException ingore) { + } catch (Exception e) { + if(conn != null) + try { conn.close(); } catch(Throwable tt) {} + throw new JobPersistenceException( + "Failure setting up connection.", e); + } + + return conn; + } catch (SQLException sqle) { + throw new JobPersistenceException( + "Failed to obtain DB connection from data source '" + + getNonManagedTXDataSource() + "': " + + sqle.toString(), sqle); + } catch (Exception e) { + throw new JobPersistenceException( + "Failed to obtain DB connection from data source '" + + getNonManagedTXDataSource() + "': " + + e.toString(), e, + JobPersistenceException.ERR_PERSISTENCE_CRITICAL_FAILURE); + } + } + +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/JobStoreSupport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/JobStoreSupport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/JobStoreSupport.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,2498 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.Calendar; +import org.quartz.CronTrigger; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.JobPersistenceException; +import org.quartz.ObjectAlreadyExistsException; +import org.quartz.Scheduler; +import org.quartz.SchedulerConfigException; +import org.quartz.SchedulerException; +import org.quartz.SimpleTrigger; +import org.quartz.Trigger; +import org.quartz.core.SchedulingContext; +import org.quartz.spi.ClassLoadHelper; +import org.quartz.spi.JobStore; +import org.quartz.spi.SchedulerSignaler; +import org.quartz.spi.TriggerFiredBundle; +import org.quartz.utils.DBConnectionManager; +import org.quartz.utils.Key; +import org.quartz.utils.TriggerStatus; + + +/** + *

+ * Contains base functionality for JDBC-based JobStore implementations. + *

+ * + * @author Jeffrey Wescott + * @author James House + */ +public abstract class JobStoreSupport implements JobStore, Constants { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected static String LOCK_TRIGGER_ACCESS = "TRIGGER_ACCESS"; + + protected static String LOCK_JOB_ACCESS = "JOB_ACCESS"; + + protected static String LOCK_CALENDAR_ACCESS = "CALENDAR_ACCESS"; + + protected static String LOCK_STATE_ACCESS = "STATE_ACCESS"; + + protected static String LOCK_MISFIRE_ACCESS = "MISFIRE_ACCESS"; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected String dsName; + + protected String tablePrefix = DEFAULT_TABLE_PREFIX; + + protected boolean useProperties = false; + + protected String instanceId; + + protected String instanceName; + + protected String delegateClassName; + protected Class delegateClass = StdJDBCDelegate.class; + + protected HashMap calendarCache = new HashMap(); + + private DriverDelegate delegate; + + private long misfireThreshold = 60000L; // one minute + + private boolean dontSetAutoCommitFalse = false; + + private boolean isClustered = false; + + private boolean useDBLocks = false; + + private boolean lockOnInsert = true; + + private Semaphore lockHandler = null; // set in initialize() method... + + private String selectWithLockSQL = null; + + private long clusterCheckinInterval = 7500L; + + private ClusterManager clusterManagementThread = null; + + private MisfireHandler misfireHandler = null; + + private ClassLoadHelper classLoadHelper; + + private SchedulerSignaler signaler; + + protected int maxToRecoverAtATime = 20; + + private boolean setTxIsolationLevelSequential = false; + + private long dbRetryInterval = 10000; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Set the name of the DataSource that should be used for + * performing database functions. + *

+ */ + public void setDataSource(String dsName) { + this.dsName = dsName; + } + + /** + *

+ * Get the name of the DataSource that should be used for + * performing database functions. + *

+ */ + public String getDataSource() { + return dsName; + } + + /** + *

+ * Set the prefix that should be pre-pended to all table names. + *

+ */ + public void setTablePrefix(String prefix) { + if (prefix == null) prefix = ""; + + this.tablePrefix = prefix; + } + + /** + *

+ * Get the prefix that should be pre-pended to all table names. + *

+ */ + public String getTablePrefix() { + return tablePrefix; + } + + /** + *

+ * Set whether String-only properties will be handled in JobDataMaps. + *

+ */ + public void setUseProperties(String useProp) { + if (useProp == null) useProp = "false"; + + this.useProperties = Boolean.valueOf(useProp).booleanValue(); + } + + /** + *

+ * Get whether String-only properties will be handled in JobDataMaps. + *

+ */ + public boolean canUseProperties() { + return useProperties; + } + + /** + *

+ * Set the instance Id of the Scheduler (must be unique within a cluster). + *

+ */ + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + /** + *

+ * Get the instance Id of the Scheduler (must be unique within a cluster). + *

+ */ + public String getInstanceId() { + + return instanceId; + } + + /** + *

+ * Set the instance Id of the Scheduler (must be unique within a cluster). + *

+ */ + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + /** + *

+ * Get the instance Id of the Scheduler (must be unique within a cluster). + *

+ */ + public String getInstanceName() { + + return instanceName; + } + + /** + *

+ * Set whether this instance is part of a cluster. + *

+ */ + public void setIsClustered(boolean isClustered) { + this.isClustered = isClustered; + } + + /** + *

+ * Get whether this instance is part of a cluster. + *

+ */ + public boolean isClustered() { + return isClustered; + } + + /** + *

+ * Get the frequency (in milliseconds) at which this instance "checks-in" + * with the other instances of the cluster. -- Affects the rate of + * detecting failed instances. + *

+ */ + public long getClusterCheckinInterval() { + return clusterCheckinInterval; + } + + /** + *

+ * Set the frequency (in milliseconds) at which this instance "checks-in" + * with the other instances of the cluster. -- Affects the rate of + * detecting failed instances. + *

+ */ + public void setClusterCheckinInterval(long l) { + clusterCheckinInterval = l; + } + + /** + *

+ * Get the maximum number of misfired triggers that the misfire handling + * thread will try to recover at one time (within one transaction). The + * default is 20. + *

+ */ + public int getMaxMisfiresToHandleAtATime() { + return maxToRecoverAtATime; + } + + /** + *

+ * Set the maximum number of misfired triggers that the misfire handling + * thread will try to recover at one time (within one transaction). The + * default is 20. + *

+ */ + public void setMaxMisfiresToHandleAtATime(int maxToRecoverAtATime) { + this.maxToRecoverAtATime = maxToRecoverAtATime; + } + + /** + * @return Returns the dbRetryInterval. + */ + public long getDbRetryInterval() { + return dbRetryInterval; + } + /** + * @param dbRetryInterval The dbRetryInterval to set. + */ + public void setDbRetryInterval(long dbRetryInterval) { + this.dbRetryInterval = dbRetryInterval; + } + + /** + *

+ * Set whether this instance should use database-based thread + * synchronization. + *

+ */ + public void setUseDBLocks(boolean useDBLocks) { + this.useDBLocks = useDBLocks; + } + + /** + *

+ * Get whether this instance should use database-based thread + * synchronization. + *

+ */ + public boolean getUseDBLocks() { + return useDBLocks; + } + + public boolean isLockOnInsert() { + return lockOnInsert; + } + + /** + * Whether or not to obtain locks when inserting new jobs/triggers. + * Defaults to true, which is safest - some db's (such as + * MS SQLServer) seem to require this to avoid deadlocks under high load, + * while others seem to do fine without. + * + *

Setting this property to false will provide a + * significant performance increase during the addition of new jobs + * and triggers.

+ * + * @param lockOnInsert + */ + public void setLockOnInsert(boolean lockOnInsert) { + this.lockOnInsert = lockOnInsert; + } + + public long getMisfireThreshold() { + return misfireThreshold; + } + + /** + * The the number of milliseconds by which a trigger must have missed its + * next-fire-time, in order for it to be considered "misfired" and thus + * have its misfire instruction applied. + * + * @param misfireThreshold + */ + public void setMisfireThreshold(long misfireThreshold) { + if (misfireThreshold < 1) + throw new IllegalArgumentException( + "Misfirethreashold must be larger than 0"); + this.misfireThreshold = misfireThreshold; + } + + public boolean isDontSetAutoCommitFalse() { + return dontSetAutoCommitFalse; + } + + /** + * Don't call set autocommit(false) on connections obtained from the + * DataSource. This can be helpfull in a few situations, such as if you + * have a driver that complains if it is called when it is already off. + * + * @param b + */ + public void setDontSetAutoCommitFalse(boolean b) { + dontSetAutoCommitFalse = b; + } + + public boolean isTxIsolationLevelSerializable() { + return setTxIsolationLevelSequential; + } + + /** + * Set the transaction isolation level of DB connections to sequential. + * + * @param b + */ + public void setTxIsolationLevelSerializable(boolean b) { + setTxIsolationLevelSequential = b; + } + + + /** + *

+ * Set the JDBC driver delegate class. + *

+ * + * @param delegateClassName + * the delegate class name + */ + public void setDriverDelegateClass(String delegateClassName) + throws InvalidConfigurationException { + this.delegateClassName = delegateClassName; + } + + /** + *

+ * Get the JDBC driver delegate class name. + *

+ * + * @return the delegate class name + */ + public String getDriverDelegateClass() { + return delegateClassName; + } + + public String getSelectWithLockSQL() { + return selectWithLockSQL; + } + + /** + *

+ * set the SQL statement to use to select and lock a row in the "locks" + * table. + *

+ * + * @see StdRowLockSemaphore + */ + public void setSelectWithLockSQL(String string) { + selectWithLockSQL = string; + } + + protected ClassLoadHelper getClassLoadHelper() { + return classLoadHelper; + } + + //--------------------------------------------------------------------------- + // interface methods + //--------------------------------------------------------------------------- + + Log getLog() { + return LogFactory.getLog(getClass()); + } + + /** + *

+ * Called by the QuartzScheduler before the JobStore is + * used, in order to give the it a chance to initialize. + *

+ */ + public void initialize(ClassLoadHelper loadHelper, + SchedulerSignaler signaler) throws SchedulerConfigException { + + if (dsName == null) { throw new SchedulerConfigException( + "DataSource name not set."); } + + classLoadHelper = loadHelper; + this.signaler = signaler; + + if (!getUseDBLocks() && !isClustered()) { + getLog() + .info( + "Using thread monitor-based data access locking (synchronization)."); + lockHandler = new SimpleSemaphore(); + } else { + getLog() + .info( + "Using db table-based data access locking (synchronization)."); + lockHandler = new StdRowLockSemaphore(getTablePrefix(), + getSelectWithLockSQL()); + } + + if (!isClustered()) { + try { + cleanVolatileTriggerAndJobs(); + } catch (SchedulerException se) { + throw new SchedulerConfigException( + "Failure occured during job recovery.", se); + } + } + } + + /** + * @see org.quartz.spi.JobStore#schedulerStarted() + */ + public void schedulerStarted() throws SchedulerException { + + if (isClustered()) { + clusterManagementThread = new ClusterManager(this); + clusterManagementThread.initialize(); + } + else { + try { + recoverJobs(); + } catch (SchedulerException se) { + throw new SchedulerConfigException( + "Failure occured during job recovery.", se); + } + } + + misfireHandler = new MisfireHandler(this); + misfireHandler.initialize(); + } + + /** + *

+ * Called by the QuartzScheduler to inform the JobStore that + * it should free up all of it's resources because the scheduler is + * shutting down. + *

+ */ + public void shutdown() { + if (clusterManagementThread != null) + clusterManagementThread.shutdown(); + + if (misfireHandler != null) misfireHandler.shutdown(); + + try { + DBConnectionManager.getInstance().shutdown(getDataSource()); + } catch (SQLException sqle) { + getLog().warn("Database connection shutdown unsuccessful.", sqle); + } + } + + public boolean supportsPersistence() { + return true; + } + + //--------------------------------------------------------------------------- + // helper methods for subclasses + //--------------------------------------------------------------------------- + + + + protected Connection getConnection() throws JobPersistenceException { + try { + Connection conn = DBConnectionManager.getInstance().getConnection( + getDataSource()); + + if (conn == null) { throw new SQLException( + "Could not get connection from DataSource '" + + getDataSource() + "'"); } + + try { + if (!isDontSetAutoCommitFalse()) conn.setAutoCommit(false); + + if(isTxIsolationLevelSerializable()) + conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + } catch (SQLException ingore) { + } catch (Exception e) { + if(conn != null) + try { conn.close(); } catch(Throwable tt) {} + throw new JobPersistenceException( + "Failure setting up connection.", e); + } + + return conn; + } catch (SQLException sqle) { + throw new JobPersistenceException( + "Failed to obtain DB connection from data source '" + + getDataSource() + "': " + sqle.toString(), sqle); + } catch (Exception e) { + throw new JobPersistenceException( + "Failed to obtain DB connection from data source '" + + getDataSource() + "': " + e.toString(), e, + JobPersistenceException.ERR_PERSISTENCE_CRITICAL_FAILURE); + } + } + + protected void releaseLock(Connection conn, String lockName, boolean doIt) { + if (doIt && conn != null) { + try { + getLockHandler().releaseLock(conn, lockName); + } catch (LockException le) { + getLog().error("Error returning lock: " + le.getMessage(), + le); + } + } + } + + /** + *

+ * Removes all volatile data + *

+ * + * @throws JobPersistenceException + * if jobs could not be recovered + */ + protected abstract void cleanVolatileTriggerAndJobs() + throws JobPersistenceException; + + /** + *

+ * Removes all volatile data. + *

+ * + * @throws JobPersistenceException + * if jobs could not be recovered + */ + protected void cleanVolatileTriggerAndJobs(Connection conn) + throws JobPersistenceException { + try { + // find volatile jobs & triggers... + Key[] volatileTriggers = getDelegate().selectVolatileTriggers(conn); + Key[] volatileJobs = getDelegate().selectVolatileJobs(conn); + + for (int i = 0; i < volatileTriggers.length; i++) { + removeTrigger(conn, null, volatileTriggers[i].getName(), + volatileTriggers[i].getGroup()); + } + getLog().info( + "Removed " + volatileTriggers.length + + " Volatile Trigger(s)."); + + for (int i = 0; i < volatileJobs.length; i++) { + removeJob(conn, null, volatileJobs[i].getName(), + volatileJobs[i].getGroup(), true); + } + getLog().info( + "Removed " + volatileJobs.length + " Volatile Job(s)."); + + // clean up any fired trigger entries + getDelegate().deleteVolatileFiredTriggers(conn); + + } catch (Exception e) { + throw new JobPersistenceException("Couldn't clean volatile data: " + + e.getMessage(), e); + } + } + + /** + *

+ * Will recover any failed or misfired jobs and clean up the data store as + * appropriate. + *

+ * + * @throws JobPersistenceException + * if jobs could not be recovered + */ + protected abstract void recoverJobs() throws JobPersistenceException; + + /** + *

+ * Will recover any failed or misfired jobs and clean up the data store as + * appropriate. + *

+ * + * @throws JobPersistenceException + * if jobs could not be recovered + */ + protected void recoverJobs(Connection conn) throws JobPersistenceException { + try { + // update inconsistent job states + int rows = getDelegate().updateTriggerStatesFromOtherStates(conn, + STATE_WAITING, STATE_ACQUIRED, STATE_BLOCKED); + + rows += getDelegate().updateTriggerStatesFromOtherStates(conn, + STATE_PAUSED, STATE_PAUSED_BLOCKED, STATE_PAUSED_BLOCKED); + + getLog().info( + "Freed " + rows + + " triggers from 'acquired' / 'blocked' state."); + + // clean up misfired jobs + getDelegate().updateTriggerStateFromOtherStatesBeforeTime(conn, + STATE_MISFIRED, STATE_WAITING, STATE_WAITING, + getMisfireTime()); // only waiting + recoverMisfiredJobs(conn, true); + + // recover jobs marked for recovery that were not fully executed + Trigger[] recoveringJobTriggers = getDelegate() + .selectTriggersForRecoveringJobs(conn); + getLog() + .info( + "Recovering " + + recoveringJobTriggers.length + + " jobs that were in-progress at the time of the last shut-down."); + + for (int i = 0; i < recoveringJobTriggers.length; ++i) { + if (jobExists(conn, recoveringJobTriggers[i].getJobName(), + recoveringJobTriggers[i].getJobGroup())) { + recoveringJobTriggers[i].computeFirstFireTime(null); + storeTrigger(conn, null, recoveringJobTriggers[i], null, false, + STATE_WAITING, false, true); + } + } + getLog().info("Recovery complete."); + + // remove lingering 'complete' triggers... + Key[] ct = getDelegate().selectTriggersInState(conn, STATE_COMPLETE); + for(int i=0; ct != null && i < ct.length; i++) + removeTrigger(conn, null, ct[i].getName(), ct[i].getGroup()); + getLog().info( + "Removed " + ct.length + + " 'complete' triggers."); + + // clean up any fired trigger entries + int n = getDelegate().deleteFiredTriggers(conn); + getLog().info("Removed " + n + " stale fired job entries."); + } catch (Exception e) { + throw new JobPersistenceException("Couldn't recover jobs: " + + e.getMessage(), e); + } + } + + protected long getMisfireTime() { + long misfireTime = System.currentTimeMillis(); + if (getMisfireThreshold() > 0) misfireTime -= getMisfireThreshold(); + + return misfireTime; + } + + private int lastRecoverCount = 0; + + protected boolean recoverMisfiredJobs(Connection conn, boolean recovering) + throws JobPersistenceException, NoSuchDelegateException, + SQLException, ClassNotFoundException, IOException { + + Key[] misfiredTriggers = getDelegate().selectTriggersInState(conn, + STATE_MISFIRED); + + if (misfiredTriggers.length > 0 + && misfiredTriggers.length > getMaxMisfiresToHandleAtATime()) getLog() + .info( + "Handling " + + getMaxMisfiresToHandleAtATime() + + " of " + + misfiredTriggers.length + + " triggers that missed their scheduled fire-time."); + else if (misfiredTriggers.length > 0) getLog().info( + "Handling " + misfiredTriggers.length + + " triggers that missed their scheduled fire-time."); + else + getLog().debug( + "Found 0 triggers that missed their scheduled fire-time."); + + lastRecoverCount = misfiredTriggers.length; + + for (int i = 0; i < misfiredTriggers.length && i < getMaxMisfiresToHandleAtATime(); i++) { + Trigger trig = getDelegate().selectTrigger(conn, + misfiredTriggers[i].getName(), + misfiredTriggers[i].getGroup()); + + if (trig == null) continue; + + Calendar cal = null; + if (trig.getCalendarName() != null) + cal = retrieveCalendar(conn, null, trig.getCalendarName()); + + String[] listeners = getDelegate().selectTriggerListeners(conn, + trig.getName(), trig.getGroup()); + for (int l = 0; l < listeners.length; ++l) { + trig.addTriggerListener(listeners[l]); + } + + signaler.notifyTriggerListenersMisfired(trig); + + trig.updateAfterMisfire(cal); + + if (trig.getNextFireTime() == null) + storeTrigger(conn, null, trig, null, true, STATE_COMPLETE, + false, recovering); + else + storeTrigger(conn, null, trig, null, true, STATE_WAITING, + false, recovering); + } + + if (misfiredTriggers.length > getMaxMisfiresToHandleAtATime()) return true; + + return false; + } + + protected boolean updateMisfiredTrigger(Connection conn, + SchedulingContext ctxt, String triggerName, String groupName, + String newStateIfNotComplete, boolean forceState) // TODO: probably + // get rid of + // this + throws JobPersistenceException { + try { + + Trigger trig = getDelegate().selectTrigger(conn, triggerName, + groupName); + + long misfireTime = System.currentTimeMillis(); + if (getMisfireThreshold() > 0) + misfireTime -= getMisfireThreshold(); + + if (trig.getNextFireTime().getTime() > misfireTime) return false; + + Calendar cal = null; + if (trig.getCalendarName() != null) + cal = retrieveCalendar(conn, ctxt, trig.getCalendarName()); + + signaler.notifyTriggerListenersMisfired(trig); + + trig.updateAfterMisfire(cal); + + if (trig.getNextFireTime() == null) storeTrigger(conn, ctxt, trig, + null, true, STATE_COMPLETE, forceState, false); + else { + storeTrigger(conn, ctxt, trig, null, true, newStateIfNotComplete, + forceState, false); + } + + return true; + + } catch (Exception e) { + throw new JobPersistenceException( + "Couldn't update misfired trigger '" + groupName + "." + + triggerName + "': " + e.getMessage(), e); + } + } + + /** + *

+ * Insert or update a job. + *

+ */ + protected void storeJob(Connection conn, SchedulingContext ctxt, + JobDetail newJob, boolean replaceExisting) + throws ObjectAlreadyExistsException, JobPersistenceException { + if (newJob.isVolatile() && isClustered()) + getLog() + .info( + "note: volatile jobs are effectively non-volatile in a clustered environment."); + + boolean existingJob = jobExists(conn, newJob.getName(), newJob + .getGroup()); + try { + if (existingJob) { + if (!replaceExisting) { throw new ObjectAlreadyExistsException( + newJob); } + getDelegate().updateJobDetail(conn, newJob); + } else { + getDelegate().insertJobDetail(conn, newJob); + } + } catch (IOException e) { + throw new JobPersistenceException("Couldn't store job: " + + e.getMessage(), e); + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't store job: " + + e.getMessage(), e); + } + } + + /** + *

+ * Check existence of a given job. + *

+ */ + protected boolean jobExists(Connection conn, String jobName, + String groupName) throws JobPersistenceException { + try { + return getDelegate().jobExists(conn, jobName, groupName); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't determine job existence (" + groupName + "." + + jobName + "): " + e.getMessage(), e); + } + } + + /** + *

+ * Insert or update a trigger. + *

+ */ + protected void storeTrigger(Connection conn, SchedulingContext ctxt, + Trigger newTrigger, JobDetail job, boolean replaceExisting, String state, + boolean forceState, boolean recovering) + throws ObjectAlreadyExistsException, JobPersistenceException { + if (newTrigger.isVolatile() && isClustered()) + getLog() + .info( + "note: volatile triggers are effectively non-volatile in a clustered environment."); + + boolean existingTrigger = triggerExists(conn, newTrigger.getName(), + newTrigger.getGroup()); + + try { + + boolean shouldBepaused = false; + + if (!forceState) { + shouldBepaused = getDelegate().isTriggerGroupPaused( + conn, newTrigger.getGroup()); + + if(!shouldBepaused) { + shouldBepaused = getDelegate().isTriggerGroupPaused(conn, + ALL_GROUPS_PAUSED); + + if (shouldBepaused) + getDelegate().insertPausedTriggerGroup(conn, + newTrigger.getGroup()); + } + + if (shouldBepaused && (state.equals(STATE_WAITING) || state.equals(STATE_ACQUIRED))) + state = STATE_PAUSED; + } + + if(job == null) { + job = getDelegate().selectJobDetail(conn, + newTrigger.getJobName(), newTrigger.getJobGroup(), + getClassLoadHelper()); + } + if (job == null) + throw new JobPersistenceException("The job (" + + newTrigger.getFullJobName() + + ") referenced by the trigger does not exist."); + if (job.isVolatile() && !newTrigger.isVolatile()) + throw new JobPersistenceException( + "It does not make sense to " + + "associate a non-volatile Trigger with a volatile Job!"); + + if (job.isStateful() && !recovering) { + String bstate = getNewStatusForTrigger(conn, ctxt, job.getName(), job + .getGroup()); + if(STATE_BLOCKED.equals(bstate) && STATE_WAITING.equals(state)) + state = STATE_BLOCKED; + if(STATE_BLOCKED.equals(bstate) && STATE_PAUSED.equals(state)) + state = STATE_PAUSED_BLOCKED; + } + if (existingTrigger) { + if (!replaceExisting) { throw new ObjectAlreadyExistsException( + newTrigger); } + if (newTrigger instanceof SimpleTrigger) { + getDelegate().updateSimpleTrigger(conn, + (SimpleTrigger) newTrigger); + } else if (newTrigger instanceof CronTrigger) { + getDelegate().updateCronTrigger(conn, + (CronTrigger) newTrigger); + } else { + getDelegate().updateBlobTrigger(conn, newTrigger); + } + getDelegate().updateTrigger(conn, newTrigger, state, job); + } else { + getDelegate().insertTrigger(conn, newTrigger, state, job); + if (newTrigger instanceof SimpleTrigger) { + getDelegate().insertSimpleTrigger(conn, + (SimpleTrigger) newTrigger); + } else if (newTrigger instanceof CronTrigger) { + getDelegate().insertCronTrigger(conn, + (CronTrigger) newTrigger); + } else { + getDelegate().insertBlobTrigger(conn, newTrigger); + } + } + } catch (Exception e) { + throw new JobPersistenceException("Couldn't store trigger: " + + e.getMessage(), e); + } + } + + /** + *

+ * Check existence of a given trigger. + *

+ */ + protected boolean triggerExists(Connection conn, String triggerName, + String groupName) throws JobPersistenceException { + try { + return getDelegate().triggerExists(conn, triggerName, groupName); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't determine trigger existence (" + groupName + "." + + triggerName + "): " + e.getMessage(), e); + } + } + + protected boolean removeJob(Connection conn, SchedulingContext ctxt, + String jobName, String groupName, boolean activeDeleteSafe) + throws JobPersistenceException { + + try { + Key[] jobTriggers = getDelegate().selectTriggerNamesForJob(conn, + jobName, groupName); + for (int i = 0; i < jobTriggers.length; ++i) { + getDelegate().deleteSimpleTrigger(conn, + jobTriggers[i].getName(), jobTriggers[i].getGroup()); + getDelegate().deleteCronTrigger(conn, jobTriggers[i].getName(), + jobTriggers[i].getGroup()); + getDelegate().deleteBlobTrigger(conn, jobTriggers[i].getName(), + jobTriggers[i].getGroup()); + getDelegate().deleteTriggerListeners(conn, + jobTriggers[i].getName(), jobTriggers[i].getGroup()); + getDelegate().deleteTrigger(conn, jobTriggers[i].getName(), + jobTriggers[i].getGroup()); + } + + getDelegate().deleteJobListeners(conn, jobName, groupName); + + if (getDelegate().deleteJobDetail(conn, jobName, groupName) > 0) { + return true; + } else { + return false; + } + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't remove job: " + + e.getMessage(), e); + } + } + + protected JobDetail retrieveJob(Connection conn, SchedulingContext ctxt, + String jobName, String groupName) throws JobPersistenceException { + try { + JobDetail job = getDelegate().selectJobDetail(conn, jobName, + groupName, getClassLoadHelper()); + String[] listeners = getDelegate().selectJobListeners(conn, + jobName, groupName); + for (int i = 0; i < listeners.length; ++i) { + job.addJobListener(listeners[i]); + } + + return job; + } catch (ClassNotFoundException e) { + throw new JobPersistenceException( + "Couldn't retrieve job because a required class was not found: " + + e.getMessage(), e, + SchedulerException.ERR_PERSISTENCE_JOB_DOES_NOT_EXIST); + } catch (IOException e) { + throw new JobPersistenceException( + "Couldn't retrieve job because the BLOB couldn't be deserialized: " + + e.getMessage(), e, + SchedulerException.ERR_PERSISTENCE_JOB_DOES_NOT_EXIST); + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't retrieve job: " + + e.getMessage(), e); + } + } + + protected boolean removeTrigger(Connection conn, SchedulingContext ctxt, + String triggerName, String groupName) + throws JobPersistenceException { + boolean removedTrigger = false; + try { + // this must be called before we delete the trigger, obviously + JobDetail job = getDelegate().selectJobForTrigger(conn, + triggerName, groupName, getClassLoadHelper()); + + getDelegate().deleteSimpleTrigger(conn, triggerName, groupName); + getDelegate().deleteCronTrigger(conn, triggerName, groupName); + getDelegate().deleteBlobTrigger(conn, triggerName, groupName); + getDelegate().deleteTriggerListeners(conn, triggerName, groupName); + removedTrigger = (getDelegate().deleteTrigger(conn, triggerName, + groupName) > 0); + + if (null != job && !job.isDurable()) { + int numTriggers = getDelegate().selectNumTriggersForJob(conn, + job.getName(), job.getGroup()); + if (numTriggers == 0) { + removeJob(conn, ctxt, job.getName(), job.getGroup(), true); + } + } + } catch (ClassNotFoundException e) { + throw new JobPersistenceException("Couldn't remove trigger: " + + e.getMessage(), e); + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't remove trigger: " + + e.getMessage(), e); + } + + return removedTrigger; + } + + protected boolean replaceTrigger(Connection conn, SchedulingContext ctxt, + String triggerName, String groupName, Trigger newTrigger) + throws JobPersistenceException { + boolean removedTrigger = false; + try { + // this must be called before we delete the trigger, obviously + JobDetail job = getDelegate().selectJobForTrigger(conn, + triggerName, groupName, getClassLoadHelper()); + + if(job == null) + return false; + + if(!newTrigger.getJobName().equals(job.getName()) || + !newTrigger.getJobGroup().equals(job.getGroup())) + throw new JobPersistenceException("New trigger is not related to the same job as the old trigger."); + + getDelegate().deleteSimpleTrigger(conn, triggerName, groupName); + getDelegate().deleteCronTrigger(conn, triggerName, groupName); + getDelegate().deleteBlobTrigger(conn, triggerName, groupName); + getDelegate().deleteTriggerListeners(conn, triggerName, groupName); + removedTrigger = (getDelegate().deleteTrigger(conn, triggerName, + groupName) > 0); + + storeTrigger(conn, ctxt, newTrigger, job, false, STATE_WAITING, false, false); + + } catch (ClassNotFoundException e) { + throw new JobPersistenceException("Couldn't remove trigger: " + + e.getMessage(), e); + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't remove trigger: " + + e.getMessage(), e); + } + + return removedTrigger; + } + + protected Trigger retrieveTrigger(Connection conn, SchedulingContext ctxt, + String triggerName, String groupName) + throws JobPersistenceException { + try { + Trigger trigger = getDelegate().selectTrigger(conn, triggerName, + groupName); + if (trigger == null) return null; + String[] listeners = getDelegate().selectTriggerListeners(conn, + triggerName, groupName); + for (int i = 0; i < listeners.length; ++i) { + trigger.addTriggerListener(listeners[i]); + } + + return trigger; + } catch (Exception e) { + throw new JobPersistenceException("Couldn't retrieve trigger: " + + e.getMessage(), e); + } + } + + public int getTriggerState(Connection conn, SchedulingContext ctxt, + String triggerName, String groupName) + throws JobPersistenceException { + try { + String ts = getDelegate().selectTriggerState(conn, triggerName, + groupName); + + if (ts == null) return Trigger.STATE_NONE; + + if (ts.equals(STATE_DELETED)) return Trigger.STATE_NONE; + + if (ts.equals(STATE_COMPLETE)) return Trigger.STATE_COMPLETE; + + if (ts.equals(STATE_PAUSED)) return Trigger.STATE_PAUSED; + + if (ts.equals(STATE_PAUSED_BLOCKED)) return Trigger.STATE_PAUSED; + + if (ts.equals(STATE_ERROR)) return Trigger.STATE_ERROR; + + if (ts.equals(STATE_BLOCKED)) return Trigger.STATE_BLOCKED; + + return Trigger.STATE_NORMAL; + + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't determine state of trigger (" + groupName + "." + + triggerName + "): " + e.getMessage(), e); + } + } + + protected void storeCalendar(Connection conn, SchedulingContext ctxt, + String calName, Calendar calendar, boolean replaceExisting, boolean updateTriggers) + throws ObjectAlreadyExistsException, JobPersistenceException { + try { + boolean existingCal = calendarExists(conn, calName); + if (existingCal && !replaceExisting) { throw new ObjectAlreadyExistsException( + "Calendar with name '" + calName + "' already exists."); } + + if (existingCal) { + if (getDelegate().updateCalendar(conn, calName, calendar) < 1) { throw new JobPersistenceException( + "Couldn't store calendar. Update failed."); } + + if(updateTriggers) { + Trigger[] trigs = getDelegate().selectTriggersForCalendar(conn, calName); + + for(int i=0; i < trigs.length; i++) { + trigs[i].updateWithNewCalendar(calendar, getMisfireThreshold()); + storeTrigger(conn, ctxt, trigs[i], null, true, STATE_WAITING, false, false); + } + } + } else { + if (getDelegate().insertCalendar(conn, calName, calendar) < 1) { throw new JobPersistenceException( + "Couldn't store calendar. Insert failed."); } + } + + calendarCache.put(calName, calendar); // lazy-cache + + } catch (IOException e) { + throw new JobPersistenceException( + "Couldn't store calendar because the BLOB couldn't be serialized: " + + e.getMessage(), e); + } catch (ClassNotFoundException e) { + throw new JobPersistenceException("Couldn't store calendar: " + + e.getMessage(), e); + }catch (SQLException e) { + throw new JobPersistenceException("Couldn't store calendar: " + + e.getMessage(), e); + } + } + + protected boolean calendarExists(Connection conn, String calName) + throws JobPersistenceException { + try { + return getDelegate().calendarExists(conn, calName); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't determine calendar existence (" + calName + "): " + + e.getMessage(), e); + } + } + + protected boolean removeCalendar(Connection conn, SchedulingContext ctxt, + String calName) throws JobPersistenceException { + try { + if (getDelegate().calendarIsReferenced(conn, calName)) { throw new JobPersistenceException( + "Calender cannot be removed if it referenced by a trigger!"); } + + calendarCache.remove(calName); + + return (getDelegate().deleteCalendar(conn, calName) > 0); + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't remove calendar: " + + e.getMessage(), e); + } + } + + protected Calendar retrieveCalendar(Connection conn, + SchedulingContext ctxt, String calName) + throws JobPersistenceException { + // all calendars are persistent, but we lazy-cache them during run + // time... + Calendar cal = (Calendar) calendarCache.get(calName); + if (cal != null) return cal; + + try { + cal = getDelegate().selectCalendar(conn, calName); + calendarCache.put(calName, cal); // lazy-cache... + return cal; + } catch (ClassNotFoundException e) { + throw new JobPersistenceException( + "Couldn't retrieve calendar because a required class was not found: " + + e.getMessage(), e); + } catch (IOException e) { + throw new JobPersistenceException( + "Couldn't retrieve calendar because the BLOB couldn't be deserialized: " + + e.getMessage(), e); + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't retrieve calendar: " + + e.getMessage(), e); + } + } + + protected int getNumberOfJobs(Connection conn, SchedulingContext ctxt) + throws JobPersistenceException { + try { + return getDelegate().selectNumJobs(conn); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't obtain number of jobs: " + e.getMessage(), e); + } + } + + protected int getNumberOfTriggers(Connection conn, SchedulingContext ctxt) + throws JobPersistenceException { + try { + return getDelegate().selectNumTriggers(conn); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't obtain number of triggers: " + e.getMessage(), e); + } + } + + protected int getNumberOfCalendars(Connection conn, SchedulingContext ctxt) + throws JobPersistenceException { + try { + return getDelegate().selectNumCalendars(conn); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't obtain number of calendars: " + e.getMessage(), e); + } + } + + protected String[] getJobNames(Connection conn, SchedulingContext ctxt, + String groupName) throws JobPersistenceException { + String[] jobNames = null; + + try { + jobNames = getDelegate().selectJobsInGroup(conn, groupName); + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't obtain job names: " + + e.getMessage(), e); + } + + return jobNames; + } + + protected String[] getTriggerNames(Connection conn, SchedulingContext ctxt, + String groupName) throws JobPersistenceException { + + String[] trigNames = null; + + try { + trigNames = getDelegate().selectTriggersInGroup(conn, groupName); + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't obtain trigger names: " + + e.getMessage(), e); + } + + return trigNames; + } + + protected String[] getJobGroupNames(Connection conn, SchedulingContext ctxt) + throws JobPersistenceException { + + String[] groupNames = null; + + try { + groupNames = getDelegate().selectJobGroups(conn); + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't obtain job groups: " + + e.getMessage(), e); + } + + return groupNames; + } + + protected String[] getTriggerGroupNames(Connection conn, + SchedulingContext ctxt) throws JobPersistenceException { + + String[] groupNames = null; + + try { + groupNames = getDelegate().selectTriggerGroups(conn); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't obtain trigger groups: " + e.getMessage(), e); + } + + return groupNames; + } + + protected String[] getCalendarNames(Connection conn, SchedulingContext ctxt) + throws JobPersistenceException { + try { + return getDelegate().selectCalendars(conn); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't obtain trigger groups: " + e.getMessage(), e); + } + } + + protected Trigger[] getTriggersForJob(Connection conn, + SchedulingContext ctxt, String jobName, String groupName) + throws JobPersistenceException { + Trigger[] array = null; + + try { + array = getDelegate() + .selectTriggersForJob(conn, jobName, groupName); + } catch (Exception e) { + throw new JobPersistenceException( + "Couldn't obtain triggers for job: " + e.getMessage(), e); + } + + return array; + } + + /** + *

+ * Pause the {@link org.quartz.Trigger} with the given name. + *

+ * + * @see #resumeTrigger(Connection, SchedulingContext, String, String) + */ + public void pauseTrigger(Connection conn, SchedulingContext ctxt, + String triggerName, String groupName) + throws JobPersistenceException { + + try { + String oldState = getDelegate().selectTriggerState(conn, + triggerName, groupName); + + if (oldState.equals(STATE_WAITING) + || oldState.equals(STATE_ACQUIRED)) { + + getDelegate().updateTriggerState(conn, triggerName, + groupName, STATE_PAUSED); + } + else if (oldState.equals(STATE_BLOCKED)) { + getDelegate().updateTriggerState(conn, triggerName, + groupName, STATE_PAUSED_BLOCKED); + } + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't pause trigger '" + + groupName + "." + triggerName + "': " + e.getMessage(), e); + } + } + + protected String getStatusForResumedTrigger(Connection conn, + SchedulingContext ctxt, TriggerStatus status) + throws JobPersistenceException { + + try { + String newState = STATE_WAITING; + + List lst = getDelegate() + .selectFiredTriggerRecordsByJob(conn, + status.getJobKey().getName(), + status.getJobKey().getGroup()); + + if (lst.size() > 0) { + FiredTriggerRecord rec = (FiredTriggerRecord) lst.get(0); + if (rec.isJobIsStateful()) // TODO: worry about + // failed/recovering/volatile job + // states? + newState = STATE_BLOCKED; + } + + return newState; + + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't determine new state in order to resume trigger '" + + status.getKey().getGroup() + "." + + status.getKey().getName() + "': " + + e.getMessage(), e); + } + + } + + protected String getNewStatusForTrigger(Connection conn, + SchedulingContext ctxt, String jobName, String groupName) + throws JobPersistenceException { + + try { + String newState = STATE_WAITING; + + List lst = getDelegate().selectFiredTriggerRecordsByJob(conn, + jobName, groupName); + + if (lst.size() > 0) { + FiredTriggerRecord rec = (FiredTriggerRecord) lst.get(0); + if (rec.isJobIsStateful()) // TODO: worry about + // failed/recovering/volatile job + // states? + newState = STATE_BLOCKED; + } + + return newState; + + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't determine state for new trigger: " + + e.getMessage(), e); + } + + } + + /* + * private List findTriggersToBeBlocked(Connection conn, SchedulingContext + * ctxt, String groupName) throws JobPersistenceException { + * + * try { List blockList = new LinkedList(); + * + * List affectingJobs = + * getDelegate().selectStatefulJobsOfTriggerGroup(conn, groupName); + * + * Iterator itr = affectingJobs.iterator(); while(itr.hasNext()) { Key + * jobKey = (Key) itr.next(); + * + * List lst = getDelegate().selectFiredTriggerRecordsByJob(conn, + * jobKey.getName(), jobKey.getGroup()); + * + * This logic is BROKEN... + * + * if(lst.size() > 0) { FiredTriggerRecord rec = + * (FiredTriggerRecord)lst.get(0); if(rec.isJobIsStateful()) // TODO: worry + * about failed/recovering/volatile job states? blockList.add( + * rec.getTriggerKey() ); } } + * + * + * return blockList; } catch (SQLException e) { throw new + * JobPersistenceException ("Couldn't determine states of resumed triggers + * in group '" + groupName + "': " + e.getMessage(), e); } } + */ + + /** + *

+ * Resume (un-pause) the {@link org.quartz.Trigger} with the + * given name. + *

+ * + *

+ * If the Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseTrigger(Connection, SchedulingContext, String, String) + */ + public void resumeTrigger(Connection conn, SchedulingContext ctxt, + String triggerName, String groupName) + throws JobPersistenceException { + try { + + TriggerStatus status = getDelegate().selectTriggerStatus(conn, + triggerName, groupName); + + if (status == null || status.getNextFireTime() == null) return; + + boolean blocked = false; + if(STATE_PAUSED_BLOCKED.equals(status.getStatus())) + blocked = true; + + String newState = getStatusForResumedTrigger(conn, ctxt, status); + + boolean misfired = false; + + if (status.getNextFireTime().before(new Date())) { + misfired = updateMisfiredTrigger(conn, ctxt, triggerName, groupName, + newState, true); + } + + if(!misfired) { + if(blocked) + getDelegate().updateTriggerStateFromOtherState(conn, + triggerName, groupName, newState, STATE_PAUSED_BLOCKED); + else + getDelegate().updateTriggerStateFromOtherState(conn, + triggerName, groupName, newState, STATE_PAUSED); + } + + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't resume trigger '" + + groupName + "." + triggerName + "': " + e.getMessage(), e); + } + } + + /** + *

+ * Pause all of the {@link org.quartz.Trigger}s in the + * given group. + *

+ * + * @see #resumeTriggerGroup(Connection, SchedulingContext, String) + */ + public void pauseTriggerGroup(Connection conn, SchedulingContext ctxt, + String groupName) throws JobPersistenceException { + + try { + + getDelegate().updateTriggerGroupStateFromOtherStates( + conn, groupName, STATE_PAUSED, STATE_ACQUIRED, + STATE_WAITING, STATE_WAITING); + + getDelegate().updateTriggerGroupStateFromOtherState( + conn, groupName, STATE_PAUSED_BLOCKED, STATE_BLOCKED); + + if (!getDelegate().isTriggerGroupPaused(conn, groupName)) { + getDelegate().insertPausedTriggerGroup(conn, groupName); + } + + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't pause trigger group '" + + groupName + "': " + e.getMessage(), e); + } + } + + /** + *

+ * Pause all of the {@link org.quartz.Trigger}s in the + * given group. + *

+ * + * @see #resumeTriggerGroup(Connection, SchedulingContext, String) + */ + public Set getPausedTriggerGroups(Connection conn, SchedulingContext ctxt) + throws JobPersistenceException { + + try { + return getDelegate().selectPausedTriggerGroups(conn); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't determine paused trigger groups: " + e.getMessage(), e); + } + } + + /** + *

+ * Resume (un-pause) all of the {@link org.quartz.Trigger}s + * in the given group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseTriggerGroup(Connection, SchedulingContext, String) + */ + public void resumeTriggerGroup(Connection conn, SchedulingContext ctxt, + String groupName) throws JobPersistenceException { + + try { + + getDelegate().deletePausedTriggerGroup(conn, groupName); + + String[] trigNames = getDelegate().selectTriggersInGroup(conn, + groupName); + + for (int i = 0; i < trigNames.length; i++) { + resumeTrigger(conn, ctxt, trigNames[i], groupName); + } + + // TODO: find an efficient way to resume triggers (better than the + // above)... logic below is broken because of + // findTriggersToBeBlocked() + /* + * int res = + * getDelegate().updateTriggerGroupStateFromOtherState(conn, + * groupName, STATE_WAITING, STATE_PAUSED); + * + * if(res > 0) { + * + * long misfireTime = System.currentTimeMillis(); + * if(getMisfireThreshold() > 0) misfireTime -= + * getMisfireThreshold(); + * + * Key[] misfires = + * getDelegate().selectMisfiredTriggersInGroupInState(conn, + * groupName, STATE_WAITING, misfireTime); + * + * List blockedTriggers = findTriggersToBeBlocked(conn, ctxt, + * groupName); + * + * Iterator itr = blockedTriggers.iterator(); while(itr.hasNext()) { + * Key key = (Key)itr.next(); + * getDelegate().updateTriggerState(conn, key.getName(), + * key.getGroup(), STATE_BLOCKED); } + * + * for(int i=0; i < misfires.length; i++) { String + * newState = STATE_WAITING; + * if(blockedTriggers.contains(misfires[i])) newState = + * STATE_BLOCKED; updateMisfiredTrigger(conn, ctxt, + * misfires[i].getName(), misfires[i].getGroup(), newState, true); } } + */ + + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't pause trigger group '" + + groupName + "': " + e.getMessage(), e); + } + } + + /** + *

+ * Pause all triggers - equivalent of calling pauseTriggerGroup(group) + * on every group. + *

+ * + *

+ * When resumeAll() is called (to un-pause), trigger misfire + * instructions WILL be applied. + *

+ * + * @see #resumeAll(SchedulingContext) + * @see #pauseTriggerGroup(SchedulingContext, String) + */ + public void pauseAll(Connection conn, SchedulingContext ctxt) + throws JobPersistenceException { + + String[] names = getTriggerGroupNames(conn, ctxt); + + for (int i = 0; i < names.length; i++) { + pauseTriggerGroup(conn, ctxt, names[i]); + } + + try { + if (!getDelegate().isTriggerGroupPaused(conn, ALL_GROUPS_PAUSED)) { + getDelegate().insertPausedTriggerGroup(conn, ALL_GROUPS_PAUSED); + } + + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't pause all trigger groups: " + e.getMessage(), e); + } + + } + + /** + * protected + *

+ * Resume (un-pause) all triggers - equivalent of calling resumeTriggerGroup(group) + * on every group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseAll(SchedulingContext) + */ + public void resumeAll(Connection conn, SchedulingContext ctxt) + throws JobPersistenceException { + + String[] names = getTriggerGroupNames(conn, ctxt); + + for (int i = 0; i < names.length; i++) { + resumeTriggerGroup(conn, ctxt, names[i]); + } + + try { + getDelegate().deletePausedTriggerGroup(conn, ALL_GROUPS_PAUSED); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't resume all trigger groups: " + e.getMessage(), e); + } + + } + + private static long ftrCtr = System.currentTimeMillis(); + + protected synchronized String getFiredTriggerRecordId() { + return getInstanceId() + ftrCtr++; + } + + // TODO: this really ought to return something like a FiredTriggerBundle, + // so that the fireInstanceId doesn't have to be on the trigger... + protected Trigger acquireNextTrigger(Connection conn, SchedulingContext ctxt, long noLaterThan) + throws JobPersistenceException { + Trigger nextTrigger = null; + + boolean acquiredOne = false; + + do { + try { + getDelegate().updateTriggerStateFromOtherStatesBeforeTime(conn, + STATE_MISFIRED, STATE_WAITING, STATE_WAITING, + getMisfireTime()); // only waiting + + long nextFireTime = getDelegate().selectNextFireTime(conn); + + if (nextFireTime == 0 || nextFireTime > noLaterThan) + return null; + + Key triggerKey = null; + do { + triggerKey = getDelegate().selectTriggerForFireTime(conn, + nextFireTime); + if (null != triggerKey) { + + int res = getDelegate() + .updateTriggerStateFromOtherState(conn, + triggerKey.getName(), + triggerKey.getGroup(), STATE_ACQUIRED, + STATE_WAITING); + + if (res <= 0) continue; + + nextTrigger = retrieveTrigger(conn, ctxt, triggerKey + .getName(), triggerKey.getGroup()); + + if(nextTrigger == null) continue; + + nextTrigger + .setFireInstanceId(getFiredTriggerRecordId()); + getDelegate().insertFiredTrigger(conn, nextTrigger, + STATE_ACQUIRED, null); + + acquiredOne = true; + } + } while (triggerKey != null && !acquiredOne); + } catch (Exception e) { + throw new JobPersistenceException( + "Couldn't acquire next trigger: " + e.getMessage(), e); + } + + } while (!acquiredOne); + + return nextTrigger; + } + + protected void releaseAcquiredTrigger(Connection conn, + SchedulingContext ctxt, Trigger trigger) + throws JobPersistenceException { + try { + getDelegate().updateTriggerStateFromOtherState(conn, + trigger.getName(), trigger.getGroup(), STATE_WAITING, + STATE_ACQUIRED); + getDelegate().deleteFiredTrigger(conn, trigger.getFireInstanceId()); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't release acquired trigger: " + e.getMessage(), e); + } + } + + protected TriggerFiredBundle triggerFired(Connection conn, + SchedulingContext ctxt, Trigger trigger) + throws JobPersistenceException { + JobDetail job = null; + Calendar cal = null; + + // Make sure trigger wasn't deleted, paused, or completed... + try { // if trigger was deleted, state will be STATE_DELETED + String state = getDelegate().selectTriggerState(conn, + trigger.getName(), trigger.getGroup()); + if (!state.equals(STATE_ACQUIRED)) return null; + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't select trigger state: " + + e.getMessage(), e); + } + + try { + job = retrieveJob(conn, ctxt, trigger.getJobName(), trigger + .getJobGroup()); + if (job == null) { return null; } + } catch (JobPersistenceException jpe) { + try { + getLog().error("Error retrieving job, setting trigger state to ERROR.", jpe); + getDelegate().updateTriggerState(conn, trigger.getName(), + trigger.getGroup(), STATE_ERROR); + } catch (SQLException sqle) { + getLog().error("Unable to set trigger state to ERROR.", sqle); + } + throw jpe; + } + + if (trigger.getCalendarName() != null) { + cal = retrieveCalendar(conn, ctxt, trigger.getCalendarName()); + if (cal == null) { return null; } + } + + try { + getDelegate().deleteFiredTrigger(conn, trigger.getFireInstanceId()); + getDelegate().insertFiredTrigger(conn, trigger, STATE_EXECUTING, + job); + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't insert fired trigger: " + + e.getMessage(), e); + } + + Date prevFireTime = trigger.getPreviousFireTime(); + + // call triggered - to update the trigger's next-fire-time state... + trigger.triggered(cal); + + String state = STATE_WAITING; + boolean force = true; + + if (job.isStateful()) { + state = STATE_BLOCKED; + force = false; + try { + getDelegate().updateTriggerStatesForJobFromOtherState(conn, job.getName(), + job.getGroup(), STATE_BLOCKED, STATE_WAITING); + getDelegate().updateTriggerStatesForJobFromOtherState(conn, job.getName(), + job.getGroup(), STATE_BLOCKED, STATE_ACQUIRED); + getDelegate().updateTriggerStatesForJobFromOtherState(conn, job.getName(), + job.getGroup(), STATE_PAUSED_BLOCKED, STATE_PAUSED); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't update states of blocked triggers: " + + e.getMessage(), e); + } + } + + if (trigger.getNextFireTime() == null) { + state = STATE_COMPLETE; + force = true; + } + + storeTrigger(conn, ctxt, trigger, job, true, state, force, false); + + job.getJobDataMap().clearDirtyFlag(); + + return new TriggerFiredBundle(job, trigger, cal, trigger.getGroup() + .equals(Scheduler.DEFAULT_RECOVERY_GROUP), new Date(), trigger + .getPreviousFireTime(), prevFireTime, trigger.getNextFireTime()); + } + + protected void triggeredJobComplete(Connection conn, + SchedulingContext ctxt, Trigger trigger, JobDetail jobDetail, + int triggerInstCode) throws JobPersistenceException { + try { + if (triggerInstCode == Trigger.INSTRUCTION_DELETE_TRIGGER) { + if(trigger.getNextFireTime() == null) { + // double check for possible reschedule within job + // execution, which would cancel the need to delete... + TriggerStatus stat = getDelegate().selectTriggerStatus( + conn, trigger.getName(), trigger.getGroup()); + if(stat != null && stat.getNextFireTime() == null) { + removeTrigger(conn, ctxt, trigger.getName(), trigger.getGroup()); + } + } + else{ + removeTrigger(conn, ctxt, trigger.getName(), trigger.getGroup()); + } + } else if (triggerInstCode == Trigger.INSTRUCTION_SET_TRIGGER_COMPLETE) { + getDelegate().updateTriggerState(conn, trigger.getName(), + trigger.getGroup(), STATE_COMPLETE); + } else if (triggerInstCode == Trigger.INSTRUCTION_SET_TRIGGER_ERROR) { + getLog().info("Trigger " + trigger.getFullName() + " set to ERROR state."); + getDelegate().updateTriggerState(conn, trigger.getName(), + trigger.getGroup(), STATE_ERROR); + } else if (triggerInstCode == Trigger.INSTRUCTION_SET_ALL_JOB_TRIGGERS_COMPLETE) { + getDelegate().updateTriggerStatesForJob(conn, + trigger.getJobName(), trigger.getJobGroup(), + STATE_COMPLETE); + } else if (triggerInstCode == Trigger.INSTRUCTION_SET_ALL_JOB_TRIGGERS_ERROR) { + getLog().info("All triggers of Job " + + trigger.getFullJobName() + " set to ERROR state."); + getDelegate().updateTriggerStatesForJob(conn, + trigger.getJobName(), trigger.getJobGroup(), + STATE_ERROR); + } + + if (jobDetail.isStateful()) { + getDelegate().updateTriggerStatesForJobFromOtherState(conn, + jobDetail.getName(), jobDetail.getGroup(), + STATE_WAITING, STATE_BLOCKED); + + getDelegate().updateTriggerStatesForJobFromOtherState(conn, + jobDetail.getName(), jobDetail.getGroup(), + STATE_PAUSED, STATE_PAUSED_BLOCKED); + + try { + if (jobDetail.getJobDataMap().isDirty()) { + getDelegate().updateJobData(conn, jobDetail); + } + } catch (IOException e) { + throw new JobPersistenceException( + "Couldn't serialize job data: " + e.getMessage(), e); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't update job data: " + e.getMessage(), e); + } + } + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't update trigger state(s): " + e.getMessage(), e); + } + + try { + getDelegate().deleteFiredTrigger(conn, trigger.getFireInstanceId()); + } catch (SQLException e) { + throw new JobPersistenceException("Couldn't delete fired trigger: " + + e.getMessage(), e); + } + } + + /** + *

+ * Get the driver delegate for DB operations. + *

+ */ + protected DriverDelegate getDelegate() throws NoSuchDelegateException { + if (null == delegate) { + try { + if(delegateClassName != null) + delegateClass = + getClassLoadHelper().loadClass(delegateClassName); + + Constructor ctor = null; + Object[] ctorParams = null; + if (canUseProperties()) { + Class[] ctorParamTypes = new Class[]{Log.class, + String.class, String.class, Boolean.class}; + ctor = delegateClass.getConstructor(ctorParamTypes); + ctorParams = new Object[]{getLog(), tablePrefix, + instanceId, new Boolean(canUseProperties())}; + } else { + Class[] ctorParamTypes = new Class[]{Log.class, + String.class, String.class}; + ctor = delegateClass.getConstructor(ctorParamTypes); + ctorParams = new Object[]{getLog(), tablePrefix, instanceId}; + } + + delegate = (DriverDelegate) ctor.newInstance(ctorParams); + } catch (NoSuchMethodException e) { + throw new NoSuchDelegateException( + "Couldn't find delegate constructor: " + e.getMessage()); + } catch (InstantiationException e) { + throw new NoSuchDelegateException("Couldn't create delegate: " + + e.getMessage()); + } catch (IllegalAccessException e) { + throw new NoSuchDelegateException("Couldn't create delegate: " + + e.getMessage()); + } catch (InvocationTargetException e) { + throw new NoSuchDelegateException("Couldn't create delegate: " + + e.getMessage()); + } catch (ClassNotFoundException e) { + throw new NoSuchDelegateException("Couldn't load delegate class: " + + e.getMessage()); + } + } + + return delegate; + } + + protected Semaphore getLockHandler() { + return lockHandler; + } + + //--------------------------------------------------------------------------- + // Management methods + //--------------------------------------------------------------------------- + + protected abstract boolean doRecoverMisfires() + throws JobPersistenceException; + + protected void signalSchedulingChange() { + signaler.signalSchedulingChange(); + } + + //--------------------------------------------------------------------------- + // Cluster management methods + //--------------------------------------------------------------------------- + + protected abstract boolean doCheckin() throws JobPersistenceException; + + protected boolean firstCheckIn = true; + + protected long lastCheckin = System.currentTimeMillis(); + + /** + * Get a list of all scheduler instances in the cluster that may have failed. + * This includes this scheduler if it has no recoverer and is checking for the + * first time. + */ + protected List findFailedInstances(Connection conn) + throws JobPersistenceException { + + List failedInstances = new LinkedList(); + boolean selfFailed = false; + + long timeNow = System.currentTimeMillis(); + + try { + List states = getDelegate().selectSchedulerStateRecords(conn, null); + // build map of states by Id... + HashMap statesById = new HashMap(); + Iterator itr = states.iterator(); + while (itr.hasNext()) { + SchedulerStateRecord rec = (SchedulerStateRecord) itr.next(); + statesById.put(rec.getSchedulerInstanceId(), rec); + } + + itr = states.iterator(); + while (itr.hasNext()) { + SchedulerStateRecord rec = (SchedulerStateRecord) itr.next(); + + // find own record... + if (rec.getSchedulerInstanceId().equals(getInstanceId())) { + if (firstCheckIn) { + if (rec.getRecoverer() == null) { + failedInstances.add(rec); + } else { + // make sure the recoverer hasn't died itself! + SchedulerStateRecord recOrec = (SchedulerStateRecord)statesById.get(rec.getRecoverer()); + + long failedIfAfter = (recOrec == null) ? timeNow : calcFailedIfAfter(recOrec); + + // if it has failed, then let's become the recoverer + if( failedIfAfter < timeNow || recOrec == null) { + failedInstances.add(rec); + } + } + } + // TODO: revisit when handle self-failed-out impled (see TODO in clusterCheckIn() below) + // else if (rec.getRecoverer() != null) { + // selfFailed = true; + // } + } else { + // find failed instances... + long failedIfAfter = calcFailedIfAfter(rec); + + if (rec.getRecoverer() == null) { + if (failedIfAfter < timeNow) { + failedInstances.add(rec); + } + } else { + // make sure the recoverer hasn't died itself! + SchedulerStateRecord recOrec = (SchedulerStateRecord)statesById.get(rec.getRecoverer()); + + failedIfAfter = (recOrec == null) ? timeNow : calcFailedIfAfter(recOrec); + + // if it has failed, then let's become the recoverer + if (failedIfAfter < timeNow || recOrec == null) { + failedInstances.add(rec); + } + } + } + } + } catch (Exception e) { + lastCheckin = System.currentTimeMillis(); + throw new JobPersistenceException("Failure identifying failed instances when checking-in: " + + e.getMessage(), e); + } + + return failedInstances; + } + + protected long calcFailedIfAfter(SchedulerStateRecord rec) { + return rec.getCheckinTimestamp() + + Math.max(rec.getCheckinInterval(), + (System.currentTimeMillis() - lastCheckin)) + + 7500L; + } + + protected List clusterCheckIn(Connection conn) + throws JobPersistenceException { + + List failedInstances = findFailedInstances(conn); + + try { + // TODO: handle self-failed-out + + // check in... + lastCheckin = System.currentTimeMillis(); + if(getDelegate().updateSchedulerState(conn, getInstanceId(), lastCheckin, null) == 0) { + getDelegate().insertSchedulerState(conn, getInstanceId(), + lastCheckin, getClusterCheckinInterval(), null); + } + + } catch (Exception e) { + throw new JobPersistenceException("Failure updating scheduler state when checking-in: " + + e.getMessage(), e); + } + + return failedInstances; + } + + protected void clusterRecover(Connection conn, List failedInstances) + throws JobPersistenceException { + + if (failedInstances.size() > 0) { + + long recoverIds = System.currentTimeMillis(); + + logWarnIfNonZero(failedInstances.size(), + "ClusterManager: detected " + failedInstances.size() + + " failed or restarted instances."); + try { + Iterator itr = failedInstances.iterator(); + while (itr.hasNext()) { + SchedulerStateRecord rec = (SchedulerStateRecord) itr + .next(); + + getLog().info( + "ClusterManager: Scanning for instance \"" + + rec.getSchedulerInstanceId() + + "\"'s failed in-progress jobs."); + + List firedTriggerRecs = getDelegate() + .selectInstancesFiredTriggerRecords(conn, + rec.getSchedulerInstanceId()); + + int acquiredCount = 0; + int recoveredCount = 0; + int otherCount = 0; + + Iterator ftItr = firedTriggerRecs.iterator(); + while (ftItr.hasNext()) { + FiredTriggerRecord ftRec = (FiredTriggerRecord) ftItr + .next(); + + Key tKey = ftRec.getTriggerKey(); + Key jKey = ftRec.getJobKey(); + + // release blocked triggers.. + if (ftRec.getFireInstanceState().equals(STATE_BLOCKED)) { + getDelegate() + .updateTriggerStatesForJobFromOtherState( + conn, jKey.getName(), + jKey.getGroup(), STATE_WAITING, + STATE_BLOCKED); + } + if (ftRec.getFireInstanceState().equals(STATE_PAUSED_BLOCKED)) { + getDelegate() + .updateTriggerStatesForJobFromOtherState( + conn, jKey.getName(), + jKey.getGroup(), STATE_PAUSED, + STATE_PAUSED_BLOCKED); + } + + // release acquired triggers.. + if (ftRec.getFireInstanceState().equals(STATE_ACQUIRED)) { + getDelegate().updateTriggerStateFromOtherState( + conn, tKey.getName(), tKey.getGroup(), + STATE_WAITING, STATE_ACQUIRED); + acquiredCount++; + }// handle jobs marked for recovery that were not fully + // executed.. + else if (ftRec.isJobRequestsRecovery()) { + if (jobExists(conn, jKey.getName(), jKey.getGroup())) { + SimpleTrigger rcvryTrig = new SimpleTrigger( + "recover_" + + rec.getSchedulerInstanceId() + + "_" + + String.valueOf(recoverIds++), + Scheduler.DEFAULT_RECOVERY_GROUP, + new Date(ftRec.getFireTimestamp())); + rcvryTrig.setJobName(jKey.getName()); + rcvryTrig.setJobGroup(jKey.getGroup()); + rcvryTrig + .setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW); + JobDataMap jd = getDelegate().selectTriggerJobDataMap(conn, tKey.getName(), tKey.getGroup()); + jd.put("QRTZ_FAILED_JOB_ORIG_TRIGGER_NAME", tKey.getName()); + jd.put("QRTZ_FAILED_JOB_ORIG_TRIGGER_GROUP", tKey.getGroup()); + jd.put("QRTZ_FAILED_JOB_ORIG_TRIGGER_FIRETIME_IN_MILLISECONDS_AS_STRING", String.valueOf(ftRec.getFireTimestamp())); + rcvryTrig.setJobDataMap(jd); + + rcvryTrig.computeFirstFireTime(null); + storeTrigger(conn, null, rcvryTrig, null, false, + STATE_WAITING, false, true); + recoveredCount++; + } else { + getLog() + .warn( + "ClusterManager: failed job '" + + jKey + + "' no longer exists, cannot schedule recovery."); + otherCount++; + } + } else { + otherCount++; + } + + // free up stateful job's triggers + if (ftRec.isJobIsStateful()) { + getDelegate() + .updateTriggerStatesForJobFromOtherState( + conn, jKey.getName(), + jKey.getGroup(), STATE_WAITING, + STATE_BLOCKED); + getDelegate() + .updateTriggerStatesForJobFromOtherState( + conn, jKey.getName(), + jKey.getGroup(), STATE_PAUSED, + STATE_PAUSED_BLOCKED); + } + } + + getDelegate().deleteFiredTriggers(conn, + rec.getSchedulerInstanceId()); + + logWarnIfNonZero(acquiredCount, + "ClusterManager: ......Freed " + acquiredCount + + " acquired trigger(s)."); + logWarnIfNonZero(recoveredCount, + "ClusterManager: ......Scheduled " + recoveredCount + + " recoverable job(s) for recovery."); + logWarnIfNonZero(otherCount, + "ClusterManager: ......Cleaned-up " + otherCount + + " other failed job(s)."); + + getDelegate().deleteSchedulerState(conn, + rec.getSchedulerInstanceId()); + + // update record to show that recovery was handled + if (rec.getSchedulerInstanceId().equals(getInstanceId())) { + getDelegate().insertSchedulerState(conn, + rec.getSchedulerInstanceId(), System.currentTimeMillis(), + rec.getCheckinInterval(), null); + } + + } + } catch (Exception e) { + throw new JobPersistenceException("Failure recovering jobs: " + + e.getMessage(), e); + } + } + } + + protected void logWarnIfNonZero(int val, String warning) { + if (val > 0) getLog().info(warning); + else + getLog().debug(warning); + } + + /** + * Closes the supplied connection + * + * @param conn (Optional) + * @throws JobPersistenceException thrown if a SQLException occurs when the + * connection is closed + */ + protected void closeConnection(Connection conn) + throws JobPersistenceException { + + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't close jdbc connection. "+e.getMessage(), e); + } + } + } + + /** + * Rollback the supplied connection + * + * @param conn (Optional) + * @throws JobPersistenceException thrown if a SQLException occurs when the + * connection is rolled back + */ + protected void rollbackConnection(Connection conn) + throws JobPersistenceException { + + if (conn != null) { + try { + conn.rollback(); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't rollback jdbc connection. "+e.getMessage(), e); + } + } + } + /** + * Commit the supplied connection + * + * @param conn (Optional) + * @throws JobPersistenceException thrown if a SQLException occurs when the + * connection is committed + */ + protected void commitConnection(Connection conn) + throws JobPersistenceException { + + if (conn != null) { + try { + conn.commit(); + } catch (SQLException e) { + throw new JobPersistenceException( + "Couldn't commit jdbc connection. "+e.getMessage(), e); + } + } + } + + ///////////////////////////////////////////////////////////////////////////// + // + // ClusterManager Thread + // + ///////////////////////////////////////////////////////////////////////////// + + class ClusterManager extends Thread { + + private boolean shutdown = false; + + private JobStoreSupport js; + + private int numFails = 0; + + ClusterManager(JobStoreSupport js) { + this.js = js; + this.setPriority(Thread.NORM_PRIORITY + 2); + this.setName("QuartzScheduler_" + instanceName + "-" + instanceId + "_ClusterManager"); + } + + public void initialize() { + this.manage(); + this.start(); + } + + public void shutdown() { + shutdown = true; + this.interrupt(); + } + + private boolean manage() { + boolean res = false; + try { + + res = js.doCheckin(); + + numFails = 0; + getLog().debug("ClusterManager: Check-in complete."); + } catch (Exception e) { + if(numFails % 4 == 0) + getLog().error( + "ClusterManager: Error managing cluster: " + + e.getMessage(), e); + numFails++; + } + return res; + } + + public void run() { + while (!shutdown) { + + if (!shutdown) { + long timeToSleep = getClusterCheckinInterval(); + long transpiredTime = (System.currentTimeMillis() - lastCheckin); + timeToSleep = timeToSleep - transpiredTime; + if (timeToSleep <= 0) timeToSleep = 100L; + + if(numFails > 0) timeToSleep = Math.max(getDbRetryInterval(), timeToSleep); + + try { + Thread.sleep(timeToSleep); + } catch (Exception ignore) { + } + } + + if (!shutdown && this.manage()) signalSchedulingChange(); + + }//while !shutdown + } + } + + ///////////////////////////////////////////////////////////////////////////// + // + // MisfireHandler Thread + // + ///////////////////////////////////////////////////////////////////////////// + + class MisfireHandler extends Thread { + + private boolean shutdown = false; + + private JobStoreSupport js; + + private int numFails = 0; + + + MisfireHandler(JobStoreSupport js) { + this.js = js; + this.setName("QuartzScheduler_" + instanceName + "-" + instanceId + "_MisfireHandler"); + } + + public void initialize() { + //this.manage(); + this.start(); + } + + public void shutdown() { + shutdown = true; + this.interrupt(); + } + + private boolean manage() { + try { + getLog().debug("MisfireHandler: scanning for misfires..."); + + boolean res = js.doRecoverMisfires(); + numFails = 0; + return res; + } catch (Exception e) { + if(numFails % 4 == 0) + getLog().error( + "MisfireHandler: Error handling misfires: " + + e.getMessage(), e); + numFails++; + } + return false; + } + + public void run() { + + while (!shutdown) { + + long sTime = System.currentTimeMillis(); + + boolean moreToDo = this.manage(); + + if (lastRecoverCount > 0) signalSchedulingChange(); + + long spanTime = System.currentTimeMillis() - sTime; + + if (!shutdown && !moreToDo) { + long timeToSleep = getMisfireThreshold() - spanTime; + if (timeToSleep <= 0) timeToSleep = 50L; + + if(numFails > 0) timeToSleep = Math.max(getDbRetryInterval(), timeToSleep); + + if (timeToSleep > 0) try { + Thread.sleep(timeToSleep); + } catch (Exception ignore) { + } + } + else if(moreToDo) { // short pause to help balance threads... + try { + Thread.sleep(50); + } catch (Exception ignore) { + } + } + + }//while !shutdown + } + } + +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/JobStoreTX.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/JobStoreTX.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/JobStoreTX.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,1424 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import org.quartz.Calendar; +import org.quartz.JobDetail; +import org.quartz.JobPersistenceException; +import org.quartz.ObjectAlreadyExistsException; +import org.quartz.SchedulerConfigException; +import org.quartz.SchedulerException; +import org.quartz.Trigger; +import org.quartz.core.SchedulingContext; +import org.quartz.spi.ClassLoadHelper; +import org.quartz.spi.SchedulerSignaler; +import org.quartz.spi.TriggerFiredBundle; + +import java.sql.Connection; +import java.util.List; +import java.util.Set; + +/** + *

+ * JobStoreTX is meant to be used in a standalone environment. + * Both commit and rollback will be handled by this class. + *

+ * + *

+ * If you need a {@link org.quartz.spi.JobStore} class to use + * within an application-server environment, use {@link + * org.quartz.impl.jdbcjobstore.JobStoreCMT} + * instead. + *

+ * + * @author Jeffrey Wescott + * @author James House + */ +public class JobStoreTX extends JobStoreSupport { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public void initialize(ClassLoadHelper loadHelper, + SchedulerSignaler signaler) throws SchedulerConfigException { + + super.initialize(loadHelper, signaler); + + getLog().info("JobStoreTX initialized."); + } + + //--------------------------------------------------------------------------- + // JobStoreSupport methods + //--------------------------------------------------------------------------- + + /** + *

+ * Recover any failed or misfired jobs and clean up the data store as + * appropriate. + *

+ * + * @throws JobPersistenceException + * if jobs could not be recovered + */ + protected void recoverJobs() throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + recoverJobs(conn); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + protected void cleanVolatileTriggerAndJobs() throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + cleanVolatileTriggerAndJobs(conn); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + //--------------------------------------------------------------------------- + // job / trigger storage methods + //--------------------------------------------------------------------------- + + /** + *

+ * Store the given {@link org.quartz.JobDetail} and {@link org.quartz.Trigger}. + *

+ * + * @param newJob + * The JobDetail to be stored. + * @param newTrigger + * The Trigger to be stored. + * @throws ObjectAlreadyExistsException + * if a Job with the same name/group already + * exists. + */ + public void storeJobAndTrigger(SchedulingContext ctxt, JobDetail newJob, + Trigger newTrigger) throws ObjectAlreadyExistsException, + JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + if(isLockOnInsert()) { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + } + + if (newJob.isVolatile() && !newTrigger.isVolatile()) { + JobPersistenceException jpe = new JobPersistenceException( + "Cannot associate non-volatile " + + "trigger with a volatile job!"); + jpe.setErrorCode(SchedulerException.ERR_CLIENT_ERROR); + throw jpe; + } + + storeJob(conn, ctxt, newJob, false); + storeTrigger(conn, ctxt, newTrigger, newJob, false, + Constants.STATE_WAITING, false, false); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Store the given {@link org.quartz.JobDetail}. + *

+ * + * @param newJob + * The JobDetail to be stored. + * @param replaceExisting + * If true, any Job existing in the + * JobStore with the same name & group should be + * over-written. + * @throws ObjectAlreadyExistsException + * if a Job with the same name/group already + * exists, and replaceExisting is set to false. + */ + public void storeJob(SchedulingContext ctxt, JobDetail newJob, + boolean replaceExisting) throws ObjectAlreadyExistsException, + JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + if(isLockOnInsert() || replaceExisting) { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + } + + storeJob(conn, ctxt, newJob, replaceExisting); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Remove (delete) the {@link org.quartz.Job} with the given + * name, and any {@link org.quartz.Trigger} s that reference + * it. + *

+ * + *

+ * If removal of the Job results in an empty group, the + * group should be removed from the JobStore's list of + * known group names. + *

+ * + * @param jobName + * The name of the Job to be removed. + * @param groupName + * The group name of the Job to be removed. + * @return true if a Job with the given name & + * group was found and removed from the store. + */ + public boolean removeJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + boolean removed = removeJob(conn, ctxt, jobName, groupName, true); + commitConnection(conn); + return removed; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Retrieve the {@link org.quartz.JobDetail} for the given + * {@link org.quartz.Job}. + *

+ * + * @param jobName + * The name of the Job to be retrieved. + * @param groupName + * The group name of the Job to be retrieved. + * @return The desired Job, or null if there is no match. + */ + public JobDetail retrieveJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + JobDetail job = retrieveJob(conn, ctxt, jobName, groupName); + commitConnection(conn); + return job; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Store the given {@link org.quartz.Trigger}. + *

+ * + * @param newTrigger + * The Trigger to be stored. + * @param replaceExisting + * If true, any Trigger existing in + * the JobStore with the same name & group should + * be over-written. + * @throws ObjectAlreadyExistsException + * if a Trigger with the same name/group already + * exists, and replaceExisting is set to false. + */ + public void storeTrigger(SchedulingContext ctxt, Trigger newTrigger, + boolean replaceExisting) throws ObjectAlreadyExistsException, + JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + if(isLockOnInsert() || replaceExisting) { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + } + + storeTrigger(conn, ctxt, newTrigger, null, replaceExisting, + STATE_WAITING, false, false); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Remove (delete) the {@link org.quartz.Trigger} with the + * given name. + *

+ * + *

+ * If removal of the Trigger results in an empty group, the + * group should be removed from the JobStore's list of + * known group names. + *

+ * + *

+ * If removal of the Trigger results in an 'orphaned' Job + * that is not 'durable', then the Job should be deleted + * also. + *

+ * + * @param triggerName + * The name of the Trigger to be removed. + * @param groupName + * The group name of the Trigger to be removed. + * @return true if a Trigger with the given + * name & group was found and removed from the store. + */ + public boolean removeTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + boolean removed = removeTrigger(conn, ctxt, triggerName, groupName); + commitConnection(conn); + return removed; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + * @see org.quartz.spi.JobStore#replaceTrigger(org.quartz.core.SchedulingContext, java.lang.String, java.lang.String, org.quartz.Trigger) + */ + public boolean replaceTrigger(SchedulingContext ctxt, String triggerName, String groupName, Trigger newTrigger) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + boolean removed = replaceTrigger(conn, ctxt, triggerName, groupName, newTrigger); + commitConnection(conn); + return removed; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + + + /** + *

+ * Retrieve the given {@link org.quartz.Trigger}. + *

+ * + * @param triggerName + * The name of the Trigger to be retrieved. + * @param groupName + * The group name of the Trigger to be retrieved. + * @return The desired Trigger, or null if there is no + * match. + */ + public Trigger retrieveTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + Trigger trigger = retrieveTrigger(conn, ctxt, triggerName, + groupName); + commitConnection(conn); + return trigger; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Store the given {@link org.quartz.Calendar}. + *

+ * + * @param calName + * The name of the calendar. + * @param calendar + * The Calendar to be stored. + * @param replaceExisting + * If true, any Calendar existing + * in the JobStore with the same name & group + * should be over-written. + * @throws ObjectAlreadyExistsException + * if a Calendar with the same name already + * exists, and replaceExisting is set to false. + */ + public void storeCalendar(SchedulingContext ctxt, String calName, + Calendar calendar, boolean replaceExisting, boolean updateTriggers) + throws ObjectAlreadyExistsException, JobPersistenceException { + Connection conn = getConnection(); + boolean lockOwner = false; + try { + if(isLockOnInsert() || updateTriggers) { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + lockOwner = true; + } + + storeCalendar(conn, ctxt, calName, calendar, replaceExisting, updateTriggers); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, lockOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Remove (delete) the {@link org.quartz.Calendar} with the + * given name. + *

+ * + *

+ * If removal of the Calendar would result in + * s pointing to non-existent calendars, then a + * JobPersistenceException will be thrown.

+ * * + * @param calName The name of the Calendar to be removed. + * @return true if a Calendar with the given name + * was found and removed from the store. + */ + public boolean removeCalendar(SchedulingContext ctxt, String calName) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean lockOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + lockOwner = true; + + boolean removed = removeCalendar(conn, ctxt, calName); + commitConnection(conn); + return removed; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, lockOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Retrieve the given {@link org.quartz.Trigger}. + *

+ * + * @param calName + * The name of the Calendar to be retrieved. + * @return The desired Calendar, or null if there is no + * match. + */ + public Calendar retrieveCalendar(SchedulingContext ctxt, String calName) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + Calendar cal = retrieveCalendar(conn, ctxt, calName); + commitConnection(conn); + return cal; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + //--------------------------------------------------------------------------- + // informational methods + //--------------------------------------------------------------------------- + + /** + *

+ * Get the number of {@link org.quartz.Job} s that are + * stored in the JobStore. + *

+ */ + public int getNumberOfJobs(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + int numJobs = getNumberOfJobs(conn, ctxt); + commitConnection(conn); + return numJobs; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the number of {@link org.quartz.Trigger} s that are + * stored in the JobsStore. + *

+ */ + public int getNumberOfTriggers(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + int numTriggers = getNumberOfTriggers(conn, ctxt); + commitConnection(conn); + return numTriggers; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the number of {@link org.quartz.Calendar} s that are + * stored in the JobsStore. + *

+ */ + public int getNumberOfCalendars(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + int numCals = getNumberOfCalendars(conn, ctxt); + commitConnection(conn); + return numCals; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + + public Set getPausedTriggerGroups(SchedulingContext ctxt) + throws JobPersistenceException { + + Connection conn = getConnection(); + try { + // no locks necessary for read... + Set groups = getPausedTriggerGroups(conn, ctxt); + commitConnection(conn); + return groups; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Job} s that + * have the given group name. + *

+ * + *

+ * If there are no jobs in the given group name, the result should be a + * zero-length array (not null). + *

+ */ + public String[] getJobNames(SchedulingContext ctxt, String groupName) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + String[] jobNames = getJobNames(conn, ctxt, groupName); + commitConnection(conn); + return jobNames; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Trigger} s + * that have the given group name. + *

+ * + *

+ * If there are no triggers in the given group name, the result should be a + * zero-length array (not null). + *

+ */ + public String[] getTriggerNames(SchedulingContext ctxt, String groupName) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + String[] triggerNames = getTriggerNames(conn, ctxt, groupName); + commitConnection(conn); + return triggerNames; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Job} + * groups. + *

+ * + *

+ * If there are no known group names, the result should be a zero-length + * array (not null). + *

+ */ + public String[] getJobGroupNames(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + String[] groupNames = getJobGroupNames(conn, ctxt); + commitConnection(conn); + return groupNames; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Trigger} + * groups. + *

+ * + *

+ * If there are no known group names, the result should be a zero-length + * array (not null). + *

+ */ + public String[] getTriggerGroupNames(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + String[] triggerGroups = getTriggerGroupNames(conn, ctxt); + commitConnection(conn); + return triggerGroups; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Calendar} s + * in the JobStore. + *

+ * + *

+ * If there are no Calendars in the given group name, the result should be + * a zero-length array (not null). + *

+ */ + public String[] getCalendarNames(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + String[] calNames = getCalendarNames(conn, ctxt); + commitConnection(conn); + return calNames; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get all of the Triggers that are associated to the given Job. + *

+ * + *

+ * If there are no matches, a zero-length array should be returned. + *

+ */ + public Trigger[] getTriggersForJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return getTriggersForJob(conn, ctxt, jobName, groupName); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + /** + *

+ * Get the current state of the identified {@link Trigger}. + *

+ * + * @see Trigger#STATE_NORMAL + * @see Trigger#STATE_PAUSED + * @see Trigger#STATE_COMPLETE + * @see Trigger#STATE_ERROR + * @see Trigger#STATE_NONE + */ + public int getTriggerState(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + try { + // no locks necessary for read... + return getTriggerState(conn, ctxt, triggerName, groupName); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + closeConnection(conn); + } + } + + //--------------------------------------------------------------------------- + // trigger state manipulation methods + //--------------------------------------------------------------------------- + + /** + *

+ * Pause the {@link org.quartz.Trigger} with the given name. + *

+ * + * @see #resumeTrigger(SchedulingContext, String, String) + */ + public void pauseTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + pauseTrigger(conn, ctxt, triggerName, groupName); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Pause all of the {@link org.quartz.Trigger}s in the + * given group. + *

+ * + * @see #resumeTriggerGroup(SchedulingContext, String) + */ + public void pauseTriggerGroup(SchedulingContext ctxt, String groupName) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + pauseTriggerGroup(conn, ctxt, groupName); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Pause the {@link org.quartz.Job} with the given name - by + * pausing all of its current Triggers. + *

+ * + * @see #resumeJob(SchedulingContext, String, String) + */ + public void pauseJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + Trigger[] triggers = getTriggersForJob(conn, ctxt, jobName, + groupName); + for (int j = 0; j < triggers.length; j++) { + pauseTrigger(conn, ctxt, triggers[j].getName(), triggers[j] + .getGroup()); + } + + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Pause all of the {@link org.quartz.Job}s in the given + * group - by pausing all of their Triggers. + *

+ * + * @see #resumeJobGroup(SchedulingContext, String) + */ + public void pauseJobGroup(SchedulingContext ctxt, String groupName) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + String[] jobNames = getJobNames(conn, ctxt, groupName); + + for (int i = 0; i < jobNames.length; i++) { + Trigger[] triggers = getTriggersForJob(conn, ctxt, jobNames[i], + groupName); + for (int j = 0; j < triggers.length; j++) { + pauseTrigger(conn, ctxt, triggers[j].getName(), triggers[j] + .getGroup()); + } + } + + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Resume (un-pause) the {@link org.quartz.Trigger} with the + * given name. + *

+ * + *

+ * If the Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseTrigger(SchedulingContext, String, String) + */ + public void resumeTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + resumeTrigger(conn, ctxt, triggerName, groupName); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Resume (un-pause) all of the {@link org.quartz.Trigger}s + * in the given group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseTriggerGroup(SchedulingContext, String) + */ + public void resumeTriggerGroup(SchedulingContext ctxt, String groupName) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + resumeTriggerGroup(conn, ctxt, groupName); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Resume (un-pause) the {@link org.quartz.Job} with the + * given name. + *

+ * + *

+ * If any of the Job'sTrigger s missed one + * or more fire-times, then the Trigger's misfire + * instruction will be applied. + *

+ * + * @see #pauseJob(SchedulingContext, String, String) + */ + public void resumeJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + Trigger[] triggers = getTriggersForJob(conn, ctxt, jobName, + groupName); + for (int j = 0; j < triggers.length; j++) { + resumeTrigger(conn, ctxt, triggers[j].getName(), triggers[j] + .getGroup()); + } + + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Resume (un-pause) all of the {@link org.quartz.Job}s in + * the given group. + *

+ * + *

+ * If any of the Job s had Trigger s that + * missed one or more fire-times, then the Trigger's + * misfire instruction will be applied. + *

+ * + * @see #pauseJobGroup(SchedulingContext, String) + */ + public void resumeJobGroup(SchedulingContext ctxt, String groupName) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + String[] jobNames = getJobNames(conn, ctxt, groupName); + + for (int i = 0; i < jobNames.length; i++) { + Trigger[] triggers = getTriggersForJob(conn, ctxt, jobNames[i], + groupName); + for (int j = 0; j < triggers.length; j++) { + resumeTrigger(conn, ctxt, triggers[j].getName(), + triggers[j].getGroup()); + } + } + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Pause all triggers - equivalent of calling pauseTriggerGroup(group) + * on every group. + *

+ * + *

+ * When resumeAll() is called (to un-pause), trigger misfire + * instructions WILL be applied. + *

+ * + * @see #resumeAll(SchedulingContext) + * @see #pauseTriggerGroup(SchedulingContext, String) + */ + public void pauseAll(SchedulingContext ctxt) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + pauseAll(conn, ctxt); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Resume (un-pause) all triggers - equivalent of calling resumeTriggerGroup(group) + * on every group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseAll(SchedulingContext) + */ + public void resumeAll(SchedulingContext ctxt) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + resumeAll(conn, ctxt); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + //--------------------------------------------------------------------------- + // trigger firing methods + //--------------------------------------------------------------------------- + + /** + *

+ * Get a handle to the next trigger to be fired, and mark it as 'reserved' + * by the calling scheduler. + *

+ * + * @see #releaseAcquiredTrigger(SchedulingContext, Trigger) + */ + public Trigger acquireNextTrigger(SchedulingContext ctxt, long noLaterThan) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + Trigger trigger = acquireNextTrigger(conn, ctxt, noLaterThan); + commitConnection(conn); + return trigger; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Inform the JobStore that the scheduler no longer plans to + * fire the given Trigger, that it had previously acquired + * (reserved). + *

+ */ + public void releaseAcquiredTrigger(SchedulingContext ctxt, Trigger trigger) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + releaseAcquiredTrigger(conn, ctxt, trigger); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Inform the JobStore that the scheduler is now firing the + * given Trigger (executing its associated Job), + * that it had previously acquired (reserved). + *

+ * + * @return null if the trigger or it's job or calendar no longer exist, or + * if the trigger was not successfully put into the 'executing' + * state. + */ + public TriggerFiredBundle triggerFired(SchedulingContext ctxt, + Trigger trigger) throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + TriggerFiredBundle tfb = null; + JobPersistenceException err = null; + try { + tfb = triggerFired(conn, ctxt, trigger); + } catch (JobPersistenceException jpe) { + if (jpe.getErrorCode() != SchedulerException.ERR_PERSISTENCE_JOB_DOES_NOT_EXIST) + throw jpe; + err = jpe; + } + + commitConnection(conn); + if (err != null) throw err; + return tfb; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + /** + *

+ * Inform the JobStore that the scheduler has completed the + * firing of the given Trigger (and the execution its + * associated Job), and that the {@link org.quartz.JobDataMap} + * in the given JobDetail should be updated if the Job + * is stateful. + *

+ */ + public void triggeredJobComplete(SchedulingContext ctxt, Trigger trigger, + JobDetail jobDetail, int triggerInstCode) + throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + triggeredJobComplete(conn, ctxt, trigger, jobDetail, + triggerInstCode); + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + protected boolean doRecoverMisfires() throws JobPersistenceException { + Connection conn = getConnection(); + boolean transOwner = false; + boolean moreToDo = false; + try { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + transOwner = true; + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + + try { + moreToDo = recoverMisfiredJobs(conn, false); + } catch (Exception e) { + throw new JobPersistenceException(e.getMessage(), e); + } + + commitConnection(conn); + + return moreToDo; + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + closeConnection(conn); + } + } + } + + protected boolean doCheckin() throws JobPersistenceException { + Connection conn = getConnection(); + + boolean transOwner = false; + boolean transStateOwner = false; + boolean recovered = false; + + try { + // Other than the first time, always checkin first to make sure there is + // work to be done before we aquire / the lock (since that is expensive, + // and is almost never necessary) + List failedRecords = (firstCheckIn) ? null : clusterCheckIn(conn); + + if (firstCheckIn || (failedRecords.size() > 0)) { + getLockHandler().obtainLock(conn, LOCK_STATE_ACCESS); + transStateOwner = true; + + // Now that we own the lock, make sure we still have work to do. + // The first time through, we also need to make sure we update/create our state record + failedRecords = (firstCheckIn) ? clusterCheckIn(conn) : findFailedInstances(conn); + + if (failedRecords.size() > 0) { + getLockHandler().obtainLock(conn, LOCK_TRIGGER_ACCESS); + //getLockHandler().obtainLock(conn, LOCK_JOB_ACCESS); + transOwner = true; + + clusterRecover(conn, failedRecords); + recovered = true; + } + } + commitConnection(conn); + } catch (JobPersistenceException e) { + rollbackConnection(conn); + throw e; + } finally { + try { + releaseLock(conn, LOCK_TRIGGER_ACCESS, transOwner); + } finally { + try { + releaseLock(conn, LOCK_STATE_ACCESS, transStateOwner); + } finally { + closeConnection(conn); + } + } + } + + firstCheckIn = false; + + return recovered; + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/LockException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/LockException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/LockException.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import org.quartz.JobPersistenceException; + +/** + *

+ * Exception class for when there is a failure obtaining or releasing a + * resource lock. + *

+ * + * @see Semaphore + * + * @author James House + */ +public class LockException extends JobPersistenceException { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public LockException(String msg) { + super(msg); + } + + public LockException(String msg, Exception cause) { + super(msg, cause); + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/MSSQLDelegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/MSSQLDelegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/MSSQLDelegate.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,102 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.apache.commons.logging.Log; + +/** + *

+ * This is a driver delegate for the MSSQL JDBC driver. + *

+ * + * @author Jeffrey Wescott + */ +public class MSSQLDelegate extends StdJDBCDelegate { + /** + *

+ * Create new MSSQLDelegate instance. + *

+ * + * @param logger + * the logger to use during execution + * @param tablePrefix + * the prefix of all table names + */ + public MSSQLDelegate(Log log, String tablePrefix, String instanceId) { + super(log, tablePrefix, instanceId); + } + + public MSSQLDelegate(Log log, String tablePrefix, String instanceId, Boolean useProperties) { + super(log, tablePrefix, instanceId, useProperties); + } + + //--------------------------------------------------------------------------- + // protected methods that can be overridden by subclasses + //--------------------------------------------------------------------------- + + /** + *

+ * This method should be overridden by any delegate subclasses that need + * special handling for BLOBs. The default implementation uses standard + * JDBC java.sql.Blob operations. + *

+ * + * @param rs + * the result set, already queued to the correct row + * @param colName + * the column name for the BLOB + * @return the deserialized Object from the ResultSet BLOB + * @throws ClassNotFoundException + * if a class found during deserialization cannot be found + * @throws IOException + * if deserialization causes an error + */ + protected Object getObjectFromBlob(ResultSet rs, String colName) + throws ClassNotFoundException, IOException, SQLException { + InputStream binaryInput = rs.getBinaryStream(colName); + + if(binaryInput == null) + return null; + + ObjectInputStream in = new ObjectInputStream(binaryInput); + Object obj = in.readObject(); + in.close(); + + return obj; + } + + protected Object getJobDetailFromBlob(ResultSet rs, String colName) + throws ClassNotFoundException, IOException, SQLException { + if (canUseProperties()) { + InputStream binaryInput = rs.getBinaryStream(colName); + return binaryInput; + } + return getObjectFromBlob(rs, colName); + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/NoSuchDelegateException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/NoSuchDelegateException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/NoSuchDelegateException.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import org.quartz.JobPersistenceException; + +/** + *

+ * Exception class for when a driver delegate cannot be found for a given + * configuration, or lack thereof. + *

+ * + * @author Jeffrey Wescott + */ +public class NoSuchDelegateException extends JobPersistenceException { + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public NoSuchDelegateException(String msg) { + super(msg); + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/PointbaseDelegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/PointbaseDelegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/PointbaseDelegate.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,531 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.apache.commons.logging.Log; +import org.quartz.Calendar; +import org.quartz.CronTrigger; +import org.quartz.JobDetail; +import org.quartz.SimpleTrigger; +import org.quartz.Trigger; + +/** + *

+ * This is a driver delegate for the Pointbase JDBC driver. + *

+ * + * @author Gregg Freeman + */ +public class PointbaseDelegate extends StdJDBCDelegate { + + //private static Category log = + // Category.getInstance(PointbaseJDBCDelegate.class); + /** + *

+ * Create new PointbaseJDBCDelegate instance. + *

+ * + * @param logger + * the logger to use during execution + * @param tablePrefix + * the prefix of all table names + */ + public PointbaseDelegate(Log logger, String tablePrefix, String instanceId) { + super(logger, tablePrefix, instanceId); + } + + /** + *

+ * Create new PointbaseJDBCDelegate instance. + *

+ * + * @param logger + * the logger to use during execution + * @param tablePrefix + * the prefix of all table names + */ + public PointbaseDelegate(Log logger, String tablePrefix, String instanceId, + Boolean useProperties) { + super(logger, tablePrefix, instanceId, useProperties); + } + + //--------------------------------------------------------------------------- + // jobs + //--------------------------------------------------------------------------- + + /** + *

+ * Insert the job detail record. + *

+ * + * @param conn + * the DB Connection + * @param job + * the job to insert + * @return number of rows inserted + * @throws IOException + * if there were problems serializing the JobDataMap + */ + public int insertJobDetail(Connection conn, JobDetail job) + throws IOException, SQLException { + //log.debug( "Inserting JobDetail " + job ); + ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap()); + int len = baos.toByteArray().length; + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + ps = conn.prepareStatement(rtp(INSERT_JOB_DETAIL)); + ps.setString(1, job.getName()); + ps.setString(2, job.getGroup()); + ps.setString(3, job.getDescription()); + ps.setString(4, job.getJobClass().getName()); + ps.setBoolean(5, job.isDurable()); + ps.setBoolean(6, job.isVolatile()); + ps.setBoolean(7, job.isStateful()); + ps.setBoolean(8, job.requestsRecovery()); + ps.setBinaryStream(9, bais, len); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + String[] jobListeners = job.getJobListenerNames(); + for (int i = 0; jobListeners != null && i < jobListeners.length; i++) + insertJobListener(conn, job, jobListeners[i]); + } + + return insertResult; + } + + /** + *

+ * Update the job detail record. + *

+ * + * @param conn + * the DB Connection + * @param job + * the job to update + * @return number of rows updated + * @throws IOException + * if there were problems serializing the JobDataMap + */ + public int updateJobDetail(Connection conn, JobDetail job) + throws IOException, SQLException { + //log.debug( "Updating job detail " + job ); + ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap()); + int len = baos.toByteArray().length; + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + ps = conn.prepareStatement(rtp(UPDATE_JOB_DETAIL)); + ps.setString(1, job.getDescription()); + ps.setString(2, job.getJobClass().getName()); + ps.setBoolean(3, job.isDurable()); + ps.setBoolean(4, job.isVolatile()); + ps.setBoolean(5, job.isStateful()); + ps.setBoolean(6, job.requestsRecovery()); + ps.setBinaryStream(7, bais, len); + ps.setString(8, job.getName()); + ps.setString(9, job.getGroup()); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + deleteJobListeners(conn, job.getName(), job.getGroup()); + + String[] jobListeners = job.getJobListenerNames(); + for (int i = 0; jobListeners != null && i < jobListeners.length; i++) + insertJobListener(conn, job, jobListeners[i]); + } + + return insertResult; + } + + public int insertTrigger(Connection conn, Trigger trigger, String state, + JobDetail jobDetail) throws SQLException, IOException { + + ByteArrayOutputStream baos = serializeJobData(trigger.getJobDataMap()); + int len = baos.toByteArray().length; + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + ps = conn.prepareStatement(rtp(INSERT_TRIGGER)); + ps.setString(1, trigger.getName()); + ps.setString(2, trigger.getGroup()); + ps.setString(3, trigger.getJobName()); + ps.setString(4, trigger.getJobGroup()); + ps.setBoolean(5, trigger.isVolatile()); + ps.setString(6, trigger.getDescription()); + ps.setBigDecimal(7, new BigDecimal(String.valueOf(trigger + .getNextFireTime().getTime()))); + long prevFireTime = -1; + if (trigger.getPreviousFireTime() != null) { + prevFireTime = trigger.getPreviousFireTime().getTime(); + } + ps.setBigDecimal(8, new BigDecimal(String.valueOf(prevFireTime))); + ps.setString(9, state); + if (trigger instanceof SimpleTrigger) { + ps.setString(10, TTYPE_SIMPLE); + } else if (trigger instanceof CronTrigger) { + ps.setString(10, TTYPE_CRON); + } else { // (trigger instanceof BlobTrigger) + ps.setString(10, TTYPE_BLOB); + } + ps.setBigDecimal(11, new BigDecimal(String.valueOf(trigger + .getStartTime().getTime()))); + long endTime = 0; + if (trigger.getEndTime() != null) { + endTime = trigger.getEndTime().getTime(); + } + ps.setBigDecimal(12, new BigDecimal(String.valueOf(endTime))); + ps.setString(13, trigger.getCalendarName()); + ps.setInt(14, trigger.getMisfireInstruction()); + ps.setBinaryStream(15, bais, len); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + String[] trigListeners = trigger.getTriggerListenerNames(); + for (int i = 0; trigListeners != null && i < trigListeners.length; i++) + insertTriggerListener(conn, trigger, trigListeners[i]); + } + + return insertResult; + } + + public int updateTrigger(Connection conn, Trigger trigger, String state, + JobDetail jobDetail) throws SQLException, IOException { + + ByteArrayOutputStream baos = serializeJobData(trigger.getJobDataMap()); + int len = baos.toByteArray().length; + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + + PreparedStatement ps = null; + + int insertResult = 0; + + + try { + ps = conn.prepareStatement(rtp(UPDATE_TRIGGER)); + + ps.setString(1, trigger.getJobName()); + ps.setString(2, trigger.getJobGroup()); + ps.setBoolean(3, trigger.isVolatile()); + ps.setString(4, trigger.getDescription()); + long nextFireTime = -1; + if (trigger.getNextFireTime() != null) { + nextFireTime = trigger.getNextFireTime().getTime(); + } + ps.setBigDecimal(5, new BigDecimal(String.valueOf(nextFireTime))); + long prevFireTime = -1; + if (trigger.getPreviousFireTime() != null) { + prevFireTime = trigger.getPreviousFireTime().getTime(); + } + ps.setBigDecimal(6, new BigDecimal(String.valueOf(prevFireTime))); + ps.setString(7, state); + if (trigger instanceof SimpleTrigger) { + // updateSimpleTrigger(conn, (SimpleTrigger)trigger); + ps.setString(8, TTYPE_SIMPLE); + } else if (trigger instanceof CronTrigger) { + // updateCronTrigger(conn, (CronTrigger)trigger); + ps.setString(8, TTYPE_CRON); + } else { + // updateBlobTrigger(conn, trigger); + ps.setString(8, TTYPE_BLOB); + } + ps.setBigDecimal(9, new BigDecimal(String.valueOf(trigger + .getStartTime().getTime()))); + long endTime = 0; + if (trigger.getEndTime() != null) { + endTime = trigger.getEndTime().getTime(); + } + ps.setBigDecimal(10, new BigDecimal(String.valueOf(endTime))); + ps.setString(11, trigger.getCalendarName()); + ps.setInt(12, trigger.getMisfireInstruction()); + ps.setBinaryStream(13, bais, len); + ps.setString(14, trigger.getName()); + ps.setString(15, trigger.getGroup()); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + deleteTriggerListeners(conn, trigger.getName(), trigger.getGroup()); + + String[] trigListeners = trigger.getTriggerListenerNames(); + for (int i = 0; trigListeners != null && i < trigListeners.length; i++) + insertTriggerListener(conn, trigger, trigListeners[i]); + } + + return insertResult; + } + + /** + *

+ * Update the job data map for the given job. + *

+ * + * @param conn + * the DB Connection + * @param job + * the job to update + * @return the number of rows updated + */ + public int updateJobData(Connection conn, JobDetail job) + throws IOException, SQLException { + //log.debug( "Updating Job Data for Job " + job ); + ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap()); + int len = baos.toByteArray().length; + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_JOB_DATA)); + ps.setBinaryStream(1, bais, len); + ps.setString(2, job.getName()); + ps.setString(3, job.getGroup()); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + //--------------------------------------------------------------------------- + // triggers + //--------------------------------------------------------------------------- + + //--------------------------------------------------------------------------- + // calendars + //--------------------------------------------------------------------------- + + /** + *

+ * Insert a new calendar. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name for the new calendar + * @param calendar + * the calendar + * @return the number of rows inserted + * @throws IOException + * if there were problems serializing the calendar + */ + public int insertCalendar(Connection conn, String calendarName, + Calendar calendar) throws IOException, SQLException { + //log.debug( "Inserting Calendar " + calendarName + " : " + calendar + // ); + ByteArrayOutputStream baos = serializeObject(calendar); + byte buf[] = baos.toByteArray(); + ByteArrayInputStream bais = new ByteArrayInputStream(buf); + + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(INSERT_CALENDAR)); + ps.setString(1, calendarName); + ps.setBinaryStream(2, bais, buf.length); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Update a calendar. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name for the new calendar + * @param calendar + * the calendar + * @return the number of rows updated + * @throws IOException + * if there were problems serializing the calendar + */ + public int updateCalendar(Connection conn, String calendarName, + Calendar calendar) throws IOException, SQLException { + //log.debug( "Updating calendar " + calendarName + " : " + calendar ); + ByteArrayOutputStream baos = serializeObject(calendar); + byte buf[] = baos.toByteArray(); + ByteArrayInputStream bais = new ByteArrayInputStream(buf); + + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_CALENDAR)); + ps.setBinaryStream(1, bais, buf.length); + ps.setString(2, calendarName); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + //--------------------------------------------------------------------------- + // protected methods that can be overridden by subclasses + //--------------------------------------------------------------------------- + + /** + *

+ * This method should be overridden by any delegate subclasses that need + * special handling for BLOBs. The default implementation uses standard + * JDBC java.sql.Blob operations. + *

+ * + * @param rs + * the result set, already queued to the correct row + * @param colName + * the column name for the BLOB + * @return the deserialized Object from the ResultSet BLOB + * @throws ClassNotFoundException + * if a class found during deserialization cannot be found + * @throws IOException + * if deserialization causes an error + */ + protected Object getObjectFromBlob(ResultSet rs, String colName) + throws ClassNotFoundException, IOException, SQLException { + //log.debug( "Getting blob from column: " + colName ); + Object obj = null; + + byte binaryData[] = rs.getBytes(colName); + + InputStream binaryInput = new ByteArrayInputStream(binaryData); + + if (null != binaryInput) { + ObjectInputStream in = new ObjectInputStream(binaryInput); + obj = in.readObject(); + in.close(); + } + + return obj; + } + + /** + *

+ * This method should be overridden by any delegate subclasses that need + * special handling for BLOBs for job details. The default implementation + * uses standard JDBC java.sql.Blob operations. + *

+ * + * @param rs + * the result set, already queued to the correct row + * @param colName + * the column name for the BLOB + * @return the deserialized Object from the ResultSet BLOB + * @throws ClassNotFoundException + * if a class found during deserialization cannot be found + * @throws IOException + * if deserialization causes an error + */ + protected Object getJobDetailFromBlob(ResultSet rs, String colName) + throws ClassNotFoundException, IOException, SQLException { + //log.debug( "Getting Job details from blob in col " + colName ); + if (canUseProperties()) { + byte data[] = rs.getBytes(colName); + if(data == null) + return null; + InputStream binaryInput = new ByteArrayInputStream(data); + return binaryInput; + } + + return getObjectFromBlob(rs, colName); + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/PostgreSQLDelegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/PostgreSQLDelegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/PostgreSQLDelegate.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,124 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.apache.commons.logging.Log; + +/** + *

+ * This is a driver delegate for the PostgreSQL JDBC driver. + *

+ * + * @author Jeffrey Wescott + */ +public class PostgreSQLDelegate extends StdJDBCDelegate { + /** + *

+ * Create new PostgreSQLDelegate instance. + *

+ * + * @param logger + * the logger to use during execution + * @param tablePrefix + * the prefix of all table names + */ + public PostgreSQLDelegate(Log log, String tablePrefix, String instanceId) { + super(log, tablePrefix, instanceId); + } + + /** + *

+ * Create new PostgreSQLDelegate instance. + *

+ * + * @param logger + * the logger to use during execution + * @param tablePrefix + * the prefix of all table names + * @param useProperties + * use java.util.Properties for storage + */ + public PostgreSQLDelegate(Log log, String tablePrefix, String instanceId, + Boolean useProperties) { + super(log, tablePrefix, instanceId, useProperties); + } + + //--------------------------------------------------------------------------- + // protected methods that can be overridden by subclasses + //--------------------------------------------------------------------------- + + /** + *

+ * This method should be overridden by any delegate subclasses that need + * special handling for BLOBs. The default implementation uses standard + * JDBC java.sql.Blob operations. + *

+ * + * @param rs + * the result set, already queued to the correct row + * @param colName + * the column name for the BLOB + * @return the deserialized Object from the ResultSet BLOB + * @throws ClassNotFoundException + * if a class found during deserialization cannot be found + * @throws IOException + * if deserialization causes an error + */ + protected Object getObjectFromBlob(ResultSet rs, String colName) + throws ClassNotFoundException, IOException, SQLException { + InputStream binaryInput = null; + byte[] bytes = rs.getBytes(colName); + + Object obj = null; + + if(bytes != null) { + binaryInput = new ByteArrayInputStream(bytes); + + ObjectInputStream in = new ObjectInputStream(binaryInput); + obj = in.readObject(); + in.close(); + } + + return obj; + } + + protected Object getJobDetailFromBlob(ResultSet rs, String colName) + throws ClassNotFoundException, IOException, SQLException { + if (canUseProperties()) { + InputStream binaryInput = null; + byte[] bytes = rs.getBytes(colName); + if(bytes == null || bytes.length == 0) + return null; + binaryInput = new ByteArrayInputStream(bytes); + return binaryInput; + } + return getObjectFromBlob(rs, colName); + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/SchedulerStateRecord.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/SchedulerStateRecord.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/SchedulerStateRecord.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,106 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +/** + *

+ * Conveys a scheduler-instance state record. + *

+ * + * @author James House + */ +public class SchedulerStateRecord implements java.io.Serializable { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private String schedulerInstanceId; + + private long checkinTimestamp; + + private long checkinInterval; + + private String recoverer; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + */ + public long getCheckinInterval() { + return checkinInterval; + } + + /** + */ + public long getCheckinTimestamp() { + return checkinTimestamp; + } + + /** + */ + public String getRecoverer() { + return recoverer; + } + + /** + */ + public String getSchedulerInstanceId() { + return schedulerInstanceId; + } + + /** + */ + public void setCheckinInterval(long l) { + checkinInterval = l; + } + + /** + */ + public void setCheckinTimestamp(long l) { + checkinTimestamp = l; + } + + /** + */ + public void setRecoverer(String string) { + recoverer = string; + } + + /** + */ + public void setSchedulerInstanceId(String string) { + schedulerInstanceId = string; + } + +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/Semaphore.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/Semaphore.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/Semaphore.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.sql.Connection; + +/** + * An interface for providing thread/resource locking in order to protect + * resources from being altered by multiple threads at the same time. + * + * @author jhouse + */ +public interface Semaphore { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Grants a lock on the identified resource to the calling thread (blocking + * until it is available). + * + * @return true if the lock was obtained. + */ + boolean obtainLock(Connection conn, String lockName) throws LockException; + + /** + * Release the lock on the identified resource if it is held by the calling + * thread. + */ + void releaseLock(Connection conn, String lockName) throws LockException; + + /** + * Determine whether the calling thread owns a lock on the identified + * resource. + */ + boolean isLockOwner(Connection conn, String lockName) throws LockException; + +} Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/SimpleSemaphore.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/SimpleSemaphore.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/SimpleSemaphore.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,162 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.sql.Connection; +import java.util.HashSet; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * An interface for providing thread/resource locking in order to protect + * resources from being altered by multiple threads at the same time. + * + * @author jhouse + */ +public class SimpleSemaphore implements Semaphore { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + ThreadLocal lockOwners = new ThreadLocal(); + + HashSet locks = new HashSet(); + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + Log getLog() { + return LogFactory.getLog(getClass()); + //return LogFactory.getLog("LOCK:"+Thread.currentThread().getName()); + } + + private HashSet getThreadLocks() { + HashSet threadLocks = (HashSet) lockOwners.get(); + if (threadLocks == null) { + threadLocks = new HashSet(); + lockOwners.set(threadLocks); + } + return threadLocks; + } + + /** + * Grants a lock on the identified resource to the calling thread (blocking + * until it is available). + * + * @return true if the lock was obtained. + */ + public synchronized boolean obtainLock(Connection conn, String lockName) { + + lockName = lockName.intern(); + + Log log = getLog(); + + if(log.isDebugEnabled()) + log.debug( + "Lock '" + lockName + "' is desired by: " + + Thread.currentThread().getName()); + + if (!isLockOwner(conn, lockName)) { + if(log.isDebugEnabled()) + log.debug( + "Lock '" + lockName + "' is being obtained: " + + Thread.currentThread().getName()); + while (locks.contains(lockName)) { + try { + this.wait(); + } catch (InterruptedException ie) { + if(log.isDebugEnabled()) + log.debug( + "Lock '" + lockName + "' was not obtained by: " + + Thread.currentThread().getName()); + } + } + + if(log.isDebugEnabled()) + log.debug( + "Lock '" + lockName + "' given to: " + + Thread.currentThread().getName()); + getThreadLocks().add(lockName); + locks.add(lockName); + } else + if(log.isDebugEnabled()) + log.debug( + "Lock '" + lockName + "' already owned by: " + + Thread.currentThread().getName() + + " -- but not owner!", + new Exception("stack-trace of wrongful returner")); + + return true; + } + + /** + * Release the lock on the identified resource if it is held by the calling + * thread. + */ + public synchronized void releaseLock(Connection conn, String lockName) { + + lockName = lockName.intern(); + + if (isLockOwner(conn, lockName)) { + if(getLog().isDebugEnabled()) + getLog().debug( + "Lock '" + lockName + "' retuned by: " + + Thread.currentThread().getName()); + getThreadLocks().remove(lockName); + locks.remove(lockName); + this.notify(); + } else + if(getLog().isDebugEnabled()) + getLog().debug( + "Lock '" + lockName + "' attempt to retun by: " + + Thread.currentThread().getName() + + " -- but not owner!", + new Exception("stack-trace of wrongful returner")); + } + + /** + * Determine whether the calling thread owns a lock on the identified + * resource. + */ + public synchronized boolean isLockOwner(Connection conn, String lockName) { + + lockName = lockName.intern(); + + return getThreadLocks().contains(lockName); + } + + public void init(Connection conn, List listOfLocks) { + // nothing to do... + } + +} Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/StdJDBCConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/StdJDBCConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/StdJDBCConstants.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,582 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ + +package org.quartz.impl.jdbcjobstore; + +/** + *

+ * This interface extends {@link + * org.quartz.impl.jdbcjobstore.Constants} + * to include the query string constants in use by the {@link + * org.quartz.impl.jdbcjobstore.StdJDBCDelegate} + * class. + *

+ * + * @author Jeffrey Wescott + */ +public interface StdJDBCConstants extends Constants { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + // table prefix substitution string + public static final String TABLE_PREFIX_SUBST = "{0}"; + + // QUERIES + public static final String UPDATE_TRIGGER_STATES_FROM_OTHER_STATES = "UPDATE " + + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + + " SET " + + COL_TRIGGER_STATE + + " = ?" + + " WHERE " + + COL_TRIGGER_STATE + + " = ? OR " + + COL_TRIGGER_STATE + " = ?"; + + public static final String UPDATE_TRIGGER_STATE_FROM_OTHER_STATES_BEFORE_TIME = "UPDATE " + + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + + " SET " + + COL_TRIGGER_STATE + + " = ?" + + " WHERE (" + + COL_TRIGGER_STATE + + " = ? OR " + + COL_TRIGGER_STATE + " = ?) AND " + COL_NEXT_FIRE_TIME + " < ?"; + + public static final String SELECT_MISFIRED_TRIGGERS = "SELECT * FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE " + + COL_NEXT_FIRE_TIME + " < ? ORDER BY START_TIME ASC"; + + public static final String SELECT_TRIGGERS_IN_STATE = "SELECT " + + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + " FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE " + + COL_TRIGGER_STATE + " = ?"; + + public static final String SELECT_MISFIRED_TRIGGERS_IN_STATE = "SELECT " + + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + " FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE " + + COL_NEXT_FIRE_TIME + " < ? AND " + COL_TRIGGER_STATE + " = ?"; + + public static final String SELECT_MISFIRED_TRIGGERS_IN_GROUP_IN_STATE = "SELECT " + + COL_TRIGGER_NAME + + " FROM " + + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + + " WHERE " + + COL_NEXT_FIRE_TIME + + " < ? AND " + + COL_TRIGGER_GROUP + + " = ? AND " + COL_TRIGGER_STATE + " = ?"; + + public static final String SELECT_VOLATILE_TRIGGERS = "SELECT " + + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + " FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE " + COL_IS_VOLATILE + + " = ?"; + + public static final String DELETE_FIRED_TRIGGERS = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_FIRED_TRIGGERS; + + public static final String INSERT_JOB_DETAIL = "INSERT INTO " + + TABLE_PREFIX_SUBST + TABLE_JOB_DETAILS + " (" + COL_JOB_NAME + + ", " + COL_JOB_GROUP + ", " + COL_DESCRIPTION + ", " + + COL_JOB_CLASS + ", " + COL_IS_DURABLE + ", " + COL_IS_VOLATILE + + ", " + COL_IS_STATEFUL + ", " + COL_REQUESTS_RECOVERY + ", " + + COL_JOB_DATAMAP + ") " + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + public static final String UPDATE_JOB_DETAIL = "UPDATE " + + TABLE_PREFIX_SUBST + TABLE_JOB_DETAILS + " SET " + + COL_DESCRIPTION + " = ?, " + COL_JOB_CLASS + " = ?, " + + COL_IS_DURABLE + " = ?, " + COL_IS_VOLATILE + " = ?, " + + COL_IS_STATEFUL + " = ?, " + COL_REQUESTS_RECOVERY + " = ?, " + + COL_JOB_DATAMAP + " = ? " + " WHERE " + COL_JOB_NAME + + " = ? AND " + COL_JOB_GROUP + " = ?"; + + public static final String SELECT_TRIGGERS_FOR_JOB = "SELECT " + + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + " FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE " + COL_JOB_NAME + + " = ? AND " + COL_JOB_GROUP + " = ?"; + + public static final String SELECT_TRIGGERS_FOR_CALENDAR = "SELECT " + + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + " FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE " + COL_CALENDAR_NAME + + " = ?"; + + public static final String SELECT_STATEFUL_JOBS_OF_TRIGGER_GROUP = "SELECT DISTINCT J." + + COL_JOB_NAME + + ", J." + + COL_JOB_GROUP + + " FROM " + + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + + " T, " + + TABLE_PREFIX_SUBST + + TABLE_JOB_DETAILS + + " J WHERE T." + + COL_TRIGGER_GROUP + + " = ? AND T." + + COL_JOB_NAME + + " = J." + + COL_JOB_NAME + + " AND T." + + COL_JOB_GROUP + + " = J." + + COL_JOB_GROUP + + " AND J." + + COL_IS_STATEFUL + " = ?"; + + public static final String DELETE_JOB_LISTENERS = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_JOB_LISTENERS + " WHERE " + + COL_JOB_NAME + " = ? AND " + COL_JOB_GROUP + " = ?"; + + public static final String DELETE_JOB_DETAIL = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_JOB_DETAILS + " WHERE " + COL_JOB_NAME + + " = ? AND " + COL_JOB_GROUP + " = ?"; + + public static final String SELECT_JOB_STATEFUL = "SELECT " + + COL_IS_STATEFUL + " FROM " + TABLE_PREFIX_SUBST + + TABLE_JOB_DETAILS + " WHERE " + COL_JOB_NAME + " = ? AND " + + COL_JOB_GROUP + " = ?"; + + public static final String SELECT_JOB_EXISTENCE = "SELECT " + COL_JOB_NAME + + " FROM " + TABLE_PREFIX_SUBST + TABLE_JOB_DETAILS + " WHERE " + + COL_JOB_NAME + " = ? AND " + COL_JOB_GROUP + " = ?"; + + public static final String UPDATE_JOB_DATA = "UPDATE " + TABLE_PREFIX_SUBST + + TABLE_JOB_DETAILS + " SET " + COL_JOB_DATAMAP + " = ? " + + " WHERE " + COL_JOB_NAME + " = ? AND " + COL_JOB_GROUP + " = ?"; + + public static final String INSERT_JOB_LISTENER = "INSERT INTO " + + TABLE_PREFIX_SUBST + TABLE_JOB_LISTENERS + " (" + COL_JOB_NAME + + ", " + COL_JOB_GROUP + ", " + COL_JOB_LISTENER + + ") VALUES(?, ?, ?)"; + + public static final String SELECT_JOB_LISTENERS = "SELECT " + + COL_JOB_LISTENER + " FROM " + TABLE_PREFIX_SUBST + + TABLE_JOB_LISTENERS + " WHERE " + COL_JOB_NAME + " = ? AND " + + COL_JOB_GROUP + " = ?"; + + public static final String SELECT_JOB_DETAIL = "SELECT *" + " FROM " + + TABLE_PREFIX_SUBST + TABLE_JOB_DETAILS + " WHERE " + COL_JOB_NAME + + " = ? AND " + COL_JOB_GROUP + " = ?"; + + public static final String SELECT_NUM_JOBS = "SELECT COUNT(" + COL_JOB_NAME + + ") " + " FROM " + TABLE_PREFIX_SUBST + TABLE_JOB_DETAILS; + + public static final String SELECT_JOB_GROUPS = "SELECT DISTINCT(" + + COL_JOB_GROUP + ") FROM " + TABLE_PREFIX_SUBST + + TABLE_JOB_DETAILS; + + public static final String SELECT_JOBS_IN_GROUP = "SELECT " + COL_JOB_NAME + + " FROM " + TABLE_PREFIX_SUBST + TABLE_JOB_DETAILS + " WHERE " + + COL_JOB_GROUP + " = ?"; + + public static final String SELECT_VOLATILE_JOBS = "SELECT " + COL_JOB_NAME + + ", " + COL_JOB_GROUP + " FROM " + TABLE_PREFIX_SUBST + + TABLE_JOB_DETAILS + " WHERE " + COL_IS_VOLATILE + " = ?"; + + public static final String INSERT_TRIGGER = "INSERT INTO " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " (" + COL_TRIGGER_NAME + + ", " + COL_TRIGGER_GROUP + ", " + COL_JOB_NAME + ", " + + COL_JOB_GROUP + ", " + COL_IS_VOLATILE + ", " + COL_DESCRIPTION + + ", " + COL_NEXT_FIRE_TIME + ", " + COL_PREV_FIRE_TIME + ", " + + COL_TRIGGER_STATE + ", " + COL_TRIGGER_TYPE + ", " + + COL_START_TIME + ", " + COL_END_TIME + ", " + COL_CALENDAR_NAME + + ", " + COL_MISFIRE_INSTRUCTION + ", " + COL_JOB_DATAMAP + ") " + + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + public static final String INSERT_SIMPLE_TRIGGER = "INSERT INTO " + + TABLE_PREFIX_SUBST + TABLE_SIMPLE_TRIGGERS + " (" + + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + ", " + + COL_REPEAT_COUNT + ", " + COL_REPEAT_INTERVAL + ", " + + COL_TIMES_TRIGGERED + ") " + " VALUES(?, ?, ?, ?, ?)"; + + public static final String INSERT_CRON_TRIGGER = "INSERT INTO " + + TABLE_PREFIX_SUBST + TABLE_CRON_TRIGGERS + " (" + + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + ", " + + COL_CRON_EXPRESSION + ", " + COL_TIME_ZONE_ID + ") " + + " VALUES(?, ?, ?, ?)"; + + public static final String INSERT_BLOB_TRIGGER = "INSERT INTO " + + TABLE_PREFIX_SUBST + TABLE_BLOB_TRIGGERS + " (" + + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + ", " + COL_BLOB + + ") " + " VALUES(?, ?, ?)"; + + public static final String UPDATE_TRIGGER_SKIP_DATA = "UPDATE " + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + " SET " + COL_JOB_NAME + " = ?, " + + COL_JOB_GROUP + " = ?, " + COL_IS_VOLATILE + " = ?, " + + COL_DESCRIPTION + " = ?, " + COL_NEXT_FIRE_TIME + " = ?, " + + COL_PREV_FIRE_TIME + " = ?, " + COL_TRIGGER_STATE + " = ?, " + + COL_TRIGGER_TYPE + " = ?, " + COL_START_TIME + " = ?, " + + COL_END_TIME + " = ?, " + COL_CALENDAR_NAME + " = ?, " + + COL_MISFIRE_INSTRUCTION + " = ? WHERE " + COL_TRIGGER_NAME + + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String UPDATE_TRIGGER = "UPDATE " + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + " SET " + COL_JOB_NAME + " = ?, " + + COL_JOB_GROUP + " = ?, " + COL_IS_VOLATILE + " = ?, " + + COL_DESCRIPTION + " = ?, " + COL_NEXT_FIRE_TIME + " = ?, " + + COL_PREV_FIRE_TIME + " = ?, " + COL_TRIGGER_STATE + " = ?, " + + COL_TRIGGER_TYPE + " = ?, " + COL_START_TIME + " = ?, " + + COL_END_TIME + " = ?, " + COL_CALENDAR_NAME + " = ?, " + + COL_MISFIRE_INSTRUCTION + " = ?, " + COL_JOB_DATAMAP + " = ? WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String UPDATE_SIMPLE_TRIGGER = "UPDATE " + + TABLE_PREFIX_SUBST + TABLE_SIMPLE_TRIGGERS + " SET " + + COL_REPEAT_COUNT + " = ?, " + COL_REPEAT_INTERVAL + " = ?, " + + COL_TIMES_TRIGGERED + " = ? WHERE " + COL_TRIGGER_NAME + + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String UPDATE_CRON_TRIGGER = "UPDATE " + + TABLE_PREFIX_SUBST + TABLE_CRON_TRIGGERS + " SET " + + COL_CRON_EXPRESSION + " = ? WHERE " + COL_TRIGGER_NAME + + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String UPDATE_BLOB_TRIGGER = "UPDATE " + + TABLE_PREFIX_SUBST + TABLE_BLOB_TRIGGERS + " SET " + COL_BLOB + + " = ? WHERE " + COL_TRIGGER_NAME + " = ? AND " + + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_TRIGGER_EXISTENCE = "SELECT " + + COL_TRIGGER_NAME + " FROM " + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + + " WHERE " + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + + " = ?"; + + public static final String UPDATE_TRIGGER_STATE = "UPDATE " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " SET " + COL_TRIGGER_STATE + + " = ?" + " WHERE " + COL_TRIGGER_NAME + " = ? AND " + + COL_TRIGGER_GROUP + " = ?"; + + public static final String UPDATE_TRIGGER_STATE_FROM_STATE = "UPDATE " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " SET " + COL_TRIGGER_STATE + + " = ?" + " WHERE " + COL_TRIGGER_NAME + " = ? AND " + + COL_TRIGGER_GROUP + " = ? AND " + COL_TRIGGER_STATE + " = ?"; + + public static final String UPDATE_TRIGGER_GROUP_STATE = "UPDATE " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " SET " + COL_TRIGGER_STATE + + " = ?"; + + public static final String UPDATE_TRIGGER_GROUP_STATE_FROM_STATE = "UPDATE " + + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + + " SET " + + COL_TRIGGER_STATE + + " = ?" + + " WHERE " + + COL_TRIGGER_GROUP + + " = ? AND " + + COL_TRIGGER_STATE + " = ?"; + + public static final String UPDATE_TRIGGER_STATE_FROM_STATES = "UPDATE " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " SET " + COL_TRIGGER_STATE + + " = ?" + " WHERE " + COL_TRIGGER_NAME + " = ? AND " + + COL_TRIGGER_GROUP + " = ? AND (" + COL_TRIGGER_STATE + " = ? OR " + + COL_TRIGGER_STATE + " = ? OR " + COL_TRIGGER_STATE + " = ?)"; + + public static final String UPDATE_TRIGGER_GROUP_STATE_FROM_STATES = "UPDATE " + + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + + " SET " + + COL_TRIGGER_STATE + + " = ?" + + " WHERE " + + COL_TRIGGER_GROUP + + " = ? AND (" + + COL_TRIGGER_STATE + + " = ? OR " + + COL_TRIGGER_STATE + + " = ? OR " + + COL_TRIGGER_STATE + " = ?)"; + + public static final String UPDATE_JOB_TRIGGER_STATES = "UPDATE " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " SET " + COL_TRIGGER_STATE + + " = ? WHERE " + COL_JOB_NAME + " = ? AND " + COL_JOB_GROUP + + " = ?"; + + public static final String UPDATE_JOB_TRIGGER_STATES_FROM_OTHER_STATE = "UPDATE " + + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + + " SET " + + COL_TRIGGER_STATE + + " = ? WHERE " + + COL_JOB_NAME + + " = ? AND " + + COL_JOB_GROUP + + " = ? AND " + COL_TRIGGER_STATE + " = ?"; + + public static final String DELETE_TRIGGER_LISTENERS = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGER_LISTENERS + " WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String INSERT_TRIGGER_LISTENER = "INSERT INTO " + + TABLE_PREFIX_SUBST + TABLE_TRIGGER_LISTENERS + " (" + + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + ", " + + COL_TRIGGER_LISTENER + ") VALUES(?, ?, ?)"; + + public static final String SELECT_TRIGGER_LISTENERS = "SELECT " + + COL_TRIGGER_LISTENER + " FROM " + TABLE_PREFIX_SUBST + + TABLE_TRIGGER_LISTENERS + " WHERE " + COL_TRIGGER_NAME + + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String DELETE_SIMPLE_TRIGGER = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_SIMPLE_TRIGGERS + " WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String DELETE_CRON_TRIGGER = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_CRON_TRIGGERS + " WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String DELETE_BLOB_TRIGGER = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_BLOB_TRIGGERS + " WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String DELETE_TRIGGER = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_NUM_TRIGGERS_FOR_JOB = "SELECT COUNT(" + + COL_TRIGGER_NAME + ") FROM " + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + " WHERE " + COL_JOB_NAME + " = ? AND " + + COL_JOB_GROUP + " = ?"; + + public static final String SELECT_JOB_FOR_TRIGGER = "SELECT J." + + COL_JOB_NAME + ", J." + COL_JOB_GROUP + ", J." + COL_IS_DURABLE + + ", J." + COL_JOB_CLASS + ", J." + COL_REQUESTS_RECOVERY + " FROM " + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + " T, " + TABLE_PREFIX_SUBST + TABLE_JOB_DETAILS + + " J WHERE T." + COL_TRIGGER_NAME + " = ? AND T." + + COL_TRIGGER_GROUP + " = ? AND T." + COL_JOB_NAME + " = J." + + COL_JOB_NAME + " AND T." + COL_JOB_GROUP + " = J." + + COL_JOB_GROUP; + + public static final String SELECT_TRIGGER = "SELECT *" + " FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_TRIGGER_DATA = "SELECT " + + COL_JOB_DATAMAP + " FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_TRIGGER_STATE = "SELECT " + + COL_TRIGGER_STATE + " FROM " + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + " WHERE " + COL_TRIGGER_NAME + " = ? AND " + + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_TRIGGER_STATUS = "SELECT " + + COL_TRIGGER_STATE + ", " + COL_NEXT_FIRE_TIME + ", " + + COL_JOB_NAME + ", " + COL_JOB_GROUP + " FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_SIMPLE_TRIGGER = "SELECT *" + " FROM " + + TABLE_PREFIX_SUBST + TABLE_SIMPLE_TRIGGERS + " WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_CRON_TRIGGER = "SELECT *" + " FROM " + + TABLE_PREFIX_SUBST + TABLE_CRON_TRIGGERS + " WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_BLOB_TRIGGER = "SELECT *" + " FROM " + + TABLE_PREFIX_SUBST + TABLE_BLOB_TRIGGERS + " WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_NUM_TRIGGERS = "SELECT COUNT(" + + COL_TRIGGER_NAME + ") " + " FROM " + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS; + + public static final String SELECT_NUM_TRIGGERS_IN_GROUP = "SELECT COUNT(" + + COL_TRIGGER_NAME + ") " + " FROM " + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + " WHERE " + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_TRIGGER_GROUPS = "SELECT DISTINCT(" + + COL_TRIGGER_GROUP + ") FROM " + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS; + + public static final String SELECT_TRIGGERS_IN_GROUP = "SELECT " + + COL_TRIGGER_NAME + " FROM " + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + + " WHERE " + COL_TRIGGER_GROUP + " = ?"; + + public static final String INSERT_CALENDAR = "INSERT INTO " + + TABLE_PREFIX_SUBST + TABLE_CALENDARS + " (" + COL_CALENDAR_NAME + + ", " + COL_CALENDAR + ") " + " VALUES(?, ?)"; + + public static final String UPDATE_CALENDAR = "UPDATE " + TABLE_PREFIX_SUBST + + TABLE_CALENDARS + " SET " + COL_CALENDAR + " = ? " + " WHERE " + + COL_CALENDAR_NAME + " = ?"; + + public static final String SELECT_CALENDAR_EXISTENCE = "SELECT " + + COL_CALENDAR_NAME + " FROM " + TABLE_PREFIX_SUBST + + TABLE_CALENDARS + " WHERE " + COL_CALENDAR_NAME + " = ?"; + + public static final String SELECT_CALENDAR = "SELECT *" + " FROM " + + TABLE_PREFIX_SUBST + TABLE_CALENDARS + " WHERE " + + COL_CALENDAR_NAME + " = ?"; + + public static final String SELECT_REFERENCED_CALENDAR = "SELECT " + + COL_CALENDAR_NAME + " FROM " + TABLE_PREFIX_SUBST + + TABLE_TRIGGERS + " WHERE " + COL_CALENDAR_NAME + " = ?"; + + public static final String DELETE_CALENDAR = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_CALENDARS + " WHERE " + + COL_CALENDAR_NAME + " = ?"; + + public static final String SELECT_NUM_CALENDARS = "SELECT COUNT(" + + COL_CALENDAR_NAME + ") " + " FROM " + TABLE_PREFIX_SUBST + + TABLE_CALENDARS; + + public static final String SELECT_CALENDARS = "SELECT " + COL_CALENDAR_NAME + + " FROM " + TABLE_PREFIX_SUBST + TABLE_CALENDARS; + + public static final String SELECT_NEXT_FIRE_TIME = "SELECT MIN(" + + COL_NEXT_FIRE_TIME + ") AS " + ALIAS_COL_NEXT_FIRE_TIME + + " FROM " + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE " + + COL_TRIGGER_STATE + " = ? AND " + COL_NEXT_FIRE_TIME + " >= 0"; + + public static final String SELECT_TRIGGER_FOR_FIRE_TIME = "SELECT " + + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + " FROM " + + TABLE_PREFIX_SUBST + TABLE_TRIGGERS + " WHERE " + + COL_TRIGGER_STATE + " = ? AND " + COL_NEXT_FIRE_TIME + " = ?"; + + public static final String INSERT_FIRED_TRIGGER = "INSERT INTO " + + TABLE_PREFIX_SUBST + TABLE_FIRED_TRIGGERS + " (" + COL_ENTRY_ID + + ", " + COL_TRIGGER_NAME + ", " + COL_TRIGGER_GROUP + ", " + + COL_IS_VOLATILE + ", " + COL_INSTANCE_NAME + ", " + + COL_FIRED_TIME + ", " + COL_ENTRY_STATE + ", " + COL_JOB_NAME + + ", " + COL_JOB_GROUP + ", " + COL_IS_STATEFUL + ", " + + COL_REQUESTS_RECOVERY + + ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + public static final String UPDATE_INSTANCES_FIRED_TRIGGER_STATE = "UPDATE " + + TABLE_PREFIX_SUBST + TABLE_FIRED_TRIGGERS + " SET " + + COL_ENTRY_STATE + " = ? AND " + COL_FIRED_TIME + " = ? WHERE " + + COL_INSTANCE_NAME + " = ?"; + + public static final String SELECT_INSTANCES_FIRED_TRIGGERS = "SELECT * FROM " + + TABLE_PREFIX_SUBST + + TABLE_FIRED_TRIGGERS + + " WHERE " + + COL_INSTANCE_NAME + " = ?"; + + public static final String SELECT_INSTANCES_RECOVERABLE_FIRED_TRIGGERS = "SELECT * FROM " + + TABLE_PREFIX_SUBST + + TABLE_FIRED_TRIGGERS + + " WHERE " + + COL_INSTANCE_NAME + " = ? AND " + COL_REQUESTS_RECOVERY + " = ?"; + + public static final String SELECT_JOB_EXECUTION_COUNT = "SELECT COUNT(" + + COL_TRIGGER_NAME + ") FROM " + TABLE_PREFIX_SUBST + + TABLE_FIRED_TRIGGERS + " WHERE " + COL_JOB_NAME + " = ? AND " + + COL_JOB_GROUP + " = ?"; + + public static final String SELECT_FIRED_TRIGGERS = "SELECT * FROM " + + TABLE_PREFIX_SUBST + TABLE_FIRED_TRIGGERS; + + public static final String SELECT_FIRED_TRIGGER = "SELECT * FROM " + + TABLE_PREFIX_SUBST + TABLE_FIRED_TRIGGERS + " WHERE " + + COL_TRIGGER_NAME + " = ? AND " + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_FIRED_TRIGGER_GROUP = "SELECT * FROM " + + TABLE_PREFIX_SUBST + TABLE_FIRED_TRIGGERS + " WHERE " + + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_FIRED_TRIGGERS_OF_JOB = "SELECT * FROM " + + TABLE_PREFIX_SUBST + TABLE_FIRED_TRIGGERS + " WHERE " + + COL_JOB_NAME + " = ? AND " + COL_JOB_GROUP + " = ?"; + + public static final String SELECT_FIRED_TRIGGERS_OF_JOB_GROUP = "SELECT * FROM " + + TABLE_PREFIX_SUBST + + TABLE_FIRED_TRIGGERS + + " WHERE " + + COL_JOB_GROUP + " = ?"; + + public static final String DELETE_FIRED_TRIGGER = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_FIRED_TRIGGERS + " WHERE " + + COL_ENTRY_ID + " = ?"; + + public static final String DELETE_INSTANCES_FIRED_TRIGGERS = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_FIRED_TRIGGERS + " WHERE " + + COL_INSTANCE_NAME + " = ?"; + + public static final String DELETE_VOLATILE_FIRED_TRIGGERS = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_FIRED_TRIGGERS + " WHERE " + + COL_IS_VOLATILE + " = ?"; + + public static final String DELETE_NO_RECOVERY_FIRED_TRIGGERS = "DELETE FROM " + + TABLE_PREFIX_SUBST + + TABLE_FIRED_TRIGGERS + + " WHERE " + + COL_INSTANCE_NAME + " = ?" + COL_REQUESTS_RECOVERY + " = ?"; + + public static final String INSERT_SCHEDULER_STATE = "INSERT INTO " + + TABLE_PREFIX_SUBST + TABLE_SCHEDULER_STATE + " (" + + COL_INSTANCE_NAME + ", " + COL_LAST_CHECKIN_TIME + ", " + + COL_CHECKIN_INTERVAL + ", " + COL_RECOVERER + + ") VALUES(?, ?, ?, ?)"; + + public static final String SELECT_SCHEDULER_STATE = "SELECT * FROM " + + TABLE_PREFIX_SUBST + TABLE_SCHEDULER_STATE + " WHERE " + + COL_INSTANCE_NAME + " = ?"; + + public static final String SELECT_SCHEDULER_STATES = "SELECT * FROM " + + TABLE_PREFIX_SUBST + TABLE_SCHEDULER_STATE; + + public static final String DELETE_SCHEDULER_STATE = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_SCHEDULER_STATE + " WHERE " + + COL_INSTANCE_NAME + " = ?"; + + public static final String UPDATE_SCHEDULER_STATE = "UPDATE " + + TABLE_PREFIX_SUBST + TABLE_SCHEDULER_STATE + " SET " + + COL_LAST_CHECKIN_TIME + " = ?, " + COL_RECOVERER + " = ? WHERE " + + COL_INSTANCE_NAME + " = ?"; + + public static final String INSERT_PAUSED_TRIGGER_GROUP = "INSERT INTO " + + TABLE_PREFIX_SUBST + TABLE_PAUSED_TRIGGERS + " (" + + COL_TRIGGER_GROUP + ") VALUES(?)"; + + public static final String SELECT_PAUSED_TRIGGER_GROUP = "SELECT " + + COL_TRIGGER_GROUP + " FROM " + TABLE_PREFIX_SUBST + + TABLE_PAUSED_TRIGGERS + " WHERE " + COL_TRIGGER_GROUP + " = ?"; + + public static final String SELECT_PAUSED_TRIGGER_GROUPS = "SELECT " + + COL_TRIGGER_GROUP + " FROM " + TABLE_PREFIX_SUBST + + TABLE_PAUSED_TRIGGERS; + + public static final String DELETE_PAUSED_TRIGGER_GROUP = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_PAUSED_TRIGGERS + " WHERE " + + COL_TRIGGER_GROUP + " = ?"; + + public static final String DELETE_PAUSED_TRIGGER_GROUPS = "DELETE FROM " + + TABLE_PREFIX_SUBST + TABLE_PAUSED_TRIGGERS; + + // CREATE TABLE qrtz_scheduler_state(INSTANCE_NAME VARCHAR2(80) NOT NULL, + // LAST_CHECKIN_TIME NUMBER(13) NOT NULL, CHECKIN_INTERVAL NUMBER(13) NOT + // NULL, RECOVERER VARCHAR2(80) NOT NULL, PRIMARY KEY (INSTANCE_NAME)); + +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/StdJDBCDelegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/StdJDBCDelegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/StdJDBCDelegate.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,4016 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.math.BigDecimal; +import java.sql.Blob; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Iterator; +import java.util.HashMap; +import java.util.Set; +import java.util.Properties; +import java.util.TimeZone; + +import org.apache.commons.logging.Log; +import org.quartz.Calendar; +import org.quartz.CronTrigger; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.Scheduler; +import org.quartz.SimpleTrigger; +import org.quartz.Trigger; +import org.quartz.spi.ClassLoadHelper; +import org.quartz.utils.Key; +import org.quartz.utils.TriggerStatus; + +/** + *

+ * This is meant to be an abstract base class for most, if not all, {@link org.quartz.impl.jdbcjobstore.DriverDelegate} + * implementations. Subclasses should override only those methods that need + * special handling for the DBMS driver in question. + *

+ * + * @author Jeffrey Wescott + * @author James House + */ +public class StdJDBCDelegate implements DriverDelegate, StdJDBCConstants { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected Log logger = null; + + protected String tablePrefix = DEFAULT_TABLE_PREFIX; + + protected String instanceId; + + protected boolean useProperties; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create new StdJDBCDelegate instance. + *

+ * + * @param logger + * the logger to use during execution + * @param tablePrefix + * the prefix of all table names + */ + public StdJDBCDelegate(Log logger, String tablePrefix, String instanceId) { + this.logger = logger; + this.tablePrefix = tablePrefix; + this.instanceId = instanceId; + } + + /** + *

+ * Create new StdJDBCDelegate instance. + *

+ * + * @param logger + * the logger to use during execution + * @param tablePrefix + * the prefix of all table names + */ + public StdJDBCDelegate(Log logger, String tablePrefix, String instanceId, + Boolean useProperties) { + this.logger = logger; + this.tablePrefix = tablePrefix; + this.instanceId = instanceId; + this.useProperties = useProperties.booleanValue(); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected boolean canUseProperties() { + return useProperties; + } + + //--------------------------------------------------------------------------- + // startup / recovery + //--------------------------------------------------------------------------- + + /** + *

+ * Insert the job detail record. + *

+ * + * @param conn + * the DB Connection + * @param newState + * the new state for the triggers + * @param oldState1 + * the first old state to update + * @param oldState2 + * the second old state to update + * @return number of rows updated + */ + public int updateTriggerStatesFromOtherStates(Connection conn, + String newState, String oldState1, String oldState2) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn + .prepareStatement(rtp(UPDATE_TRIGGER_STATES_FROM_OTHER_STATES)); + ps.setString(1, newState); + ps.setString(2, oldState1); + ps.setString(3, oldState2); + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Get the names of all of the triggers that have misfired. + *

+ * + * @param conn + * the DB Connection + * @return an array of {@link + * org.quartz.utils.Key} objects + */ + public Key[] selectMisfiredTriggers(Connection conn, long ts) + throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_MISFIRED_TRIGGERS)); + ps.setBigDecimal(1, new BigDecimal(String.valueOf(ts))); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + String triggerName = rs.getString(COL_TRIGGER_NAME); + String groupName = rs.getString(COL_TRIGGER_GROUP); + list.add(new Key(triggerName, groupName)); + } + Object[] oArr = list.toArray(); + Key[] kArr = new Key[oArr.length]; + System.arraycopy(oArr, 0, kArr, 0, oArr.length); + return kArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select all of the triggers in a given state. + *

+ * + * @param conn + * the DB Connection + * @param state + * the state the triggers must be in + * @return an array of trigger Key s + */ + public Key[] selectTriggersInState(Connection conn, String state) + throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_TRIGGERS_IN_STATE)); + ps.setString(1, state); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + list.add(new Key(rs.getString(1), rs.getString(2))); + } + + Key[] sArr = (Key[]) list.toArray(new Key[list.size()]); + return sArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public Key[] selectMisfiredTriggersInState(Connection conn, String state, + long ts) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_MISFIRED_TRIGGERS_IN_STATE)); + ps.setBigDecimal(1, new BigDecimal(String.valueOf(ts))); + ps.setString(2, state); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + String triggerName = rs.getString(COL_TRIGGER_NAME); + String groupName = rs.getString(COL_TRIGGER_GROUP); + list.add(new Key(triggerName, groupName)); + } + Object[] oArr = list.toArray(); + Key[] kArr = new Key[oArr.length]; + System.arraycopy(oArr, 0, kArr, 0, oArr.length); + return kArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Get the names of all of the triggers in the given group and state that + * have misfired. + *

+ * + * @param conn + * the DB Connection + * @return an array of {@link + * org.quartz.utils.Key} objects + */ + public Key[] selectMisfiredTriggersInGroupInState(Connection conn, + String groupName, String state, long ts) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn + .prepareStatement(rtp(SELECT_MISFIRED_TRIGGERS_IN_GROUP_IN_STATE)); + ps.setBigDecimal(1, new BigDecimal(String.valueOf(ts))); + ps.setString(2, groupName); + ps.setString(3, state); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + String triggerName = rs.getString(COL_TRIGGER_NAME); + list.add(new Key(triggerName, groupName)); + } + Object[] oArr = list.toArray(); + Key[] kArr = new Key[oArr.length]; + System.arraycopy(oArr, 0, kArr, 0, oArr.length); + return kArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select all of the triggers for jobs that are requesting recovery. The + * returned trigger objects will have unique "recoverXXX" trigger names and + * will be in the {@link + * org.quartz.Scheduler}.DEFAULT_RECOVERY_GROUP + * trigger group. + *

+ * + *

+ * In order to preserve the ordering of the triggers, the fire time will be + * set from the COL_FIRED_TIME column in the TABLE_FIRED_TRIGGERS + * table. The caller is responsible for calling computeFirstFireTime + * on each returned trigger. It is also up to the caller to insert the + * returned triggers to ensure that they are fired. + *

+ * + * @param conn + * the DB Connection + * @return an array of {@link org.quartz.Trigger} objects + */ + public Trigger[] selectTriggersForRecoveringJobs(Connection conn) + throws SQLException, IOException, ClassNotFoundException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn + .prepareStatement(rtp(SELECT_INSTANCES_RECOVERABLE_FIRED_TRIGGERS)); + ps.setString(1, instanceId); + ps.setBoolean(2, true); + rs = ps.executeQuery(); + + long dumId = System.currentTimeMillis(); + ArrayList list = new ArrayList(); + while (rs.next()) { + String jobName = rs.getString(COL_JOB_NAME); + String jobGroup = rs.getString(COL_JOB_GROUP); + String trigName = rs.getString(COL_TRIGGER_NAME); + String trigGroup = rs.getString(COL_TRIGGER_GROUP); + long firedTime = rs.getLong(COL_FIRED_TIME); + SimpleTrigger rcvryTrig = new SimpleTrigger("recover_" + + instanceId + "_" + String.valueOf(dumId++), + Scheduler.DEFAULT_RECOVERY_GROUP, new Date(firedTime)); + rcvryTrig.setJobName(jobName); + rcvryTrig.setJobGroup(jobGroup); + rcvryTrig + .setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW); + + JobDataMap jd = selectTriggerJobDataMap(conn, trigName, trigGroup); + jd.put("QRTZ_FAILED_JOB_ORIG_TRIGGER_NAME", trigName); + jd.put("QRTZ_FAILED_JOB_ORIG_TRIGGER_GROUP", trigGroup); + jd.put("QRTZ_FAILED_JOB_ORIG_TRIGGER_FIRETIME_IN_MILLISECONDS_AS_STRING", String.valueOf(firedTime)); + rcvryTrig.setJobDataMap(jd); + + list.add(rcvryTrig); + } + Object[] oArr = list.toArray(); + Trigger[] tArr = new Trigger[oArr.length]; + System.arraycopy(oArr, 0, tArr, 0, oArr.length); + return tArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Delete all fired triggers. + *

+ * + * @param conn + * the DB Connection + * @return the number of rows deleted + */ + public int deleteFiredTriggers(Connection conn) throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(DELETE_FIRED_TRIGGERS)); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int deleteFiredTriggers(Connection conn, String instanceId) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(DELETE_INSTANCES_FIRED_TRIGGERS)); + ps.setString(1, instanceId); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + //--------------------------------------------------------------------------- + // jobs + //--------------------------------------------------------------------------- + + /** + *

+ * Insert the job detail record. + *

+ * + * @param conn + * the DB Connection + * @param job + * the job to insert + * @return number of rows inserted + * @throws IOException + * if there were problems serializing the JobDataMap + */ + public int insertJobDetail(Connection conn, JobDetail job) + throws IOException, SQLException { + ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + ps = conn.prepareStatement(rtp(INSERT_JOB_DETAIL)); + ps.setString(1, job.getName()); + ps.setString(2, job.getGroup()); + ps.setString(3, job.getDescription()); + ps.setString(4, job.getJobClass().getName()); + ps.setBoolean(5, job.isDurable()); + ps.setBoolean(6, job.isVolatile()); + ps.setBoolean(7, job.isStateful()); + ps.setBoolean(8, job.requestsRecovery()); + ps.setBytes(9, baos.toByteArray()); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + String[] jobListeners = job.getJobListenerNames(); + for (int i = 0; jobListeners != null && i < jobListeners.length; i++) + insertJobListener(conn, job, jobListeners[i]); + } + + return insertResult; + } + + /** + *

+ * Update the job detail record. + *

+ * + * @param conn + * the DB Connection + * @param job + * the job to update + * @return number of rows updated + * @throws IOException + * if there were problems serializing the JobDataMap + */ + public int updateJobDetail(Connection conn, JobDetail job) + throws IOException, SQLException { + ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + ps = conn.prepareStatement(rtp(UPDATE_JOB_DETAIL)); + ps.setString(1, job.getDescription()); + ps.setString(2, job.getJobClass().getName()); + ps.setBoolean(3, job.isDurable()); + ps.setBoolean(4, job.isVolatile()); + ps.setBoolean(5, job.isStateful()); + ps.setBoolean(6, job.requestsRecovery()); + ps.setBytes(7, baos.toByteArray()); + ps.setString(8, job.getName()); + ps.setString(9, job.getGroup()); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + deleteJobListeners(conn, job.getName(), job.getGroup()); + + String[] jobListeners = job.getJobListenerNames(); + for (int i = 0; jobListeners != null && i < jobListeners.length; i++) + insertJobListener(conn, job, jobListeners[i]); + } + + return insertResult; + } + + /** + *

+ * Get the names of all of the triggers associated with the given job. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @return an array of {@link + * org.quartz.utils.Key} objects + */ + public Key[] selectTriggerNamesForJob(Connection conn, String jobName, + String groupName) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_TRIGGERS_FOR_JOB)); + ps.setString(1, jobName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(10); + while (rs.next()) { + String trigName = rs.getString(COL_TRIGGER_NAME); + String trigGroup = rs.getString(COL_TRIGGER_GROUP); + list.add(new Key(trigName, trigGroup)); + } + Object[] oArr = list.toArray(); + Key[] kArr = new Key[oArr.length]; + System.arraycopy(oArr, 0, kArr, 0, oArr.length); + return kArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Delete all job listeners for the given job. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @return the number of rows deleted + */ + public int deleteJobListeners(Connection conn, String jobName, + String groupName) throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(DELETE_JOB_LISTENERS)); + ps.setString(1, jobName); + ps.setString(2, groupName); + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Delete the job detail record for the given job. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @return the number of rows deleted + */ + public int deleteJobDetail(Connection conn, String jobName, String groupName) + throws SQLException { + PreparedStatement ps = null; + + try { + logger.debug("Deleting job: " + groupName + "." + jobName); + ps = conn.prepareStatement(rtp(DELETE_JOB_DETAIL)); + ps.setString(1, jobName); + ps.setString(2, groupName); + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Check whether or not the given job is stateful. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @return true if the job exists and is stateful, false otherwise + */ + public boolean isJobStateful(Connection conn, String jobName, + String groupName) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_JOB_STATEFUL)); + ps.setString(1, jobName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + if (!rs.next()) { return false; } + return rs.getBoolean(COL_IS_STATEFUL); + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Check whether or not the given job exists. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @return true if the job exists, false otherwise + */ + public boolean jobExists(Connection conn, String jobName, String groupName) + throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_JOB_EXISTENCE)); + ps.setString(1, jobName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + if (rs.next()) { + return true; + } else { + return false; + } + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + } + + /** + *

+ * Update the job data map for the given job. + *

+ * + * @param conn + * the DB Connection + * @param job + * the job to update + * @return the number of rows updated + */ + public int updateJobData(Connection conn, JobDetail job) + throws IOException, SQLException { + ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap()); + + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_JOB_DATA)); + ps.setBytes(1, baos.toByteArray()); + ps.setString(2, job.getName()); + ps.setString(3, job.getGroup()); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Associate a listener with a job. + *

+ * + * @param conn + * the DB Connection + * @param job + * the job to associate with the listener + * @param listener + * the listener to insert + * @return the number of rows inserted + */ + public int insertJobListener(Connection conn, JobDetail job, String listener) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(INSERT_JOB_LISTENER)); + ps.setString(1, job.getName()); + ps.setString(2, job.getGroup()); + ps.setString(3, listener); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Get all of the listeners for a given job. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the job name whose listeners are wanted + * @param groupName + * the group containing the job + * @return array of String listener names + */ + public String[] selectJobListeners(Connection conn, String jobName, + String groupName) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ArrayList list = new ArrayList(); + ps = conn.prepareStatement(rtp(SELECT_JOB_LISTENERS)); + ps.setString(1, jobName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + while (rs.next()) { + list.add(rs.getString(1)); + } + + Object[] oArr = list.toArray(); + String[] sArr = new String[oArr.length]; + System.arraycopy(oArr, 0, sArr, 0, oArr.length); + return sArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select the JobDetail object for a given job name / group name. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the job name whose listeners are wanted + * @param groupName + * the group containing the job + * @return the populated JobDetail object + * @throws ClassNotFoundException + * if a class found during deserialization cannot be found or if + * the job class could not be found + * @throws IOException + * if deserialization causes an error + */ + public JobDetail selectJobDetail(Connection conn, String jobName, + String groupName, ClassLoadHelper loadHelper) + throws ClassNotFoundException, IOException, SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_JOB_DETAIL)); + ps.setString(1, jobName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + JobDetail job = null; + + if (rs.next()) { + job = new JobDetail(); + + job.setName(rs.getString(COL_JOB_NAME)); + job.setGroup(rs.getString(COL_JOB_GROUP)); + job.setDescription(rs.getString(COL_DESCRIPTION)); + job.setJobClass(loadHelper.loadClass(rs + .getString(COL_JOB_CLASS))); + job.setDurability(rs.getBoolean(COL_IS_DURABLE)); + job.setVolatility(rs.getBoolean(COL_IS_VOLATILE)); + job.setRequestsRecovery(rs.getBoolean(COL_REQUESTS_RECOVERY)); + + Map map = null; + if (canUseProperties()) map = getMapFromProperties(rs); + else + map = (Map) getObjectFromBlob(rs, COL_JOB_DATAMAP); + + if (null != map) { + job.setJobDataMap(new JobDataMap(map)); + } + } + + return job; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + * build Map from java.util.Properties encoding. + */ + private Map getMapFromProperties(ResultSet rs) + throws ClassNotFoundException, IOException, SQLException { + Map map; + InputStream is = (InputStream) getJobDetailFromBlob(rs, COL_JOB_DATAMAP); + if(is == null) + return null; + Properties properties = new Properties(); + if (is != null) properties.load(is); + map = convertFromProperty(properties); + return map; + } + + /** + *

+ * Select the total number of jobs stored. + *

+ * + * @param conn + * the DB Connection + * @return the total number of jobs stored + */ + public int selectNumJobs(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + int count = 0; + ps = conn.prepareStatement(rtp(SELECT_NUM_JOBS)); + rs = ps.executeQuery(); + + if (rs.next()) { + count = rs.getInt(1); + } + + return count; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select all of the job group names that are stored. + *

+ * + * @param conn + * the DB Connection + * @return an array of String group names + */ + public String[] selectJobGroups(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_JOB_GROUPS)); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + list.add(rs.getString(1)); + } + + Object[] oArr = list.toArray(); + String[] sArr = new String[oArr.length]; + System.arraycopy(oArr, 0, sArr, 0, oArr.length); + return sArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select all of the jobs contained in a given group. + *

+ * + * @param conn + * the DB Connection + * @param groupName + * the group containing the jobs + * @return an array of String job names + */ + public String[] selectJobsInGroup(Connection conn, String groupName) + throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_JOBS_IN_GROUP)); + ps.setString(1, groupName); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + list.add(rs.getString(1)); + } + + Object[] oArr = list.toArray(); + String[] sArr = new String[oArr.length]; + System.arraycopy(oArr, 0, sArr, 0, oArr.length); + return sArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + //--------------------------------------------------------------------------- + // triggers + //--------------------------------------------------------------------------- + + /** + *

+ * Insert the base trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @param state + * the state that the trigger should be stored in + * @return the number of rows inserted + */ + public int insertTrigger(Connection conn, Trigger trigger, String state, + JobDetail jobDetail) throws SQLException, IOException { + + ByteArrayOutputStream baos = null; + if(trigger.getJobDataMap().size() > 0) + baos = serializeJobData(trigger.getJobDataMap()); + + PreparedStatement ps = null; + + int insertResult = 0; + + try { + ps = conn.prepareStatement(rtp(INSERT_TRIGGER)); + ps.setString(1, trigger.getName()); + ps.setString(2, trigger.getGroup()); + ps.setString(3, trigger.getJobName()); + ps.setString(4, trigger.getJobGroup()); + ps.setBoolean(5, trigger.isVolatile()); + ps.setString(6, trigger.getDescription()); + ps.setBigDecimal(7, new BigDecimal(String.valueOf(trigger + .getNextFireTime().getTime()))); + long prevFireTime = -1; + if (trigger.getPreviousFireTime() != null) { + prevFireTime = trigger.getPreviousFireTime().getTime(); + } + ps.setBigDecimal(8, new BigDecimal(String.valueOf(prevFireTime))); + ps.setString(9, state); + if (trigger instanceof SimpleTrigger) { + ps.setString(10, TTYPE_SIMPLE); + } else if (trigger instanceof CronTrigger) { + ps.setString(10, TTYPE_CRON); + } else { // (trigger instanceof BlobTrigger) + ps.setString(10, TTYPE_BLOB); + } + ps.setBigDecimal(11, new BigDecimal(String.valueOf(trigger + .getStartTime().getTime()))); + long endTime = 0; + if (trigger.getEndTime() != null) { + endTime = trigger.getEndTime().getTime(); + } + ps.setBigDecimal(12, new BigDecimal(String.valueOf(endTime))); + ps.setString(13, trigger.getCalendarName()); + ps.setInt(14, trigger.getMisfireInstruction()); + if(baos != null) + ps.setBytes(15, baos.toByteArray()); + else + ps.setBytes(15, null); + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + String[] trigListeners = trigger.getTriggerListenerNames(); + for (int i = 0; trigListeners != null && i < trigListeners.length; i++) + insertTriggerListener(conn, trigger, trigListeners[i]); + } + + return insertResult; + } + + /** + *

+ * Insert the simple trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @return the number of rows inserted + */ + public int insertSimpleTrigger(Connection conn, SimpleTrigger trigger) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(INSERT_SIMPLE_TRIGGER)); + ps.setString(1, trigger.getName()); + ps.setString(2, trigger.getGroup()); + ps.setInt(3, trigger.getRepeatCount()); + ps.setBigDecimal(4, new BigDecimal(String.valueOf(trigger + .getRepeatInterval()))); + ps.setInt(5, trigger.getTimesTriggered()); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Insert the cron trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @return the number of rows inserted + */ + public int insertCronTrigger(Connection conn, CronTrigger trigger) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(INSERT_CRON_TRIGGER)); + ps.setString(1, trigger.getName()); + ps.setString(2, trigger.getGroup()); + ps.setString(3, trigger.getCronExpression()); + ps.setString(4, trigger.getTimeZone().getID()); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Insert the blob trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @return the number of rows inserted + */ + public int insertBlobTrigger(Connection conn, Trigger trigger) + throws SQLException, IOException { + PreparedStatement ps = null; + ByteArrayOutputStream os = null; + + try { + // update the blob + os = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(os); + oos.writeObject(trigger); + oos.close(); + + byte[] buf = os.toByteArray(); + ByteArrayInputStream is = new ByteArrayInputStream(buf); + + ps = conn.prepareStatement(rtp(INSERT_BLOB_TRIGGER)); + ps.setString(1, trigger.getName()); + ps.setString(2, trigger.getGroup()); + ps.setBinaryStream(3, is, buf.length); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Update the base trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @param state + * the state that the trigger should be stored in + * @return the number of rows updated + */ + public int updateTrigger(Connection conn, Trigger trigger, String state, + JobDetail jobDetail) throws SQLException, IOException { + + // save some clock cycles by unnecessarily writing job data blob ... + boolean updateJobData = trigger.getJobDataMap().isDirty(); + ByteArrayOutputStream baos = null; + if(updateJobData && trigger.getJobDataMap().size() > 0) + baos = serializeJobData(trigger.getJobDataMap()); + + PreparedStatement ps = null; + + int insertResult = 0; + + + try { + if(updateJobData) + ps = conn.prepareStatement(rtp(UPDATE_TRIGGER)); + else + ps = conn.prepareStatement(rtp(UPDATE_TRIGGER_SKIP_DATA)); + + ps.setString(1, trigger.getJobName()); + ps.setString(2, trigger.getJobGroup()); + ps.setBoolean(3, trigger.isVolatile()); + ps.setString(4, trigger.getDescription()); + long nextFireTime = -1; + if (trigger.getNextFireTime() != null) { + nextFireTime = trigger.getNextFireTime().getTime(); + } + ps.setBigDecimal(5, new BigDecimal(String.valueOf(nextFireTime))); + long prevFireTime = -1; + if (trigger.getPreviousFireTime() != null) { + prevFireTime = trigger.getPreviousFireTime().getTime(); + } + ps.setBigDecimal(6, new BigDecimal(String.valueOf(prevFireTime))); + ps.setString(7, state); + if (trigger instanceof SimpleTrigger) { + // updateSimpleTrigger(conn, (SimpleTrigger)trigger); + ps.setString(8, TTYPE_SIMPLE); + } else if (trigger instanceof CronTrigger) { + // updateCronTrigger(conn, (CronTrigger)trigger); + ps.setString(8, TTYPE_CRON); + } else { + // updateBlobTrigger(conn, trigger); + ps.setString(8, TTYPE_BLOB); + } + ps.setBigDecimal(9, new BigDecimal(String.valueOf(trigger + .getStartTime().getTime()))); + long endTime = 0; + if (trigger.getEndTime() != null) { + endTime = trigger.getEndTime().getTime(); + } + ps.setBigDecimal(10, new BigDecimal(String.valueOf(endTime))); + ps.setString(11, trigger.getCalendarName()); + ps.setInt(12, trigger.getMisfireInstruction()); + if(updateJobData) { + ps.setBytes(13, baos.toByteArray()); + + ps.setString(14, trigger.getName()); + ps.setString(15, trigger.getGroup()); + } + else { + ps.setString(13, trigger.getName()); + ps.setString(14, trigger.getGroup()); + } + + insertResult = ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + if (insertResult > 0) { + deleteTriggerListeners(conn, trigger.getName(), trigger.getGroup()); + + String[] trigListeners = trigger.getTriggerListenerNames(); + for (int i = 0; trigListeners != null && i < trigListeners.length; i++) + insertTriggerListener(conn, trigger, trigListeners[i]); + } + + return insertResult; + } + + /** + *

+ * Update the simple trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @return the number of rows updated + */ + public int updateSimpleTrigger(Connection conn, SimpleTrigger trigger) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_SIMPLE_TRIGGER)); + + ps.setInt(1, trigger.getRepeatCount()); + ps.setBigDecimal(2, new BigDecimal(String.valueOf(trigger + .getRepeatInterval()))); + ps.setInt(3, trigger.getTimesTriggered()); + ps.setString(4, trigger.getName()); + ps.setString(5, trigger.getGroup()); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Update the cron trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @return the number of rows updated + */ + public int updateCronTrigger(Connection conn, CronTrigger trigger) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_CRON_TRIGGER)); + ps.setString(1, trigger.getCronExpression()); + ps.setString(2, trigger.getName()); + ps.setString(3, trigger.getGroup()); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Update the blob trigger data. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger to insert + * @return the number of rows updated + */ + public int updateBlobTrigger(Connection conn, Trigger trigger) + throws SQLException, IOException { + PreparedStatement ps = null; + ByteArrayOutputStream os = null; + + try { + // update the blob + os = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(os); + oos.writeObject(trigger); + oos.close(); + + byte[] buf = os.toByteArray(); + ByteArrayInputStream is = new ByteArrayInputStream(buf); + + ps = conn.prepareStatement(rtp(UPDATE_BLOB_TRIGGER)); + ps.setBinaryStream(1, is, buf.length); + ps.setString(2, trigger.getName()); + ps.setString(3, trigger.getGroup()); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + if (os != null) os.close(); + } + } + + /** + *

+ * Check whether or not a trigger exists. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return true if the trigger exists, false otherwise + */ + public boolean triggerExists(Connection conn, String triggerName, + String groupName) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_TRIGGER_EXISTENCE)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + if (rs.next()) { + return true; + } else { + return false; + } + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Update the state for a given trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @param state + * the new state for the trigger + * @return the number of rows updated + */ + public int updateTriggerState(Connection conn, String triggerName, + String groupName, String state) throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_TRIGGER_STATE)); + ps.setString(1, state); + ps.setString(2, triggerName); + ps.setString(3, groupName); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Update the given trigger to the given new state, if it is one of the + * given old states. + *

+ * + * @param conn + * the DB connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @param newState + * the new state for the trigger + * @param oldState1 + * one of the old state the trigger must be in + * @param oldState2 + * one of the old state the trigger must be in + * @param oldState3 + * one of the old state the trigger must be in + * @return int the number of rows updated + * @throws SQLException + */ + public int updateTriggerStateFromOtherStates(Connection conn, + String triggerName, String groupName, String newState, + String oldState1, String oldState2, String oldState3) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_TRIGGER_STATE_FROM_STATES)); + ps.setString(1, newState); + ps.setString(2, triggerName); + ps.setString(3, groupName); + ps.setString(4, oldState1); + ps.setString(5, oldState2); + ps.setString(6, oldState3); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int updateTriggerStateFromOtherStatesBeforeTime(Connection conn, + String newState, String oldState1, String oldState2, long time) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn + .prepareStatement(rtp(UPDATE_TRIGGER_STATE_FROM_OTHER_STATES_BEFORE_TIME)); + ps.setString(1, newState); + ps.setString(2, oldState1); + ps.setString(3, oldState2); + ps.setLong(4, time); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Update all triggers in the given group to the given new state, if they + * are in one of the given old states. + *

+ * + * @param conn + * the DB connection + * @param groupName + * the group containing the trigger + * @param newState + * the new state for the trigger + * @param oldState1 + * one of the old state the trigger must be in + * @param oldState2 + * one of the old state the trigger must be in + * @param oldState3 + * one of the old state the trigger must be in + * @return int the number of rows updated + * @throws SQLException + */ + public int updateTriggerGroupStateFromOtherStates(Connection conn, + String groupName, String newState, String oldState1, + String oldState2, String oldState3) throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn + .prepareStatement(rtp(UPDATE_TRIGGER_GROUP_STATE_FROM_STATES)); + ps.setString(1, newState); + ps.setString(2, groupName); + ps.setString(3, oldState1); + ps.setString(4, oldState2); + ps.setString(5, oldState3); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Update the given trigger to the given new state, if it is in the given + * old state. + *

+ * + * @param conn + * the DB connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @param newState + * the new state for the trigger + * @param oldState + * the old state the trigger must be in + * @return int the number of rows updated + * @throws SQLException + */ + public int updateTriggerStateFromOtherState(Connection conn, + String triggerName, String groupName, String newState, + String oldState) throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_TRIGGER_STATE_FROM_STATE)); + ps.setString(1, newState); + ps.setString(2, triggerName); + ps.setString(3, groupName); + ps.setString(4, oldState); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Update all of the triggers of the given group to the given new state, if + * they are in the given old state. + *

+ * + * @param conn + * the DB connection + * @param groupName + * the group containing the triggers + * @param newState + * the new state for the trigger group + * @param oldState + * the old state the triggers must be in + * @return int the number of rows updated + * @throws SQLException + */ + public int updateTriggerGroupStateFromOtherState(Connection conn, + String groupName, String newState, String oldState) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn + .prepareStatement(rtp(UPDATE_TRIGGER_GROUP_STATE_FROM_STATE)); + ps.setString(1, newState); + ps.setString(2, groupName); + ps.setString(3, oldState); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Update the states of all triggers associated with the given job. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @param state + * the new state for the triggers + * @return the number of rows updated + */ + public int updateTriggerStatesForJob(Connection conn, String jobName, + String groupName, String state) throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_JOB_TRIGGER_STATES)); + ps.setString(1, state); + ps.setString(2, jobName); + ps.setString(3, groupName); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int updateTriggerStatesForJobFromOtherState(Connection conn, + String jobName, String groupName, String state, String oldState) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn + .prepareStatement(rtp(UPDATE_JOB_TRIGGER_STATES_FROM_OTHER_STATE)); + ps.setString(1, state); + ps.setString(2, jobName); + ps.setString(3, groupName); + ps.setString(4, oldState); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Delete all of the listeners associated with a given trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger whose listeners will be deleted + * @param groupName + * the name of the group containing the trigger + * @return the number of rows deleted + */ + public int deleteTriggerListeners(Connection conn, String triggerName, + String groupName) throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(DELETE_TRIGGER_LISTENERS)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Associate a listener with the given trigger. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger + * @param listener + * the name of the listener to associate with the trigger + * @return the number of rows inserted + */ + public int insertTriggerListener(Connection conn, Trigger trigger, + String listener) throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(INSERT_TRIGGER_LISTENER)); + ps.setString(1, trigger.getName()); + ps.setString(2, trigger.getGroup()); + ps.setString(3, listener); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select the listeners associated with a given trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return array of String trigger listener names + */ + public String[] selectTriggerListeners(Connection conn, String triggerName, + String groupName) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_TRIGGER_LISTENERS)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + list.add(rs.getString(1)); + } + Object[] oArr = list.toArray(); + String[] sArr = new String[oArr.length]; + System.arraycopy(oArr, 0, sArr, 0, oArr.length); + return sArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Delete the simple trigger data for a trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the number of rows deleted + */ + public int deleteSimpleTrigger(Connection conn, String triggerName, + String groupName) throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(DELETE_SIMPLE_TRIGGER)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Delete the cron trigger data for a trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the number of rows deleted + */ + public int deleteCronTrigger(Connection conn, String triggerName, + String groupName) throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(DELETE_CRON_TRIGGER)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Delete the cron trigger data for a trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the number of rows deleted + */ + public int deleteBlobTrigger(Connection conn, String triggerName, + String groupName) throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(DELETE_BLOB_TRIGGER)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Delete the base trigger data for a trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the number of rows deleted + */ + public int deleteTrigger(Connection conn, String triggerName, + String groupName) throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(DELETE_TRIGGER)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select the number of triggers associated with a given job. + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the job + * @param groupName + * the group containing the job + * @return the number of triggers for the given job + */ + public int selectNumTriggersForJob(Connection conn, String jobName, + String groupName) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_NUM_TRIGGERS_FOR_JOB)); + ps.setString(1, jobName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + if (rs.next()) { + return rs.getInt(1); + } else { + return 0; + } + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select the job to which the trigger is associated. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the {@link org.quartz.JobDetail} object + * associated with the given trigger + * @throws SQLException + * @throws ClassNotFoundException + */ + public JobDetail selectJobForTrigger(Connection conn, String triggerName, + String groupName, ClassLoadHelper loadHelper) throws ClassNotFoundException, SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_JOB_FOR_TRIGGER)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + if (rs.next()) { + JobDetail job = new JobDetail(); + job.setName(rs.getString(1)); + job.setGroup(rs.getString(2)); + job.setDurability(rs.getBoolean(3)); + job.setJobClass(loadHelper.loadClass(rs + .getString(4))); + job.setRequestsRecovery(rs.getBoolean(5)); + + return job; + } else { + logger.debug("No job for trigger '" + groupName + "." + + triggerName + "'."); + return null; + } + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select the triggers for a job + *

+ * + * @param conn + * the DB Connection + * @param jobName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return an array of (@link org.quartz.Trigger) objects + * associated with a given job. + * @throws SQLException + */ + public Trigger[] selectTriggersForJob(Connection conn, String jobName, + String groupName) throws SQLException, ClassNotFoundException, + IOException { + + ArrayList trigList = new ArrayList(); + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_TRIGGERS_FOR_JOB)); + ps.setString(1, jobName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + while (rs.next()) { + Trigger t = selectTrigger(conn, + rs.getString(COL_TRIGGER_NAME), + rs.getString(COL_TRIGGER_GROUP)); + if(t != null) + trigList.add(t); + } + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + return (Trigger[]) trigList.toArray(new Trigger[trigList.size()]); + } + + public Trigger[] selectTriggersForCalendar(Connection conn, String calName) + throws SQLException, ClassNotFoundException, IOException { + + ArrayList trigList = new ArrayList(); + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_TRIGGERS_FOR_CALENDAR)); + ps.setString(1, calName); + rs = ps.executeQuery(); + + while (rs.next()) { + trigList.add(selectTrigger(conn, + rs.getString(COL_TRIGGER_NAME), rs + .getString(COL_TRIGGER_GROUP))); + } + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + return (Trigger[]) trigList.toArray(new Trigger[trigList.size()]); + } + + public List selectStatefulJobsOfTriggerGroup(Connection conn, + String groupName) throws SQLException { + ArrayList jobList = new ArrayList(); + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn + .prepareStatement(rtp(SELECT_STATEFUL_JOBS_OF_TRIGGER_GROUP)); + ps.setString(1, groupName); + ps.setBoolean(2, true); + rs = ps.executeQuery(); + + while (rs.next()) { + jobList.add(new Key(rs.getString(COL_JOB_NAME), rs + .getString(COL_JOB_GROUP))); + } + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + return jobList; + } + + /** + *

+ * Select a trigger. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the {@link org.quartz.Trigger} object + */ + public Trigger selectTrigger(Connection conn, String triggerName, + String groupName) throws SQLException, ClassNotFoundException, + IOException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + Trigger trigger = null; + + ps = conn.prepareStatement(rtp(SELECT_TRIGGER)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + if (rs.next()) { + String jobName = rs.getString(COL_JOB_NAME); + String jobGroup = rs.getString(COL_JOB_GROUP); + boolean volatility = rs.getBoolean(COL_IS_VOLATILE); + String description = rs.getString(COL_DESCRIPTION); + long nextFireTime = rs.getLong(COL_NEXT_FIRE_TIME); + long prevFireTime = rs.getLong(COL_PREV_FIRE_TIME); + String triggerType = rs.getString(COL_TRIGGER_TYPE); + long startTime = rs.getLong(COL_START_TIME); + long endTime = rs.getLong(COL_END_TIME); + String calendarName = rs.getString(COL_CALENDAR_NAME); + int misFireInstr = rs.getInt(COL_MISFIRE_INSTRUCTION); + + Map map = null; + if (canUseProperties()) map = getMapFromProperties(rs); + else + map = (Map) getObjectFromBlob(rs, COL_JOB_DATAMAP); + + Date nft = null; + if (nextFireTime > 0) { + nft = new Date(nextFireTime); + } + Date pft = null; + if (prevFireTime > 0) { + pft = new Date(prevFireTime); + } + Date startTimeD = new Date(startTime); + Date endTimeD = null; + if (endTime > 0) { + endTimeD = new Date(endTime); + } + + rs.close(); + ps.close(); + + if (triggerType.equals(TTYPE_SIMPLE)) { + ps = conn.prepareStatement(rtp(SELECT_SIMPLE_TRIGGER)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + if (rs.next()) { + int repeatCount = rs.getInt(COL_REPEAT_COUNT); + long repeatInterval = rs.getLong(COL_REPEAT_INTERVAL); + int timesTriggered = rs.getInt(COL_TIMES_TRIGGERED); + + SimpleTrigger st = new SimpleTrigger(triggerName, + groupName, jobName, jobGroup, startTimeD, + endTimeD, repeatCount, repeatInterval); + st.setCalendarName(calendarName); + st.setMisfireInstruction(misFireInstr); + st.setTimesTriggered(timesTriggered); + st.setVolatility(volatility); + st.setNextFireTime(nft); + st.setPreviousFireTime(pft); + st.setDescription(description); + if (null != map) { + st.setJobDataMap(new JobDataMap(map)); + } + trigger = st; + } + } else if (triggerType.equals(TTYPE_CRON)) { + ps = conn.prepareStatement(rtp(SELECT_CRON_TRIGGER)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + if (rs.next()) { + String cronExpr = rs.getString(COL_CRON_EXPRESSION); + String timeZoneId = rs.getString(COL_TIME_ZONE_ID); + + CronTrigger ct = null; + try { + TimeZone timeZone = null; + if (timeZoneId != null) { + timeZone = TimeZone.getTimeZone(timeZoneId); + } + ct = new CronTrigger(triggerName, groupName, + jobName, jobGroup, startTimeD, endTimeD, + cronExpr, timeZone); + } catch (Exception neverHappens) { + // expr must be valid, or it never would have + // gotten to the store... + } + if (null != ct) { + ct.setCalendarName(calendarName); + ct.setMisfireInstruction(misFireInstr); + ct.setVolatility(volatility); + ct.setNextFireTime(nft); + ct.setPreviousFireTime(pft); + ct.setDescription(description); + if (null != map) { + ct.setJobDataMap(new JobDataMap(map)); + } + trigger = ct; + } + } + } else if (triggerType.equals(TTYPE_BLOB)) { + ps = conn.prepareStatement(rtp(SELECT_BLOB_TRIGGER)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + if (rs.next()) { + trigger = (Trigger) getObjectFromBlob(rs, COL_BLOB); + } + } else { + throw new ClassNotFoundException("class for trigger type '" + + triggerType + "' not found."); + } + } + + return trigger; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select a trigger's JobDataMap. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the {@link org.quartz.JobDataMap} of the Trigger, + * never null, but possibly empty. + */ + public JobDataMap selectTriggerJobDataMap(Connection conn, String triggerName, + String groupName) throws SQLException, ClassNotFoundException, + IOException { + + PreparedStatement ps = null; + ResultSet rs = null; + + try { + Trigger trigger = null; + + ps = conn.prepareStatement(rtp(SELECT_TRIGGER_DATA)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + if (rs.next()) { + + Map map = null; + if (canUseProperties()) + map = getMapFromProperties(rs); + else + map = (Map) getObjectFromBlob(rs, COL_JOB_DATAMAP); + + rs.close(); + ps.close(); + + if (null != map) { + return new JobDataMap(map); + } + } + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + return new JobDataMap(); + } + + + /** + *

+ * Select a trigger' state value. + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return the {@link org.quartz.Trigger} object + */ + public String selectTriggerState(Connection conn, String triggerName, + String groupName) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + String state = null; + + ps = conn.prepareStatement(rtp(SELECT_TRIGGER_STATE)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + if (rs.next()) { + state = rs.getString(COL_TRIGGER_STATE); + } else + state = STATE_DELETED; + + return state.intern(); + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + } + + /** + *

+ * Select a trigger' status (state & next fire time). + *

+ * + * @param conn + * the DB Connection + * @param triggerName + * the name of the trigger + * @param groupName + * the group containing the trigger + * @return a TriggerStatus object, or null + */ + public TriggerStatus selectTriggerStatus(Connection conn, + String triggerName, String groupName) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + TriggerStatus status = null; + + ps = conn.prepareStatement(rtp(SELECT_TRIGGER_STATUS)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + rs = ps.executeQuery(); + + if (rs.next()) { + String state = rs.getString(COL_TRIGGER_STATE); + long nextFireTime = rs.getLong(COL_NEXT_FIRE_TIME); + String jobName = rs.getString(COL_JOB_NAME); + String jobGroup = rs.getString(COL_JOB_GROUP); + + Date nft = null; + if (nextFireTime > 0) { + nft = new Date(nextFireTime); + } + + status = new TriggerStatus(state, nft); + status.setKey(new Key(triggerName, groupName)); + status.setJobKey(new Key(jobName, jobGroup)); + } + + return status; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + } + + /** + *

+ * Select the total number of triggers stored. + *

+ * + * @param conn + * the DB Connection + * @return the total number of triggers stored + */ + public int selectNumTriggers(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + int count = 0; + ps = conn.prepareStatement(rtp(SELECT_NUM_TRIGGERS)); + rs = ps.executeQuery(); + + if (rs.next()) { + count = rs.getInt(1); + } + + return count; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select all of the trigger group names that are stored. + *

+ * + * @param conn + * the DB Connection + * @return an array of String group names + */ + public String[] selectTriggerGroups(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_TRIGGER_GROUPS)); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + list.add(rs.getString(1)); + } + + Object[] oArr = list.toArray(); + String[] sArr = new String[oArr.length]; + System.arraycopy(oArr, 0, sArr, 0, oArr.length); + return sArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select all of the triggers contained in a given group. + *

+ * + * @param conn + * the DB Connection + * @param groupName + * the group containing the triggers + * @return an array of String trigger names + */ + public String[] selectTriggersInGroup(Connection conn, String groupName) + throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_TRIGGERS_IN_GROUP)); + ps.setString(1, groupName); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + list.add(rs.getString(1)); + } + + Object[] oArr = list.toArray(); + String[] sArr = new String[oArr.length]; + System.arraycopy(oArr, 0, sArr, 0, oArr.length); + return sArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int insertPausedTriggerGroup(Connection conn, String groupName) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(INSERT_PAUSED_TRIGGER_GROUP)); + ps.setString(1, groupName); + int rows = ps.executeUpdate(); + + return rows; + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int deletePausedTriggerGroup(Connection conn, String groupName) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(DELETE_PAUSED_TRIGGER_GROUP)); + ps.setString(1, groupName); + int rows = ps.executeUpdate(); + + return rows; + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int deleteAllPausedTriggerGroups(Connection conn) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(DELETE_PAUSED_TRIGGER_GROUPS)); + int rows = ps.executeUpdate(); + + return rows; + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public boolean isTriggerGroupPaused(Connection conn, String groupName) + throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_PAUSED_TRIGGER_GROUP)); + ps.setString(1, groupName); + rs = ps.executeQuery(); + + return rs.next(); + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public boolean isExistingTriggerGroup(Connection conn, String groupName) + throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_NUM_TRIGGERS_IN_GROUP)); + ps.setString(1, groupName); + rs = ps.executeQuery(); + + if (!rs.next()) return false; + + return (rs.getInt(1) > 0); + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + //--------------------------------------------------------------------------- + // calendars + //--------------------------------------------------------------------------- + + /** + *

+ * Insert a new calendar. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name for the new calendar + * @param calendar + * the calendar + * @return the number of rows inserted + * @throws IOException + * if there were problems serializing the calendar + */ + public int insertCalendar(Connection conn, String calendarName, + Calendar calendar) throws IOException, SQLException { + ByteArrayOutputStream baos = serializeObject(calendar); + + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(INSERT_CALENDAR)); + ps.setString(1, calendarName); + ps.setBytes(2, baos.toByteArray()); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Update a calendar. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name for the new calendar + * @param calendar + * the calendar + * @return the number of rows updated + * @throws IOException + * if there were problems serializing the calendar + */ + public int updateCalendar(Connection conn, String calendarName, + Calendar calendar) throws IOException, SQLException { + ByteArrayOutputStream baos = serializeObject(calendar); + + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(UPDATE_CALENDAR)); + ps.setBytes(1, baos.toByteArray()); + ps.setString(2, calendarName); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Check whether or not a calendar exists. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name of the calendar + * @return true if the trigger exists, false otherwise + */ + public boolean calendarExists(Connection conn, String calendarName) + throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_CALENDAR_EXISTENCE)); + ps.setString(1, calendarName); + rs = ps.executeQuery(); + + if (rs.next()) { + return true; + } else { + return false; + } + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select a calendar. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name of the calendar + * @return the Calendar + * @throws ClassNotFoundException + * if a class found during deserialization cannot be found be + * found + * @throws IOException + * if there were problems deserializing the calendar + */ + public Calendar selectCalendar(Connection conn, String calendarName) + throws ClassNotFoundException, IOException, SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + try { + String selCal = rtp(SELECT_CALENDAR); + ps = conn.prepareStatement(selCal); + ps.setString(1, calendarName); + rs = ps.executeQuery(); + + Calendar cal = null; + if (rs.next()) { + cal = (Calendar) getObjectFromBlob(rs, COL_CALENDAR); + } + if (null == cal) { + logger.warn("Couldn't find calendar with name '" + calendarName + + "'."); + } + return cal; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Check whether or not a calendar is referenced by any triggers. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name of the calendar + * @return true if any triggers reference the calendar, false otherwise + */ + public boolean calendarIsReferenced(Connection conn, String calendarName) + throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + try { + ps = conn.prepareStatement(rtp(SELECT_REFERENCED_CALENDAR)); + ps.setString(1, calendarName); + rs = ps.executeQuery(); + + if (rs.next()) { + return true; + } else { + return false; + } + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Delete a calendar. + *

+ * + * @param conn + * the DB Connection + * @param calendarName + * the name of the trigger + * @return the number of rows deleted + */ + public int deleteCalendar(Connection conn, String calendarName) + throws SQLException { + PreparedStatement ps = null; + + try { + ps = conn.prepareStatement(rtp(DELETE_CALENDAR)); + ps.setString(1, calendarName); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select the total number of calendars stored. + *

+ * + * @param conn + * the DB Connection + * @return the total number of calendars stored + */ + public int selectNumCalendars(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + int count = 0; + ps = conn.prepareStatement(rtp(SELECT_NUM_CALENDARS)); + + rs = ps.executeQuery(); + + if (rs.next()) { + count = rs.getInt(1); + } + + return count; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select all of the stored calendars. + *

+ * + * @param conn + * the DB Connection + * @return an array of String calendar names + */ + public String[] selectCalendars(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_CALENDARS)); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + list.add(rs.getString(1)); + } + + Object[] oArr = list.toArray(); + String[] sArr = new String[oArr.length]; + System.arraycopy(oArr, 0, sArr, 0, oArr.length); + return sArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + //--------------------------------------------------------------------------- + // trigger firing + //--------------------------------------------------------------------------- + + /** + *

+ * Select the next time that a trigger will be fired. + *

+ * + * @param conn + * the DB Connection + * @return the next fire time, or 0 if no trigger will be fired + */ + public long selectNextFireTime(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + try { + ps = conn.prepareStatement(rtp(SELECT_NEXT_FIRE_TIME)); + ps.setString(1, STATE_WAITING); + rs = ps.executeQuery(); + + if (rs.next()) { + return rs.getLong(ALIAS_COL_NEXT_FIRE_TIME); + } else { + return 0l; + } + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select the trigger that will be fired at the given fire time. + *

+ * + * @param conn + * the DB Connection + * @param fireTime + * the time that the trigger will be fired + * @return a {@link org.quartz.utils.Key} representing the + * trigger that will be fired at the given fire time, or null if no + * trigger will be fired at that time + */ + public Key selectTriggerForFireTime(Connection conn, long fireTime) + throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + try { + ps = conn.prepareStatement(rtp(SELECT_TRIGGER_FOR_FIRE_TIME)); + ps.setString(1, STATE_WAITING); + ps.setBigDecimal(2, new BigDecimal(String.valueOf(fireTime))); + rs = ps.executeQuery(); + + if (rs.next()) { + return new Key(rs.getString(COL_TRIGGER_NAME), rs + .getString(COL_TRIGGER_GROUP)); + } else { + return null; + } + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Insert a fired trigger. + *

+ * + * @param conn + * the DB Connection + * @param trigger + * the trigger + * @param state + * the state that the trigger should be stored in + * @return the number of rows inserted + */ + public int insertFiredTrigger(Connection conn, Trigger trigger, + String state, JobDetail job) throws SQLException { + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(rtp(INSERT_FIRED_TRIGGER)); + ps.setString(1, trigger.getFireInstanceId()); + ps.setString(2, trigger.getName()); + ps.setString(3, trigger.getGroup()); + ps.setBoolean(4, trigger.isVolatile()); + ps.setString(5, instanceId); + ps.setBigDecimal(6, new BigDecimal(String.valueOf(trigger + .getNextFireTime().getTime()))); + ps.setString(7, state); + if (job != null) { + ps.setString(8, trigger.getJobName()); + ps.setString(9, trigger.getJobGroup()); + ps.setBoolean(10, job.isStateful()); + ps.setBoolean(11, job.requestsRecovery()); + } else { + ps.setString(8, null); + ps.setString(9, null); + ps.setBoolean(10, false); + ps.setBoolean(11, false); + } + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select the states of all fired-trigger records for a given trigger, or + * trigger group if trigger name is null. + *

+ * + * @return a List of FiredTriggerRecord objects. + */ + public List selectFiredTriggerRecords(Connection conn, String triggerName, + String groupName) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + try { + List lst = new LinkedList(); + + if (triggerName != null) { + ps = conn.prepareStatement(rtp(SELECT_FIRED_TRIGGER)); + ps.setString(1, triggerName); + ps.setString(2, groupName); + } else { + ps = conn.prepareStatement(rtp(SELECT_FIRED_TRIGGER_GROUP)); + ps.setString(1, groupName); + } + rs = ps.executeQuery(); + + while (rs.next()) { + FiredTriggerRecord rec = new FiredTriggerRecord(); + + rec.setFireInstanceId(rs.getString(COL_ENTRY_ID)); + rec.setFireInstanceState(rs.getString(COL_ENTRY_STATE)); + rec.setFireTimestamp(rs.getLong(COL_FIRED_TIME)); + rec.setSchedulerInstanceId(rs.getString(COL_INSTANCE_NAME)); + rec.setTriggerIsVolatile(rs.getBoolean(COL_IS_VOLATILE)); + rec.setTriggerKey(new Key(rs.getString(COL_TRIGGER_NAME), rs + .getString(COL_TRIGGER_GROUP))); + if (!rec.getFireInstanceState().equals(STATE_ACQUIRED)) { + rec.setJobIsStateful(rs.getBoolean(COL_IS_STATEFUL)); + rec.setJobRequestsRecovery(rs + .getBoolean(COL_REQUESTS_RECOVERY)); + rec.setJobKey(new Key(rs.getString(COL_JOB_NAME), rs + .getString(COL_JOB_GROUP))); + } + lst.add(rec); + } + + return lst; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Select the states of all fired-trigger records for a given job, or job + * group if job name is null. + *

+ * + * @return a List of FiredTriggerRecord objects. + */ + public List selectFiredTriggerRecordsByJob(Connection conn, String jobName, + String groupName) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + try { + List lst = new LinkedList(); + + if (jobName != null) { + ps = conn.prepareStatement(rtp(SELECT_FIRED_TRIGGERS_OF_JOB)); + ps.setString(1, jobName); + ps.setString(2, groupName); + } else { + ps = conn + .prepareStatement(rtp(SELECT_FIRED_TRIGGERS_OF_JOB_GROUP)); + ps.setString(1, groupName); + } + rs = ps.executeQuery(); + + while (rs.next()) { + FiredTriggerRecord rec = new FiredTriggerRecord(); + + rec.setFireInstanceId(rs.getString(COL_ENTRY_ID)); + rec.setFireInstanceState(rs.getString(COL_ENTRY_STATE)); + rec.setFireTimestamp(rs.getLong(COL_FIRED_TIME)); + rec.setSchedulerInstanceId(rs.getString(COL_INSTANCE_NAME)); + rec.setTriggerIsVolatile(rs.getBoolean(COL_IS_VOLATILE)); + rec.setTriggerKey(new Key(rs.getString(COL_TRIGGER_NAME), rs + .getString(COL_TRIGGER_GROUP))); + if (!rec.getFireInstanceState().equals(STATE_ACQUIRED)) { + rec.setJobIsStateful(rs.getBoolean(COL_IS_STATEFUL)); + rec.setJobRequestsRecovery(rs + .getBoolean(COL_REQUESTS_RECOVERY)); + rec.setJobKey(new Key(rs.getString(COL_JOB_NAME), rs + .getString(COL_JOB_GROUP))); + } + lst.add(rec); + } + + return lst; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + } + + public List selectInstancesFiredTriggerRecords(Connection conn, + String instanceName) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + try { + List lst = new LinkedList(); + + ps = conn.prepareStatement(rtp(SELECT_INSTANCES_FIRED_TRIGGERS)); + ps.setString(1, instanceName); + rs = ps.executeQuery(); + + while (rs.next()) { + FiredTriggerRecord rec = new FiredTriggerRecord(); + + rec.setFireInstanceId(rs.getString(COL_ENTRY_ID)); + rec.setFireInstanceState(rs.getString(COL_ENTRY_STATE)); + rec.setFireTimestamp(rs.getLong(COL_FIRED_TIME)); + rec.setSchedulerInstanceId(rs.getString(COL_INSTANCE_NAME)); + rec.setTriggerIsVolatile(rs.getBoolean(COL_IS_VOLATILE)); + rec.setTriggerKey(new Key(rs.getString(COL_TRIGGER_NAME), rs + .getString(COL_TRIGGER_GROUP))); + if (!rec.getFireInstanceState().equals(STATE_ACQUIRED)) { + rec.setJobIsStateful(rs.getBoolean(COL_IS_STATEFUL)); + rec.setJobRequestsRecovery(rs + .getBoolean(COL_REQUESTS_RECOVERY)); + rec.setJobKey(new Key(rs.getString(COL_JOB_NAME), rs + .getString(COL_JOB_GROUP))); + } + lst.add(rec); + } + + return lst; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * Delete a fired trigger. + *

+ * + * @param conn + * the DB Connection + * @param entryId + * the fired trigger entry to delete + * @return the number of rows deleted + */ + public int deleteFiredTrigger(Connection conn, String entryId) + throws SQLException { + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(rtp(DELETE_FIRED_TRIGGER)); + ps.setString(1, entryId); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int selectJobExecutionCount(Connection conn, String jobName, + String jobGroup) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_JOB_EXECUTION_COUNT)); + ps.setString(1, jobName); + ps.setString(2, jobGroup); + + rs = ps.executeQuery(); + + if (rs.next()) return rs.getInt(1); + else + return 0; + + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int deleteVolatileFiredTriggers(Connection conn) throws SQLException { + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(rtp(DELETE_VOLATILE_FIRED_TRIGGERS)); + ps.setBoolean(1, true); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int insertSchedulerState(Connection conn, String instanceId, + long checkInTime, long interval, String recoverer) + throws SQLException { + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(rtp(INSERT_SCHEDULER_STATE)); + ps.setString(1, instanceId); + ps.setLong(2, checkInTime); + ps.setLong(3, interval); + ps.setString(4, recoverer); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int deleteSchedulerState(Connection conn, String instanceId) + throws SQLException { + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(rtp(DELETE_SCHEDULER_STATE)); + ps.setString(1, instanceId); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public int updateSchedulerState(Connection conn, String instanceId, long checkInTime, String recoverer) + throws SQLException { + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(rtp(UPDATE_SCHEDULER_STATE)); + ps.setLong(1, checkInTime); + ps.setString(2, recoverer); + ps.setString(3, instanceId); + + return ps.executeUpdate(); + } finally { + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public List selectSchedulerStateRecords(Connection conn, String instanceId) + throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + try { + List lst = new LinkedList(); + + if (instanceId != null) { + ps = conn.prepareStatement(rtp(SELECT_SCHEDULER_STATE)); + ps.setString(1, instanceId); + } else { + ps = conn.prepareStatement(rtp(SELECT_SCHEDULER_STATES)); + } + rs = ps.executeQuery(); + + while (rs.next()) { + SchedulerStateRecord rec = new SchedulerStateRecord(); + + rec.setSchedulerInstanceId(rs.getString(COL_INSTANCE_NAME)); + rec.setCheckinTimestamp(rs.getLong(COL_LAST_CHECKIN_TIME)); + rec.setCheckinInterval(rs.getLong(COL_CHECKIN_INTERVAL)); + rec.setRecoverer(rs.getString(COL_RECOVERER)); + + lst.add(rec); + } + + return lst; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + + } + + //--------------------------------------------------------------------------- + // protected methods that can be overridden by subclasses + //--------------------------------------------------------------------------- + + /** + *

+ * Replace the table prefix in a query by replacing any occurrences of + * "{0}" with the table prefix. + *

+ * + * @param query + * the unsubstitued query + * @return the query, with proper table prefix substituted + */ + protected final String rtp(String query) { + return Util.rtp(query, tablePrefix); + } + + /** + *

+ * Create a serialized java.util.ByteArrayOutputStream + * version of an Object. + *

+ * + * @param obj + * the object to serialize + * @return the serialized ByteArrayOutputStream + * @throws IOException + * if serialization causes an error + */ + protected ByteArrayOutputStream serializeObject(Object obj) + throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + if (null != obj) { + ObjectOutputStream out = new ObjectOutputStream(baos); + out.writeObject(obj); + out.flush(); + } + return baos; + } + + /** + *

+ * Remove the transient data from and then create a serialized java.util.ByteArrayOutputStream + * version of a {@link org.quartz.JobDataMap}. + *

+ * + * @param obj + * the object to serialize + * @return the serialized ByteArrayOutputStream + * @throws IOException + * if serialization causes an error + */ + protected ByteArrayOutputStream serializeJobData(JobDataMap data) + throws IOException { + if (canUseProperties()) return serializeProperties(data); + + if (null != data) { + data.removeTransientData(); + return serializeObject(data); + } else { + return serializeObject(null); + } + } + + /** + * serialize the java.util.Properties + */ + private ByteArrayOutputStream serializeProperties(JobDataMap data) + throws IOException { + ByteArrayOutputStream ba = new ByteArrayOutputStream(); + if (null != data) { + Properties properties = convertToProperty(data.getWrappedMap()); + properties.store(ba, ""); + } + + return ba; + } + + /** + * convert the JobDataMap into a list of properties + */ + protected Map convertFromProperty(Properties properties) throws IOException { + Map data = new HashMap(); + Set keys = properties.keySet(); + Iterator it = keys.iterator(); + while (it.hasNext()) { + Object key = it.next(); + Object val = properties.get(key); + data.put(key, val); + } + + return data; + } + + /** + * convert the JobDataMap into a list of properties + */ + protected Properties convertToProperty(Map data) throws IOException { + Properties properties = new Properties(); + Set keys = data.keySet(); + Iterator it = keys.iterator(); + while (it.hasNext()) { + Object key = it.next(); + Object val = data.get(key); + if(!(key instanceof String)) + throw new IOException("JobDataMap keys/values must be Strings " + + "when the 'useProperties' property is set. " + + " offending Key: " + key); + if(!(val instanceof String)) + throw new IOException("JobDataMap values must be Strings " + + "when the 'useProperties' property is set. " + + " Key of offending value: " + key); + if (val == null) val = ""; + properties.put(key, val); + } + return properties; + } + + /** + *

+ * This method should be overridden by any delegate subclasses that need + * special handling for BLOBs. The default implementation uses standard + * JDBC java.sql.Blob operations. + *

+ * + * @param rs + * the result set, already queued to the correct row + * @param colName + * the column name for the BLOB + * @return the deserialized Object from the ResultSet BLOB + * @throws ClassNotFoundException + * if a class found during deserialization cannot be found + * @throws IOException + * if deserialization causes an error + */ + protected Object getObjectFromBlob(ResultSet rs, String colName) + throws ClassNotFoundException, IOException, SQLException { + Object obj = null; + + Blob blobLocator = rs.getBlob(colName); + if (blobLocator != null) { + InputStream binaryInput = blobLocator.getBinaryStream(); + + if (null != binaryInput) { + ObjectInputStream in = new ObjectInputStream(binaryInput); + obj = in.readObject(); + in.close(); + } + } + return obj; + } + + public Key[] selectVolatileTriggers(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_VOLATILE_TRIGGERS)); + ps.setBoolean(1, true); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + String triggerName = rs.getString(COL_TRIGGER_NAME); + String groupName = rs.getString(COL_TRIGGER_GROUP); + list.add(new Key(triggerName, groupName)); + } + Object[] oArr = list.toArray(); + Key[] kArr = new Key[oArr.length]; + System.arraycopy(oArr, 0, kArr, 0, oArr.length); + return kArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + public Key[] selectVolatileJobs(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = conn.prepareStatement(rtp(SELECT_VOLATILE_JOBS)); + ps.setBoolean(1, true); + rs = ps.executeQuery(); + + ArrayList list = new ArrayList(); + while (rs.next()) { + String triggerName = rs.getString(COL_JOB_NAME); + String groupName = rs.getString(COL_JOB_GROUP); + list.add(new Key(triggerName, groupName)); + } + Object[] oArr = list.toArray(); + Key[] kArr = new Key[oArr.length]; + System.arraycopy(oArr, 0, kArr, 0, oArr.length); + return kArr; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } + + /** + *

+ * This method should be overridden by any delegate subclasses that need + * special handling for BLOBs for job details. The default implementation + * uses standard JDBC java.sql.Blob operations. + *

+ * + * @param rs + * the result set, already queued to the correct row + * @param colName + * the column name for the BLOB + * @return the deserialized Object from the ResultSet BLOB + * @throws ClassNotFoundException + * if a class found during deserialization cannot be found + * @throws IOException + * if deserialization causes an error + */ + protected Object getJobDetailFromBlob(ResultSet rs, String colName) + throws ClassNotFoundException, IOException, SQLException { + if (canUseProperties()) { + Blob blobLocator = rs.getBlob(colName); + if (blobLocator != null) { + InputStream binaryInput = blobLocator.getBinaryStream(); + return binaryInput; + } else { + return null; + } + } + + return getObjectFromBlob(rs, colName); + } + + /** + * @see org.quartz.impl.jdbcjobstore.DriverDelegate#selectPausedTriggerGroups(java.sql.Connection) + */ + public Set selectPausedTriggerGroups(Connection conn) throws SQLException { + PreparedStatement ps = null; + ResultSet rs = null; + + HashSet set = new HashSet(); + try { + ps = conn.prepareStatement(rtp(SELECT_PAUSED_TRIGGER_GROUPS)); + rs = ps.executeQuery(); + + while (rs.next()) { + String groupName = rs.getString(COL_TRIGGER_GROUP); + set.add(groupName); + } + return set; + } finally { + if (null != rs) { + try { + rs.close(); + } catch (SQLException ignore) { + } + } + if (null != ps) { + try { + ps.close(); + } catch (SQLException ignore) { + } + } + } + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/StdRowLockSemaphore.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/StdRowLockSemaphore.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/StdRowLockSemaphore.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,219 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashSet; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * An interface for providing thread/resource locking in order to protect + * resources from being altered by multiple threads at the same time. + * + * @author jhouse + */ +public class StdRowLockSemaphore implements Semaphore, Constants, + StdJDBCConstants { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static final String SELECT_FOR_LOCK = "SELECT * FROM " + + TABLE_PREFIX_SUBST + TABLE_LOCKS + " WHERE " + COL_LOCK_NAME + + " = ? FOR UPDATE"; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + ThreadLocal lockOwners = new ThreadLocal(); + + // java.util.HashMap threadLocksOb = new java.util.HashMap(); + private String selectWithLockSQL = SELECT_FOR_LOCK; + + private String tablePrefix; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public StdRowLockSemaphore(String tablePrefix, String selectWithLockSQL) { + this.tablePrefix = tablePrefix; + + if (selectWithLockSQL != null && selectWithLockSQL.trim().length() != 0) + this.selectWithLockSQL = selectWithLockSQL; + + this.selectWithLockSQL = Util.rtp(this.selectWithLockSQL, tablePrefix); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + Log getLog() { + return LogFactory.getLog(getClass()); + //return LogFactory.getLog("LOCK:"+Thread.currentThread().getName()); + } + + private HashSet getThreadLocks() { + HashSet threadLocks = (HashSet) lockOwners.get(); + if (threadLocks == null) { + threadLocks = new HashSet(); + lockOwners.set(threadLocks); + } + return threadLocks; + } + + /** + * Grants a lock on the identified resource to the calling thread (blocking + * until it is available). + * + * @return true if the lock was obtained. + */ + public boolean obtainLock(Connection conn, String lockName) + throws LockException { + + lockName = lockName.intern(); + + Log log = getLog(); + + if(log.isDebugEnabled()) + log.debug( + "Lock '" + lockName + "' is desired by: " + + Thread.currentThread().getName()); + if (!isLockOwner(conn, lockName)) { + + PreparedStatement ps = null; + ResultSet rs = null; + try { + ps = conn.prepareStatement(selectWithLockSQL); + ps.setString(1, lockName); + + + if(log.isDebugEnabled()) + log.debug( + "Lock '" + lockName + "' is being obtained: " + + Thread.currentThread().getName()); + rs = ps.executeQuery(); + if (!rs.next()) + throw new SQLException(Util.rtp( + "No row exists in table " + TABLE_PREFIX_SUBST + + TABLE_LOCKS + " for lock named: " + + lockName, tablePrefix)); + } catch (SQLException sqle) { + //Exception src = + // (Exception)getThreadLocksObtainer().get(lockName); + //if(src != null) + // src.printStackTrace(); + //else + // System.err.println("--- ***************** NO OBTAINER!"); + + if(log.isDebugEnabled()) + log.debug( + "Lock '" + lockName + "' was not obtained by: " + + Thread.currentThread().getName()); + throw new LockException("Failure obtaining db row lock: " + + sqle.getMessage(), sqle); + } finally { + if (rs != null) try { + rs.close(); + } catch (Exception ignore) { + } + if (ps != null) try { + ps.close(); + } catch (Exception ignore) { + } + } + if(log.isDebugEnabled()) + log.debug( + "Lock '" + lockName + "' given to: " + + Thread.currentThread().getName()); + getThreadLocks().add(lockName); + //getThreadLocksObtainer().put(lockName, new + // Exception("Obtainer...")); + } else + if(log.isDebugEnabled()) + log.debug( + "Lock '" + lockName + "' Is already owned by: " + + Thread.currentThread().getName()); + + return true; + } + + /** + * Release the lock on the identified resource if it is held by the calling + * thread. + */ + public void releaseLock(Connection conn, String lockName) { + + lockName = lockName.intern(); + + if (isLockOwner(conn, lockName)) { + if(getLog().isDebugEnabled()) + getLog().debug( + "Lock '" + lockName + "' returned by: " + + Thread.currentThread().getName()); + getThreadLocks().remove(lockName); + //getThreadLocksObtainer().remove(lockName); + } else + if(getLog().isDebugEnabled()) + getLog().warn( + "Lock '" + lockName + "' attempt to retun by: " + + Thread.currentThread().getName() + + " -- but not owner!", + new Exception("stack-trace of wrongful returner")); + + } + + /** + * Determine whether the calling thread owns a lock on the identified + * resource. + */ + public boolean isLockOwner(Connection conn, String lockName) { + + lockName = lockName.intern(); + + return getThreadLocks().contains(lockName); + } + +} Index: 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/Util.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/Util.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/impl/jdbcjobstore/Util.java 17 Aug 2012 15:10:18 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.impl.jdbcjobstore; + +import java.text.MessageFormat; + +/** + *

+ * This class contains utility functions for use in all delegate classes. + *

+ * + * @author Jeffrey Wescott + */ +public final class Util { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Replace the table prefix in a query by replacing any occurrences of + * "{0}" with the table prefix. + *

+ * + * @param query + * the unsubstitued query + * @param query + * the table prefix + * @return the query, with proper table prefix substituted + */ + public static final String rtp(String query, String tablePrefix) { + return MessageFormat.format(query, new Object[]{tablePrefix}); + } + + /** + *

+ * Obtain a unique key for a given job. + *

+ * + * @param jobName + * the job name + * @param groupName + * the group containing the job + * @return a unique String key + */ + static final String getJobNameKey(String jobName, String groupName) { + return (groupName + "_$x$x$_" + jobName).intern(); + } + + /** + *

+ * Obtain a unique key for a given trigger. + *

+ * + * @param triggerName + * the trigger name + * @param groupName + * the group containing the trigger + * @return a unique String key + */ + static final String getTriggerNameKey(String triggerName, String groupName) { + return (groupName + "_$x$x$_" + triggerName).intern(); + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/jobs/FileScanJob.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/jobs/FileScanJob.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/jobs/FileScanJob.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,118 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.jobs; + +import java.io.File; + +import org.quartz.JobDataMap; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.quartz.SchedulerContext; +import org.quartz.SchedulerException; +import org.quartz.StatefulJob; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Inspects a file and compares whether it's "last modified date" has changed + * since the last time it was inspected. If the file has been updated, the + * job invokes a "call-back" method on an identified + * FileScanListener that can be found in the + * SchedulerContext. + * + * @author jhouse + * @see org.quartz.jobs.FileScanListener + */ +public class FileScanJob implements StatefulJob { + + public static String FILE_NAME = "FILE_NAME"; + public static String FILE_SCAN_LISTENER_NAME = "FILE_SCAN_LISTENER_NAME"; + private static String LAST_MODIFIED_TIME = "LAST_MODIFIED_TIME"; + + public FileScanJob() { + } + + /** + * @see org.quartz.Job#execute(org.quartz.JobExecutionContext) + */ + public void execute(JobExecutionContext context) throws JobExecutionException { + + Log log = LogFactory.getLog(getClass()); + + JobDataMap data = context.getJobDetail().getJobDataMap(); + SchedulerContext schedCtxt = null; + try { + schedCtxt = context.getScheduler().getContext(); + } catch (SchedulerException e) { + throw new JobExecutionException("Error obtaining scheduler context.", e, false); + } + + String fileName = data.getString(FILE_NAME); + String listenerName = data.getString(FILE_SCAN_LISTENER_NAME); + + if(fileName == null) + throw new JobExecutionException("Required parameter '" + + FILE_NAME + "' not found in JobDataMap"); + if(listenerName == null) + throw new JobExecutionException("Required parameter '" + + FILE_SCAN_LISTENER_NAME + "' not found in JobDataMap"); + + FileScanListener listener = (FileScanListener)schedCtxt.get(listenerName); + + if(listener == null) + throw new JobExecutionException("FileScanListener named '" + + listenerName + "' not found in SchedulerContext"); + + long lastDate = -1; + if(data.containsKey(LAST_MODIFIED_TIME)) + lastDate = data.getLong(LAST_MODIFIED_TIME); + + long newDate = getLastModifiedDate(fileName); + + if(newDate < 0) { + log.warn("File '"+fileName+"' does not exist."); + return; + } + + if(lastDate > 0 && (newDate != lastDate)) { + // notify call back... + log.info("File '"+fileName+"' updated, notifying listener."); + listener.fileUpdated(fileName); + } + else + log.debug("File '"+fileName+"' unchanged."); + + data.put(LAST_MODIFIED_TIME, newDate); + } + + protected long getLastModifiedDate(String fileName) { + + File file = new File(fileName); + + if(!file.exists()) { + return -1; + } + else { + return file.lastModified(); + } + } +} Index: 3rdParty_sources/quartz/org/quartz/jobs/FileScanListener.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/jobs/FileScanListener.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/jobs/FileScanListener.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.jobs; + +/** + * Interface for objects wishing to receive a 'call-back' from a + * FileScanJob. + * + * @author jhouse + * @see org.quartz.jobs.FileScanJob + */ +public interface FileScanListener { + + public void fileUpdated(String fileName); +} Index: 3rdParty_sources/quartz/org/quartz/jobs/NativeJob.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/jobs/NativeJob.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/jobs/NativeJob.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,263 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ + +package org.quartz.jobs; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.Job; +import org.quartz.JobDataMap; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; + +/* + *

Built in job for executing native executables in a separate process.

+ * + * + * @see #PROP_COMMAND + * @see #PROP_PARAMETERS + * @see #PROP_WAIT_FOR_PROCESS + * @see #PROP_CONSUME_STREAMS + * + * @author Matthew Payne + * @author James House + * @author Steinar Overbeck Cook + * @date Sep 17, 2003 @Time: 11:27:13 AM + */ +public class NativeJob implements Job { + + /* + *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Required parameter that specifies the name of the command (executable) + * to be ran. + */ + public static final String PROP_COMMAND = "command"; + + /** + * Optional parameter that specifies the parameters to be passed to the + * executed command. + */ + public static final String PROP_PARAMETERS = "parameters"; + + + /** + * Optional parameter (value should be 'true' or 'false') that specifies + * whether the job should wait for the execution of the native process to + * complete before it completes. + * + *

Defaults to true.

+ */ + public static final String PROP_WAIT_FOR_PROCESS = "waitForProcess"; + + /** + * Optional parameter (value should be 'true' or 'false') that specifies + * whether the spawned process's stdout and stderr streams should be + * consumed. If the process creates output, it is possible that it might + * 'hang' if the streams are not consumed. + * + *

Defaults to false.

+ */ + public static final String PROP_CONSUME_STREAMS = "consumeStreams"; + + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public void execute(JobExecutionContext context) + throws JobExecutionException { + + JobDataMap data = context.getJobDetail().getJobDataMap(); + + String command = data.getString(PROP_COMMAND); + + String parameters = data.getString(PROP_PARAMETERS); + + if (parameters == null) { + parameters = ""; + } + + boolean wait = true; + if(data.containsKey(PROP_WAIT_FOR_PROCESS)) { + wait = data.getBooleanValue(PROP_WAIT_FOR_PROCESS); + } + boolean consumeStreams = false; + if(data.containsKey(PROP_CONSUME_STREAMS)) { + consumeStreams = data.getBooleanValue(PROP_CONSUME_STREAMS); + } + + this.runNativeCommand(command, parameters, wait, consumeStreams); + } + + private static Log getLog() + { + return LogFactory.getLog(NativeJob.class); + } + + private void runNativeCommand(String command, String parameters, boolean wait, boolean consumeStreams) throws JobExecutionException { + + String[] cmd = null; + String[] args = new String[2]; + args[0] = command; + args[1] = parameters; + + try { + //with this variable will be done the swithcing + String osName = System.getProperty("os.name"); + + //only will work with Windows NT + if (osName.equals("Windows NT")) { + if (cmd == null) cmd = new String[args.length + 2]; + cmd[0] = "cmd.exe"; + cmd[1] = "/C"; + for (int i = 0; i < args.length; i++) + cmd[i + 2] = args[i]; + } + //only will work with Windows 95 + else if (osName.equals("Windows 95")) { + if (cmd == null) cmd = new String[args.length + 2]; + cmd[0] = "command.com"; + cmd[1] = "/C"; + for (int i = 0; i < args.length; i++) + cmd[i + 2] = args[i]; + } + //only will work with Windows 2003 + else if (osName.equals("Windows 2003")) { + if (cmd == null) cmd = new String[args.length + 2]; + cmd[0] = "cmd.exe"; + cmd[1] = "/C"; + + for (int i = 0; i < args.length; i++) + cmd[i + 2] = args[i]; + } + //only will work with Windows 2000 + else if (osName.equals("Windows 2000")) { + if (cmd == null) cmd = new String[args.length + 2]; + cmd[0] = "cmd.exe"; + cmd[1] = "/C"; + + for (int i = 0; i < args.length; i++) + cmd[i + 2] = args[i]; + } + //only will work with Windows XP + else if (osName.equals("Windows XP")) { + if (cmd == null) cmd = new String[args.length + 2]; + cmd[0] = "cmd.exe"; + cmd[1] = "/C"; + + for (int i = 0; i < args.length; i++) + cmd[i + 2] = args[i]; + } + //only will work with Linux + else if (osName.equals("Linux")) { + if (cmd == null) cmd = new String[args.length]; + cmd = args; + } + //will work with the rest + else { + if (cmd == null) cmd = new String[args.length]; + cmd = args; + } + + Runtime rt = Runtime.getRuntime(); + // Executes the command + getLog().info("About to run" + cmd[0] + cmd[1]); + Process proc = rt.exec(cmd); + // Consumes the stdout from the process + StreamConsumer stdoutConsumer = new StreamConsumer(proc.getInputStream(), "stdout"); + + // Consumes the stderr from the process + if(consumeStreams) { + StreamConsumer stderrConsumer = new StreamConsumer(proc.getErrorStream(), "stderr"); + stdoutConsumer.start(); + stderrConsumer.start(); + } + + if(wait) + proc.waitFor(); + // any error message? + + } catch (Exception x) { + throw new JobExecutionException("Error launching native command: ", x, false); + } + } + + /** + * Consumes data from the given input stream until EOF and prints the data to stdout + * + * @author cooste + * @author jhouse + */ + class StreamConsumer extends Thread { + InputStream is; + String type; + + /** + * + */ + public StreamConsumer(InputStream inputStream, String type) { + this.is = inputStream; + this.type = type; + } + + /** + * Runs this object as a separate thread, printing the contents of the InputStream + * supplied during instantiation, to either stdout or stderr + */ + public void run() { + BufferedReader br = null; + try { + br = new BufferedReader(new InputStreamReader(is)); + String line = null; + + while ((line = br.readLine()) != null) { + if(type.equalsIgnoreCase("stderr")) + getLog().warn(type + ">" + line); + else + getLog().info(type + ">" + line); + } + } catch (IOException ioe) { + getLog().error("Error consuming " + type + " stream of spawned process.", ioe); + } + finally { + if(br != null) + try { br.close(); } catch(Exception ignore) {} + } + } + } + +} Index: 3rdParty_sources/quartz/org/quartz/jobs/NoOpJob.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/jobs/NoOpJob.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/jobs/NoOpJob.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.jobs; + +import org.quartz.Job; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; + +/** + *

+ * An implementation of Job, that does absolutely nothing - useful for system + * which only wish to use {@link org.quartz.TriggerListener}s + * and {@link org.quartz.JobListener}s, rather than writing + * Jobs that perform work. + *

+ * + * @author James House + */ +public class NoOpJob implements Job { + + + /* + *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public NoOpJob() { + } + + /* + *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Do nothing. + *

+ */ + public void execute(JobExecutionContext context) + throws JobExecutionException { + } + +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/jobs/ee/ejb/EJBInvokerJob.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/jobs/ee/ejb/EJBInvokerJob.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/jobs/ee/ejb/EJBInvokerJob.java 17 Aug 2012 15:10:22 -0000 1.1 @@ -0,0 +1,274 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.jobs.ee.ejb; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.rmi.RemoteException; +import java.util.Hashtable; + +import javax.ejb.EJBHome; +import javax.ejb.EJBMetaData; +import javax.ejb.EJBObject; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.rmi.PortableRemoteObject; + +import org.quartz.Job; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; + +/** + *

+ * A Job that invokes a method on an EJB. + *

+ * + *

+ * Expects the properties corresponding to the following keys to be in the + * JobDataMap when it executes: + *

    + *
  • EJB_JNDI_NAME_KEY- the JNDI name (location) of the + * EJB's home interface.
  • + *
  • EJB_METHOD_KEY- the name of the method to invoke on the + * EJB.
  • + *
  • EJB_ARGS_KEY- an Object[] of the args to pass to the + * method (optional, if left out, there are no arguments).
  • + *
  • EJB_ARG_TYPES_KEY- an Class[] of the types of the args to + * pass to the method (optional, if left out, the types will be derived by + * calling getClass() on each of the arguments).
  • + *
+ *
+ * The following keys can also be used at need: + *
    + *
  • INITIAL_CONTEXT_FACTORY - the context factory used to + * build the context.
  • + *
  • PROVIDER_URL - the name of the environment property + * for specifying configuration information for the service provider to use. + *
  • + *
+ *

+ * + * @author Andrew Collins + * @author James House + * @author Joel Shellman + * @author Chris Bonham + */ +public class EJBInvokerJob implements Job { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static final String EJB_JNDI_NAME_KEY = "ejb"; + + public static final String EJB_METHOD_KEY = "method"; + + public static final String EJB_ARG_TYPES_KEY = "argTypes"; + + public static final String EJB_ARGS_KEY = "args"; + + public static final String INITIAL_CONTEXT_FACTORY = "java.naming.factory.initial"; + + public static final String PROVIDER_URL = "java.naming.provider.url"; + + public static final String PRINCIPAL = "java.naming.security.principal"; + + public static final String CREDENTIALS = "java.naming.security.credentials"; + + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public EJBInvokerJob() { + // nothing + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public void execute(JobExecutionContext context) + throws JobExecutionException { + JobDetail detail = context.getJobDetail(); + + JobDataMap dataMap = detail.getJobDataMap(); + + String ejb = dataMap.getString(EJB_JNDI_NAME_KEY); + String method = dataMap.getString(EJB_METHOD_KEY); + Object[] arguments = (Object[]) dataMap.get(EJB_ARGS_KEY); + if (arguments == null) { + arguments = new Object[0]; + } + + if (ejb == null) { + // must specify remote home + throw new JobExecutionException(); } + + InitialContext jndiContext = null; + + // get initial context + try { + jndiContext = getInitialContext(dataMap); + } catch (NamingException ne) { + throw new JobExecutionException(ne); + } + + Object value = null; + + // locate home interface + try { + value = jndiContext.lookup(ejb); + } catch (NamingException ne) { + throw new JobExecutionException(ne); + } finally { + if (jndiContext != null) { + try { + jndiContext.close(); + } catch (NamingException e) { + // Ignore any errors closing the initial context + } + } + } + + // get home interface + EJBHome ejbHome = (EJBHome) PortableRemoteObject.narrow(value, + EJBHome.class); + + // get meta data + EJBMetaData metaData = null; + + try { + metaData = ejbHome.getEJBMetaData(); + } catch (RemoteException re) { + throw new JobExecutionException(re); + } + + // get home interface class + Class homeClass = metaData.getHomeInterfaceClass(); + + // get remote interface class + Class remoteClass = metaData.getRemoteInterfaceClass(); + + // get home interface + ejbHome = (EJBHome) PortableRemoteObject.narrow(ejbHome, homeClass); + + Method methodCreate = null; + + try { + // create method 'create()' on home interface + methodCreate = homeClass.getDeclaredMethod("create", ((Class[])null)); + } catch (NoSuchMethodException nsme) { + throw new JobExecutionException(nsme); + } + + // create remote object + EJBObject remoteObj = null; + + try { + // invoke 'create()' method on home interface + remoteObj = (EJBObject) methodCreate.invoke(ejbHome, ((Object[])null)); + } catch (IllegalAccessException iae) { + throw new JobExecutionException(iae); + } catch (InvocationTargetException ite) { + throw new JobExecutionException(ite); + } + + // execute user-specified method on remote object + Method methodExecute = null; + + try { + // create method signature + + Class[] argTypes = (Class[]) dataMap.get(EJB_ARG_TYPES_KEY); + if (argTypes == null) { + argTypes = new Class[arguments.length]; + for (int i = 0; i < arguments.length; i++) { + argTypes[i] = arguments[i].getClass(); + } + } + + // get method on remote object + methodExecute = remoteClass.getMethod(method, argTypes); + } catch (NoSuchMethodException nsme) { + throw new JobExecutionException(nsme); + } + + try { + // invoke user-specified method on remote object + methodExecute.invoke(remoteObj, arguments); + } catch (IllegalAccessException iae) { + throw new JobExecutionException(iae); + } catch (InvocationTargetException ite) { + throw new JobExecutionException(ite); + } + } + + private InitialContext getInitialContext(JobDataMap jobDataMap) + throws NamingException { + Hashtable params = new Hashtable(2); + + String initialContextFactory = + jobDataMap.getString(INITIAL_CONTEXT_FACTORY); + if (initialContextFactory != null) { + params.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); + } + + String providerUrl = jobDataMap.getString(PROVIDER_URL); + if (providerUrl != null) { + params.put(Context.PROVIDER_URL, providerUrl); + } + + String principal = jobDataMap.getString(PRINCIPAL); + if ( principal != null ) { + params.put( Context.SECURITY_PRINCIPAL, principal ); + } + + String credentials = jobDataMap.getString(CREDENTIALS); + if ( credentials != null ) { + params.put( Context.SECURITY_CREDENTIALS, credentials ); + } + + if (params.size() == 0) + { + return new InitialContext(); + } + else + { + return new InitialContext(params); + } + } +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/jobs/ee/jmx/JMXInvokerJob.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/jobs/ee/jmx/JMXInvokerJob.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/jobs/ee/jmx/JMXInvokerJob.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,181 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.jobs.ee.jmx; + + +import java.util.LinkedList; +import java.util.StringTokenizer; + +import javax.management.MBeanServer; +import javax.management.MBeanServerFactory; +import javax.management.ObjectName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.Job; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; + + +/** + * Generic JMX invoker Job. It supports any number or type of parameters + * to the JMX bean.

+ * + * The required parameters are as follows (case doesn't matter):

+ *

+ *
JMX_OBJECTNAME + *
This is the fully qualifed name of the object (ie in JBoss to lookup + * the log4j jmx bean you would specify "jboss.system:type=Log4jService,service=Logging" + *
JMX_METHOD + *
This is the method to invoke on the specified JMX Bean. (ie in JBoss to + * change the log level you would specify "setLoggerLevel" + *
JMX_PARAMDEFS + *
This is a definition of the parameters to be passed to the specified method + * and their corresponding java types. Each parameter definition is comma seperated + * and has the following parts: :. Type is the java type for the parameter. + * The following types are supported:

+ * i - is for int

+ * l - is for long

+ * f - is for float

+ * d - is for double

+ * s - is for String

+ * b - is for boolean

+ * For ilfdb use lower for native type and upper for object wrapper. The name portion + * of the definition is the name of the parameter holding the string value. (ie + * s:fname,s:lname would require 2 parameters of the name fname and lname and + * would be passed in that order to the method. + * + * @author James Nelson (jmn@provident-solutions.com) -- Provident Solutions LLC + * + */ +public class JMXInvokerJob implements Job { + + public void execute(JobExecutionContext context) throws JobExecutionException { + try { + Object[] params=null; + String[] types=null; + String objName = null; + String objMethod = null; + String[] keys = context.getJobDetail().getJobDataMap().getKeys(); + for (int i = 0; i < keys.length; i++) { + String value = context.getJobDetail().getJobDataMap().getString(keys[i]); + if ("JMX_OBJECTNAME".equalsIgnoreCase(keys[i])) { + objName = value; + } else if ("JMX_METHOD".equalsIgnoreCase(keys[i])) { + objMethod = value; + } else if("JMX_PARAMDEFS".equalsIgnoreCase(keys[i])) { + String[] paramdefs=split(value, ","); + params=new Object[paramdefs.length]; + types=new String[paramdefs.length]; + for(int k=0;k + * A Job which sends an e-mail with the configured content to the configured + * recipient. + *

+ * + * @author James House + */ +public class SendMailJob implements Job { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * The host name of the smtp server. REQUIRED. + */ + public static final String PROP_SMTP_HOST = "smtp_host"; + + /** + * The e-mail address to send the mail to. REQUIRED. + */ + public static final String PROP_RECIPIENT = "recipient"; + + /** + * The e-mail address to cc the mail to. Optional. + */ + public static final String PROP_CC_RECIPIENT = "cc_recipient"; + + /** + * The e-mail address to claim the mail is from. REQUIRED. + */ + public static final String PROP_SENDER = "sender"; + + /** + * The e-mail address the message should say to reply to. Optional. + */ + public static final String PROP_REPLY_TO = "reply_to"; + + /** + * The subject to place on the e-mail. REQUIRED. + */ + public static final String PROP_SUBJECT = "subject"; + + /** + * The e-mail message body. REQUIRED. + */ + public static final String PROP_MESSAGE = "message"; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * @see org.quartz.Job#execute(org.quartz.JobExecutionContext) + */ + public void execute(JobExecutionContext context) + throws JobExecutionException { + + JobDataMap data = context.getJobDetail().getJobDataMap(); + + String smtpHost = data.getString(PROP_SMTP_HOST); + String to = data.getString(PROP_RECIPIENT); + String cc = data.getString(PROP_CC_RECIPIENT); + String from = data.getString(PROP_SENDER); + String replyTo = data.getString(PROP_REPLY_TO); + String subject = data.getString(PROP_SUBJECT); + String message = data.getString(PROP_MESSAGE); + + if (smtpHost == null || smtpHost.trim().length() == 0) + throw new IllegalArgumentException( + "PROP_SMTP_HOST not specified."); + if (to == null || to.trim().length() == 0) + throw new IllegalArgumentException( + "PROP_RECIPIENT not specified."); + if (from == null || from.trim().length() == 0) + throw new IllegalArgumentException("PROP_SENDER not specified."); + if (subject == null || subject.trim().length() == 0) + throw new IllegalArgumentException( + "PROP_SUBJECT not specified."); + if (message == null || message.trim().length() == 0) + throw new IllegalArgumentException( + "PROP_MESSAGE not specified."); + + if (cc != null && cc.trim().length() == 0) cc = null; + + if (replyTo != null && replyTo.trim().length() == 0) replyTo = null; + + String mailDesc = "'" + subject + "' to: " + to; + + getLog().info("Sending message " + mailDesc); + + try { + sendMail(smtpHost, to, cc, from, replyTo, subject, message); + } catch (MessagingException e) { + throw new JobExecutionException("Unable to send mail: " + mailDesc, + e, false); + } + + } + + private static Log getLog() { + return LogFactory.getLog(SendMailJob.class); + } + + private void sendMail(String smtpHost, String to, String cc, String from, + String replyTo, String subject, String message) + throws MessagingException { + MimeMessage mimeMessage = prepareMimeMessage(smtpHost, to, cc, from, + replyTo, subject); + mimeMessage.setText(message); + Transport.send(mimeMessage); + } + + private MimeMessage prepareMimeMessage(String smtpHost, String to, + String cc, String from, String replyTo, String subject) + throws MessagingException { + + Properties properties = new Properties(); + properties.put("mail.smtp.host", smtpHost); + Session session = Session.getDefaultInstance(properties, null); + + MimeMessage mimeMessage = new MimeMessage(session); + + Address[] toAddresses = InternetAddress.parse(to); + mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses); + + if (cc != null) { + Address[] ccAddresses = InternetAddress.parse(cc); + mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses); + } + + mimeMessage.setFrom(new InternetAddress(from)); + if (replyTo != null) + mimeMessage + .setReplyTo(new InternetAddress[]{new InternetAddress( + replyTo)}); + mimeMessage.setSubject(subject); + mimeMessage.setSentDate(new Date()); + + return mimeMessage; + } + +} Index: 3rdParty_sources/quartz/org/quartz/plugins/history/LoggingJobHistoryPlugin.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/plugins/history/LoggingJobHistoryPlugin.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/plugins/history/LoggingJobHistoryPlugin.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,539 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.plugins.history; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.Trigger; +import org.quartz.JobListener; +import org.quartz.spi.SchedulerPlugin; + +import java.text.MessageFormat; + +/** + * Logs a history of all job executions (and execution vetos) via the + * Jakarta Commons-Logging framework. + * + *

+ * The logged message is customizable by setting one of the following message + * properties to a String that conforms to the syntax of java.util.MessageFormat. + *

+ * + *

+ * JobToBeFiredMessage - available message data are: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
ElementData TypeDescription
0StringThe Job's Name.
1StringThe Job's Group.
2DateThe current time.
3StringThe Trigger's name.
4StringThe Triggers's group.
5DateThe scheduled fire time.
6DateThe next scheduled fire time.
7IntegerThe re-fire count from the JobExecutionContext.
+ * + * The default message text is "Job {1}.{0} fired (by trigger {4}.{3}) at: + * {2, date, HH:mm:ss MM/dd/yyyy}" + *

+ * + * + *

+ * JobSuccessMessage - available message data are: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
ElementData TypeDescription
0StringThe Job's Name.
1StringThe Job's Group.
2DateThe current time.
3StringThe Trigger's name.
4StringThe Triggers's group.
5DateThe scheduled fire time.
6DateThe next scheduled fire time.
7IntegerThe re-fire count from the JobExecutionContext.
8ObjectThe string value (toString() having been called) of the result (if any) + * that the Job set on the JobExecutionContext, with on it. "NULL" if no + * result was set.
+ * + * The default message text is "Job {1}.{0} execution complete at {2, date, + * HH:mm:ss MM/dd/yyyy} and reports: {8}" + *

+ * + *

+ * JobFailedMessage - available message data are: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
ElementData TypeDescription
0StringThe Job's Name.
1StringThe Job's Group.
2DateThe current time.
3StringThe Trigger's name.
4StringThe Triggers's group.
5DateThe scheduled fire time.
6DateThe next scheduled fire time.
7IntegerThe re-fire count from the JobExecutionContext.
8StringThe message from the thrown JobExecution Exception. + *
+ * + * The default message text is "Job {1}.{0} execution failed at {2, date, + * HH:mm:ss MM/dd/yyyy} and reports: {8}" + *

+ * + * + *

+ * JobWasVetoedMessage - available message data are: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
ElementData TypeDescription
0StringThe Job's Name.
1StringThe Job's Group.
2DateThe current time.
3StringThe Trigger's name.
4StringThe Triggers's group.
5DateThe scheduled fire time.
6DateThe next scheduled fire time.
7IntegerThe re-fire count from the JobExecutionContext.
+ * + * The default message text is "Job {1}.{0} was vetoed. It was to be fired + * (by trigger {4}.{3}) at: {2, date, HH:mm:ss MM/dd/yyyy}" + *

+ * + * + * @author James House + */ +public class LoggingJobHistoryPlugin implements SchedulerPlugin, JobListener { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private String name; + + private String jobToBeFiredMessage = "Job {1}.{0} fired (by trigger {4}.{3}) at: {2, date, HH:mm:ss MM/dd/yyyy}"; + + private String jobSuccessMessage = "Job {1}.{0} execution complete at {2, date, HH:mm:ss MM/dd/yyyy} and reports: {8}"; + + private String jobFailedMessage = "Job {1}.{0} execution failed at {2, date, HH:mm:ss MM/dd/yyyy} and reports: {8}"; + + private String jobWasVetoedMessage = "Job {1}.{0} was vetoed. It was to be fired (by trigger {4}.{3}) at: {2, date, HH:mm:ss MM/dd/yyyy}"; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public LoggingJobHistoryPlugin() { + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected Log getLog() { + return LogFactory.getLog(LoggingJobHistoryPlugin.class); + } + + /** + * Get the message that is logged when a Job successfully completes its + * execution. + * + * @return String + */ + public String getJobSuccessMessage() { + return jobSuccessMessage; + } + + /** + * Get the message that is logged when a Job fails its + * execution. + * + * @return String + */ + public String getJobFailedMessage() { + return jobFailedMessage; + } + + /** + * Get the message that is logged when a Job is about to execute. + * + * @return String + */ + public String getJobToBeFiredMessage() { + return jobToBeFiredMessage; + } + + /** + * Set the message that is logged when a Job successfully completes its + * execution. + * + * @param jobCompleteMessage + * String in java.text.MessageFormat syntax. + */ + public void setJobSuccessMessage(String jobSuccessMessage) { + this.jobSuccessMessage = jobSuccessMessage; + } + + /** + * Set the message that is logged when a Job fails its + * execution. + * + * @param jobCompleteMessage + * String in java.text.MessageFormat syntax. + */ + public void setJobFailedMessage(String jobFailedMessage) { + this.jobFailedMessage = jobFailedMessage; + } + + /** + * Set the message that is logged when a Job is about to execute. + * + * @param jobToBeFiredMessage + * String in java.text.MessageFormat syntax. + */ + public void setJobToBeFiredMessage(String jobToBeFiredMessage) { + this.jobToBeFiredMessage = jobToBeFiredMessage; + } + + /** + * Get the message that is logged when a Job execution is vetoed by a + * trigger listener. + * + * @return String + */ + public String getJobWasVetoedMessage() { + return jobWasVetoedMessage; + } + + /** + * Set the message that is logged when a Job execution is vetoed by a + * trigger listener. + * + * @param jobToBeFiredMessage + * String in java.text.MessageFormat syntax. + */ + public void setJobWasVetoedMessage(String jobWasVetoedMessage) { + this.jobWasVetoedMessage = jobWasVetoedMessage; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * SchedulerPlugin Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Called during creation of the Scheduler in order to give + * the SchedulerPlugin a chance to initialize. + *

+ * + * @throws SchedulerConfigException + * if there is an error initializing. + */ + public void initialize(String name, Scheduler scheduler) + throws SchedulerException { + this.name = name; + scheduler.addGlobalJobListener(this); + } + + public void start() { + // do nothing... + } + + /** + *

+ * Called in order to inform the SchedulerPlugin that it + * should free up all of it's resources because the scheduler is shutting + * down. + *

+ */ + public void shutdown() { + // nothing to do... + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * JobListener Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /* + * Object[] arguments = { new Integer(7), new + * Date(System.currentTimeMillis()), "a disturbance in the Force" }; + * + * String result = MessageFormat.format( "At {1,time} on {1,date}, there + * was {2} on planet {0,number,integer}.", arguments); + */ + + public String getName() { + return name; + } + + /** + * @see org.quartz.JobListener#jobToBeExecuted(JobExecutionContext) + */ + public void jobToBeExecuted(JobExecutionContext context) { + if (!getLog().isInfoEnabled()) { + return; + } + + Trigger trigger = context.getTrigger(); + + Object[] args = {context.getJobDetail().getName(), + context.getJobDetail().getGroup(), new java.util.Date(), + trigger.getName(), trigger.getGroup(), + trigger.getPreviousFireTime(), trigger.getNextFireTime(), + new Integer(context.getRefireCount())}; + + getLog().info(MessageFormat.format(getJobToBeFiredMessage(), args)); + } + + /** + * @see org.quartz.JobListener#jobWasExecuted(JobExecutionContext, JobExecutionException) + */ + public void jobWasExecuted(JobExecutionContext context, + JobExecutionException jobException) { + + Trigger trigger = context.getTrigger(); + + Object[] args = null; + + if (jobException != null) { + if (!getLog().isWarnEnabled()) { + return; + } + + String errMsg = jobException.getMessage(); + args = new Object[]{context.getJobDetail().getName(), + context.getJobDetail().getGroup(), new java.util.Date(), + trigger.getName(), trigger.getGroup(), + trigger.getPreviousFireTime(), trigger.getNextFireTime(), + new Integer(context.getRefireCount()), errMsg}; + + getLog().warn(MessageFormat.format(getJobFailedMessage(), args), jobException); + } + else { + if (!getLog().isInfoEnabled()) { + return; + } + + String result = String.valueOf(context.getResult()); + args = new Object[]{context.getJobDetail().getName(), + context.getJobDetail().getGroup(), new java.util.Date(), + trigger.getName(), trigger.getGroup(), + trigger.getPreviousFireTime(), trigger.getNextFireTime(), + new Integer(context.getRefireCount()), result}; + + getLog().info(MessageFormat.format(getJobSuccessMessage(), args)); + } + } + + /** + * @see org.quartz.JobListener#jobExecutionVetoed(org.quartz.JobExecutionContext) + */ + public void jobExecutionVetoed(JobExecutionContext context) { + + if (!getLog().isInfoEnabled()) { + return; + } + + Trigger trigger = context.getTrigger(); + + Object[] args = {context.getJobDetail().getName(), + context.getJobDetail().getGroup(), new java.util.Date(), + trigger.getName(), trigger.getGroup(), + trigger.getPreviousFireTime(), trigger.getNextFireTime(), + new Integer(context.getRefireCount())}; + + getLog().info(MessageFormat.format(getJobWasVetoedMessage(), args)); + } + +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/plugins/history/LoggingTriggerHistoryPlugin.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/plugins/history/LoggingTriggerHistoryPlugin.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/plugins/history/LoggingTriggerHistoryPlugin.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,427 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.plugins.history; + +import java.text.MessageFormat; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.JobExecutionContext; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.Trigger; +import org.quartz.TriggerListener; +import org.quartz.spi.SchedulerPlugin; + +/** + * Logs a history of all trigger firings via the Jakarta Commons-Logging + * framework. + * + *

+ * The logged message is customizable by setting one of the following message + * properties to a String that conforms to the syntax of java.util.MessageFormat. + *

+ * + *

+ * TriggerFiredMessage - available message data are: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
ElementData TypeDescription
0StringThe Trigger's Name.
1StringThe Trigger's Group.
2DateThe scheduled fire time.
3DateThe next scheduled fire time.
4DateThe actual fire time.
5StringThe Job's name.
6StringThe Job's group.
7IntegerThe re-fire count from the JobExecutionContext.
+ * + * The default message text is "Trigger {1}.{0} fired job {6}.{5} at: {4, + * date, HH:mm:ss MM/dd/yyyy}" + *

+ * + *

+ * TriggerMisfiredMessage - available message data are: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
ElementData TypeDescription
0StringThe Trigger's Name.
1StringThe Trigger's Group.
2DateThe scheduled fire time.
3DateThe next scheduled fire time.
4DateThe actual fire time. (the time the misfire was detected/handled)
5StringThe Job's name.
6StringThe Job's group.
+ * + * The default message text is "Trigger {1}.{0} misfired job {6}.{5} at: + * {4, date, HH:mm:ss MM/dd/yyyy}. Should have fired at: {3, date, HH:mm:ss + * MM/dd/yyyy}" + *

+ * + *

+ * TriggerCompleteMessage - available message data are: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
ElementData TypeDescription
0StringThe Trigger's Name.
1StringThe Trigger's Group.
2DateThe scheduled fire time.
3DateThe next scheduled fire time.
4DateThe job completion time.
5StringThe Job's name.
6StringThe Job's group.
7IntegerThe re-fire count from the JobExecutionContext.
8IntegerThe trigger's resulting instruction code.
9StringA human-readable translation of the trigger's resulting instruction + * code.
+ * + * The default message text is "Trigger {1}.{0} completed firing job + * {6}.{5} at {4, date, HH:mm:ss MM/dd/yyyy} with resulting trigger instruction + * code: {9}" + *

+ * + * @author James House + */ +public class LoggingTriggerHistoryPlugin implements SchedulerPlugin, + TriggerListener { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private String name; + + private String triggerFiredMessage = "Trigger {1}.{0} fired job {6}.{5} at: {4, date, HH:mm:ss MM/dd/yyyy}"; + + private String triggerMisfiredMessage = "Trigger {1}.{0} misfired job {6}.{5} at: {4, date, HH:mm:ss MM/dd/yyyy}. Should have fired at: {3, date, HH:mm:ss MM/dd/yyyy}"; + + private String triggerCompleteMessage = "Trigger {1}.{0} completed firing job {6}.{5} at {4, date, HH:mm:ss MM/dd/yyyy} with resulting trigger instruction code: {9}"; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public LoggingTriggerHistoryPlugin() { + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected Log getLog() { + return LogFactory.getLog(LoggingTriggerHistoryPlugin.class); + } + + /** + * Get the message that is printed upon the completion of a trigger's + * firing. + * + * @return String + */ + public String getTriggerCompleteMessage() { + return triggerCompleteMessage; + } + + /** + * Get the message that is printed upon a trigger's firing. + * + * @return String + */ + public String getTriggerFiredMessage() { + return triggerFiredMessage; + } + + /** + * Get the message that is printed upon a trigger's mis-firing. + * + * @return String + */ + public String getTriggerMisfiredMessage() { + return triggerMisfiredMessage; + } + + /** + * Set the message that is printed upon the completion of a trigger's + * firing. + * + * @param triggerCompleteMessage + * String in java.text.MessageFormat syntax. + */ + public void setTriggerCompleteMessage(String triggerCompleteMessage) { + this.triggerCompleteMessage = triggerCompleteMessage; + } + + /** + * Set the message that is printed upon a trigger's firing. + * + * @param triggerFiredMessage + * String in java.text.MessageFormat syntax. + */ + public void setTriggerFiredMessage(String triggerFiredMessage) { + this.triggerFiredMessage = triggerFiredMessage; + } + + /** + * Set the message that is printed upon a trigger's firing. + * + * @param triggerMisfiredMessage + * String in java.text.MessageFormat syntax. + */ + public void setTriggerMisfiredMessage(String triggerMisfiredMessage) { + this.triggerMisfiredMessage = triggerMisfiredMessage; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * SchedulerPlugin Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Called during creation of the Scheduler in order to give + * the SchedulerPlugin a chance to initialize. + *

+ * + * @throws SchedulerConfigException + * if there is an error initializing. + */ + public void initialize(String name, Scheduler scheduler) + throws SchedulerException { + this.name = name; + + scheduler.addGlobalTriggerListener(this); + } + + public void start() { + // do nothing... + } + + /** + *

+ * Called in order to inform the SchedulerPlugin that it + * should free up all of it's resources because the scheduler is shutting + * down. + *

+ */ + public void shutdown() { + // nothing to do... + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * TriggerListener Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /* + * Object[] arguments = { new Integer(7), new + * Date(System.currentTimeMillis()), "a disturbance in the Force" }; + * + * String result = MessageFormat.format( "At {1,time} on {1,date}, there + * was {2} on planet {0,number,integer}.", arguments); + */ + + public String getName() { + return name; + } + + public void triggerFired(Trigger trigger, JobExecutionContext context) { + if (!getLog().isInfoEnabled()) { + return; + } + + Object[] args = {trigger.getName(), trigger.getGroup(), + trigger.getPreviousFireTime(), trigger.getNextFireTime(), + new java.util.Date(), context.getJobDetail().getName(), + context.getJobDetail().getGroup(), + new Integer(context.getRefireCount())}; + + getLog().info(MessageFormat.format(getTriggerFiredMessage(), args)); + } + + public void triggerMisfired(Trigger trigger) { + if (!getLog().isInfoEnabled()) { + return; + } + + Object[] args = {trigger.getName(), trigger.getGroup(), + trigger.getPreviousFireTime(), trigger.getNextFireTime(), + new java.util.Date(), trigger.getJobGroup(), + trigger.getJobGroup(),}; + + getLog().info(MessageFormat.format(getTriggerMisfiredMessage(), args)); + } + + public void triggerComplete(Trigger trigger, JobExecutionContext context, + int triggerInstructionCode) { + if (!getLog().isInfoEnabled()) { + return; + } + + String instrCode = "UNKNOWN"; + if (triggerInstructionCode == Trigger.INSTRUCTION_DELETE_TRIGGER) instrCode = "DELETE TRIGGER"; + else if (triggerInstructionCode == Trigger.INSTRUCTION_NOOP) instrCode = "DO NOTHING"; + else if (triggerInstructionCode == Trigger.INSTRUCTION_RE_EXECUTE_JOB) instrCode = "RE-EXECUTE JOB"; + else if (triggerInstructionCode == Trigger.INSTRUCTION_SET_ALL_JOB_TRIGGERS_COMPLETE) instrCode = "SET ALL OF JOB'S TRIGGERS COMPLETE"; + else if (triggerInstructionCode == Trigger.INSTRUCTION_SET_TRIGGER_COMPLETE) + instrCode = "SET THIS TRIGGER COMPLETE"; + + Object[] args = {trigger.getName(), trigger.getGroup(), + trigger.getPreviousFireTime(), trigger.getNextFireTime(), + new java.util.Date(), context.getJobDetail().getName(), + context.getJobDetail().getGroup(), + new Integer(context.getRefireCount()), + new Integer(triggerInstructionCode), instrCode}; + + getLog().info(MessageFormat.format(getTriggerCompleteMessage(), args)); + } + + public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context) { + return false; + } + +} Index: 3rdParty_sources/quartz/org/quartz/plugins/management/ShutdownHookPlugin.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/plugins/management/ShutdownHookPlugin.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/plugins/management/ShutdownHookPlugin.java 17 Aug 2012 15:10:22 -0000 1.1 @@ -0,0 +1,162 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.plugins.management; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.spi.SchedulerPlugin; + +/** + * This plugin catches the event of the JVM terminating (such as upon a CRTL-C) + * and tells the scheuler to shutdown. + * + * @see org.quartz.Scheduler#shutdown(boolean) + * + * @author James House + */ +public class ShutdownHookPlugin implements SchedulerPlugin { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private String name; + + private Scheduler scheduler; + + private boolean cleanShutdown = true; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public ShutdownHookPlugin() { + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Determine whether or not the plug-in is configured to cause a clean + * shutdown of the scheduler. + * + *

+ * The default value is true. + *

+ * + * @see org.quartz.Scheduler#shutdown(boolean) + */ + public boolean isCleanShutdown() { + return cleanShutdown; + } + + /** + * Set whether or not the plug-in is configured to cause a clean shutdown + * of the scheduler. + * + *

+ * The default value is true. + *

+ * + * @see org.quartz.Scheduler#shutdown(boolean) + */ + public void setCleanShutdown(boolean b) { + cleanShutdown = b; + } + + protected static Log getLog() { + return LogFactory.getLog(ShutdownHookPlugin.class); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * SchedulerPlugin Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Called during creation of the Scheduler in order to give + * the SchedulerPlugin a chance to initialize. + *

+ * + * @throws SchedulerConfigException + * if there is an error initializing. + */ + public void initialize(String name, final Scheduler scheduler) + throws SchedulerException { + this.name = name; + this.scheduler = scheduler; + + getLog().info("Registering Quartz shutdown hook."); + + Thread t = new Thread("Quartz Shutdown-Hook " + + scheduler.getSchedulerName()) { + public void run() { + getLog().info("Shutting down Quartz..."); + try { + scheduler.shutdown(isCleanShutdown()); + } catch (SchedulerException e) { + getLog().info( + "Error shutting down Quartz: " + e.getMessage(), e); + } + } + }; + + Runtime.getRuntime().addShutdownHook(t); + } + + public void start() { + // do nothing. + } + + /** + *

+ * Called in order to inform the SchedulerPlugin that it + * should free up all of it's resources because the scheduler is shutting + * down. + *

+ */ + public void shutdown() { + // nothing to do in this case (since the scheduler is already shutting + // down) + } + +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/plugins/xml/JobInitializationPlugin.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/plugins/xml/JobInitializationPlugin.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/plugins/xml/JobInitializationPlugin.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,417 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.plugins.xml; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.net.URLDecoder; +import java.util.Date; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.JobDetail; +import org.quartz.Scheduler; +import org.quartz.SchedulerConfigException; +import org.quartz.SchedulerException; +import org.quartz.SimpleTrigger; +import org.quartz.jobs.FileScanJob; +import org.quartz.jobs.FileScanListener; +import org.quartz.simpl.CascadingClassLoadHelper; +import org.quartz.spi.ClassLoadHelper; +import org.quartz.spi.SchedulerPlugin; +import org.quartz.xml.JobSchedulingDataProcessor; + +/** +* This plugin loads an XML file to add jobs and schedule them with triggers + * as the scheduler is initialized, and can optionally periodically scan the + * file for changes. + * + * @author James House + * @author Pierre Awaragi + */ +public class JobInitializationPlugin implements SchedulerPlugin, FileScanListener { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private String name; + + private Scheduler scheduler; + + private boolean overWriteExistingJobs = false; + + private boolean failOnFileNotFound = true; + + private boolean fileFound = false; + + private String fileName = JobSchedulingDataProcessor.QUARTZ_XML_FILE_NAME; + + private String filePath = null; + + private boolean useContextClassLoader = true; + + private boolean validating = false; + + private boolean validatingSchema = true; + + private long scanInterval = 0; + + boolean initializing = true; + + boolean started = false; + + protected ClassLoadHelper classLoadHelper = null; + + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public JobInitializationPlugin() { + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * The file name (and path) to the XML file that should be read. + * + * @return + */ + public String getFileName() { + return fileName; + } + + /** + * The file name (and path) to the XML file that should be read. + * + * @param fileName + */ + public void setFileName(String fileName) { + this.fileName = fileName; + } + + /** + * Whether or not jobs defined in the XML file should be overwrite existing + * jobs with the same name. + * + * @return + */ + public boolean isOverWriteExistingJobs() { + return overWriteExistingJobs; + } + + /** + * Whether or not jobs defined in the XML file should be overwrite existing + * jobs with the same name. + * + * @param overWriteExistingJobs + */ + public void setOverWriteExistingJobs(boolean overWriteExistingJobs) { + this.overWriteExistingJobs = overWriteExistingJobs; + } + + /** + * The interval (in seconds) at which to scan for changes to the file. + * If the file has been changed, it is re-loaded and parsed. The default + * value for the interval is 0, which disables scanning. + * + * @return Returns the scanInterval. + */ + public long getScanInterval() { + return scanInterval / 1000; + } + + /** + * The interval (in seconds) at which to scan for changes to the file. + * If the file has been changed, it is re-loaded and parsed. The default + * value for the interval is 0, which disables scanning. + * + * @param scanInterval The scanInterval to set. + */ + public void setScanInterval(long scanInterval) { + this.scanInterval = scanInterval * 1000; + } + + /** + * Whether or not initialization of the plugin should fail (throw an + * exception) if the file cannot be found. Default is true. + * + * @return + */ + public boolean isFailOnFileNotFound() { + return failOnFileNotFound; + } + + /** + * Whether or not initialization of the plugin should fail (throw an + * exception) if the file cannot be found. Default is true. + * + * @param overWriteExistingJobs + */ + public void setFailOnFileNotFound(boolean failOnFileNotFound) { + this.failOnFileNotFound = failOnFileNotFound; + } + + /** + * Whether or not the context class loader should be used. Default is true. + * + * @return + */ + public boolean isUseContextClassLoader() { + return useContextClassLoader; + } + + /** + * Whether or not context class loader should be used. Default is true. + * + * @param useContextClassLoader + */ + public void setUseContextClassLoader(boolean useContextClassLoader) { + this.useContextClassLoader = useContextClassLoader; + } + + /** + * Whether or not the XML should be validated. Default is false. + * + * @return + */ + public boolean isValidating() { + return validating; + } + + /** + * Whether or not the XML should be validated. Default is false. + * + * @param validating + */ + public void setValidating(boolean validating) { + this.validating = validating; + } + + /** + * Whether or not the XML schema should be validated. Default is true. + * + * @return + */ + public boolean isValidatingSchema() { + return validatingSchema; + } + + /** + * Whether or not the XML schema should be validated. Default is true. + * + * @param validatingSchema + */ + public void setValidatingSchema(boolean validatingSchema) { + this.validatingSchema = validatingSchema; + } + + protected static Log getLog() { + return LogFactory.getLog(JobInitializationPlugin.class); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * SchedulerPlugin Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Called during creation of the Scheduler in order to give + * the SchedulerPlugin a chance to initialize. + *

+ * + * @throws SchedulerConfigException + * if there is an error initializing. + */ + public void initialize(String name, final Scheduler scheduler) + throws SchedulerException { + + initializing = true; + + classLoadHelper = new CascadingClassLoadHelper(); + classLoadHelper.initialize(); + + try { + this.name = name; + this.scheduler = scheduler; + + getLog().info("Registering Quartz Job Initialization Plug-in."); + + findFile(); + } + finally { + initializing = false; + } + } + + private String getFilePath() throws SchedulerException { + if(this.filePath == null) { + findFile(); + } + return this.filePath; + } + + /** + * + */ + private void findFile() throws SchedulerException { + java.io.InputStream f = null; + String furl = null; + + File file = new File(getFileName()); // files in filesystem + + if (!file.exists()) { + URL url = classLoadHelper.getResource(getFileName()); + if(url != null) { +// we need jdk 1.3 compatibility, so we abandon this code... +// try { +// furl = URLDecoder.decode(url.getPath(), "UTF-8"); +// } catch (UnsupportedEncodingException e) { +// furl = url.getPath(); +// } + furl = URLDecoder.decode(url.getPath()); + file = new File(furl); + try { + f = url.openStream(); + } catch (IOException ignor) { + // Swallow the exception + } + } + } + else { + try { + f = new java.io.FileInputStream(file); + }catch (FileNotFoundException e) { + // ignore + } + } + + if (f == null && isFailOnFileNotFound()) { + throw new SchedulerException("File named '" + getFileName() + + "' does not exist."); + } else if (f == null) { + getLog().warn("File named '" + getFileName() + "' does not exist."); + } else { + fileFound = true; + try { + if(furl != null) + this.filePath = furl; + else + this.filePath = file.getAbsolutePath(); + f.close(); + } catch (IOException ioe) { + getLog().warn("Error closing jobs file " + getFileName(), ioe); + } + } + } + + public void start() { + + if(scanInterval > 0) { + try{ + SimpleTrigger trig = new SimpleTrigger( + "JobInitializationPlugin_"+name, + "JobInitializationPlugin", + new Date(), null, + SimpleTrigger.REPEAT_INDEFINITELY, scanInterval); + trig.setVolatility(true); + JobDetail job = new JobDetail( + "JobInitializationPlugin_"+name, + "JobInitializationPlugin", + FileScanJob.class); + job.setVolatility(true); + job.getJobDataMap().put(FileScanJob.FILE_NAME, getFilePath()); + job.getJobDataMap().put(FileScanJob.FILE_SCAN_LISTENER_NAME, "JobInitializationPlugin_"+name); + + scheduler.getContext().put("JobInitializationPlugin_"+name, this); + scheduler.scheduleJob(job, trig); + } + catch(SchedulerException se) { + getLog().error("Error starting background-task for watching jobs file.", se); + } + } + + try { + processFile(); + } + finally { + started = true; + } + } + + /** + *

+ * Called in order to inform the SchedulerPlugin that it + * should free up all of it's resources because the scheduler is shutting + * down. + *

+ */ + public void shutdown() { + // nothing to do + } + + + public void processFile() { + if (!fileFound) return; + + JobSchedulingDataProcessor processor = + new JobSchedulingDataProcessor(isUseContextClassLoader(), isValidating(), isValidatingSchema()); + + try { + processor.processFileAndScheduleJobs(fileName, scheduler, isOverWriteExistingJobs()); + } catch (Exception e) { + getLog().error("Error scheduling jobs: " + e.getMessage(), e); + } + } + + /** + * @see org.quartz.jobs.FileScanListener#fileUpdated(java.lang.String) + */ + public void fileUpdated(String fileName) { + if(started) + processFile(); + } + +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/plugins/xml/JobInitializationPluginMultiple.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/plugins/xml/JobInitializationPluginMultiple.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/plugins/xml/JobInitializationPluginMultiple.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,435 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.plugins.xml; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.URL; +import java.util.Date; +import java.util.Iterator; +import java.util.StringTokenizer; +import java.util.Vector; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.JobDetail; +import org.quartz.Scheduler; +import org.quartz.SchedulerConfigException; +import org.quartz.SchedulerException; +import org.quartz.SimpleTrigger; +import org.quartz.jobs.FileScanJob; +import org.quartz.jobs.FileScanListener; +import org.quartz.spi.SchedulerPlugin; +import org.quartz.xml.JobSchedulingDataProcessor; + +/** +* This plugin loads XML files to add jobs and schedule them with triggers + * as the scheduler is initialized, and can optionally periodically scan the + * file for changes. + * + * @author Brooke Hedrick + */ +public class JobInitializationPluginMultiple implements SchedulerPlugin, FileScanListener { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private String name; + + private Scheduler scheduler; + + private boolean overWriteExistingJobs = true; + + private boolean failOnFileNotFound = true; + + private String fileName = JobSchedulingDataProcessor.QUARTZ_XML_FILE_NAME; + + private Vector files = new Vector(); + + private boolean useContextClassLoader = true; + + private boolean validating = true; + + private boolean validatingSchema = true; + + private long scanInterval = 0; + + boolean initializing = true; + + boolean started = false; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public JobInitializationPluginMultiple() { + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Whether or not jobs defined in the XML file should be overwrite existing + * jobs with the same name. + * + * @return + */ + public boolean isOverWriteExistingJobs() { + return overWriteExistingJobs; + } + + /** + * Whether or not jobs defined in the XML file should be overwrite existing + * jobs with the same name. + * + * @param overWriteExistingJobs + */ + public void setOverWriteExistingJobs(boolean overWriteExistingJobs) { + this.overWriteExistingJobs = overWriteExistingJobs; + } + + /** + * The file name (and path) to the XML file that should be read. + * + * @return + */ + public String getFileName() { + return fileName; + } + + /** + * The file name (and path) to the XML file that should be read. + * + * @param fileName + */ + public void setFileName(String fileName) { + this.fileName = fileName; + } + + /** + * The interval (in seconds) at which to scan for changes to the file. + * If the file has been changed, it is re-loaded and parsed. The default + * value for the interval is 0, which disables scanning. + * + * @return Returns the scanInterval. + */ + public long getScanInterval() { + return scanInterval / 1000; + } + + /** + * The interval (in seconds) at which to scan for changes to the file. + * If the file has been changed, it is re-loaded and parsed. The default + * value for the interval is 0, which disables scanning. + * + * @param scanInterval The scanInterval to set. + */ + public void setScanInterval(long scanInterval) { + this.scanInterval = scanInterval * 1000; + } + + /** + * Whether or not initialization of the plugin should fail (throw an + * exception) if the file cannot be found. Default is true. + * + * @return + */ + public boolean isFailOnFileNotFound() { + return failOnFileNotFound; + } + + /** + * Whether or not initialization of the plugin should fail (throw an + * exception) if the file cannot be found. Default is true. + * + * @param overWriteExistingJobs + */ + public void setFailOnFileNotFound(boolean failOnFileNotFound) { + this.failOnFileNotFound = failOnFileNotFound; + } + + /** + * Whether or not the context class loader should be used. Default is true. + * + * @return + */ + public boolean isUseContextClassLoader() { + return useContextClassLoader; + } + + /** + * Whether or not context class loader should be used. Default is true. + * + * @param useContextClassLoader + */ + public void setUseContextClassLoader(boolean useContextClassLoader) { + this.useContextClassLoader = useContextClassLoader; + } + + /** + * Whether or not the XML should be validated. Default is true. + * + * @return + */ + public boolean isValidating() { + return validating; + } + + /** + * Whether or not the XML should be validated. Default is true. + * + * @param validating + */ + public void setValidating(boolean validating) { + this.validating = validating; + } + + /** + * Whether or not the XML schema should be validated. Default is true. + * + * @return + */ + public boolean isValidatingSchema() { + return validatingSchema; + } + + /** + * Whether or not the XML schema should be validated. Default is true. + * + * @param validatingSchema + */ + public void setValidatingSchema(boolean validatingSchema) { + this.validatingSchema = validatingSchema; + } + + protected static Log getLog() { + return LogFactory.getLog(JobInitializationPluginMultiple.class); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * SchedulerPlugin Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Called during creation of the Scheduler in order to give + * the SchedulerPlugin a chance to initialize. + *

+ * + * @throws SchedulerConfigException + * if there is an error initializing. + */ + public void initialize(String name, final Scheduler scheduler) + throws SchedulerException { + + initializing = true; + try { + this.name = name; + this.scheduler = scheduler; + + getLog().info("Registering Quartz Job Initialization Plug-in."); + + updateJobFileList(); + } + finally { + initializing = false; + } + } + + private void updateJobFileList() { + StringTokenizer stok = new StringTokenizer(fileName, ","); + + while(stok.hasMoreTokens()) { + JobFile jobFile = new JobFile(stok.nextToken()); + files.add(jobFile); + } + } + + public void start() { + //TODO:bth 6.3.2005 The way this works, I believe we only need one job scanning for changes per directory + + if(scanInterval > 0) { + try{ + Iterator iterator = files.iterator(); + while (iterator.hasNext()) { + JobFile jobFile = (JobFile)iterator.next(); + + SimpleTrigger trig = new SimpleTrigger( + "JobInitializationPluginMultiple_"+name, + "JobInitializationPluginMultiple", + new Date(), null, + SimpleTrigger.REPEAT_INDEFINITELY, scanInterval); + trig.setVolatility(true); + JobDetail job = new JobDetail( + "JobInitializationPluginMultiple_"+name, + "JobInitializationPluginMultiple", + FileScanJob.class); + job.setVolatility(true); + job.getJobDataMap().put(FileScanJob.FILE_NAME, jobFile.getFilePath()); + job.getJobDataMap().put(FileScanJob.FILE_SCAN_LISTENER_NAME, "JobInitializationPluginMultiple_"+name); + + scheduler.getContext().put("JobInitializationPluginMultiple_"+name, this); + scheduler.scheduleJob(job, trig); + } + } + catch(SchedulerException se) { + getLog().error("Error starting background-task for watching jobs file.", se); + } + } + + try { + processFiles(); + } + finally { + started = true; + } + } + + /** + *

+ * Called in order to inform the SchedulerPlugin that it + * should free up all of it's resources because the scheduler is shutting + * down. + *

+ */ + public void shutdown() { + // nothing to do + } + + + public void processFiles() { + JobSchedulingDataProcessor processor = + new JobSchedulingDataProcessor(isUseContextClassLoader(), isValidating(), isValidatingSchema()); + + Iterator iterator = files.iterator(); + while (iterator.hasNext()) { + JobFile jobFile = (JobFile)iterator.next(); + + try { + if (jobFile.getFileFound()) { + processor.processFileAndScheduleJobs(jobFile.getFileName(), scheduler, isOverWriteExistingJobs()); + } + } catch (Exception e) { + getLog().error("Error scheduling jobs: " + e.getMessage(), e); + } + } + } + + /** + * @see org.quartz.jobs.FileScanListener#fileUpdated(java.lang.String) + */ + public void fileUpdated(String fileName) { + if(started) + processFiles(); + } + + class JobFile { + private String fileName = null; + + private String filePath = null; + + private boolean fileFound = false; + + protected JobFile(String fileName) { + this.fileName = fileName; + } + + protected String getFileName() { + return fileName; + } + + protected boolean getFileFound() throws SchedulerException { + if(this.filePath == null) { + findFile(); + } + + return fileFound; + } + + protected String getFilePath() throws SchedulerException { + if(this.filePath == null) { + findFile(); + } + + return this.filePath; + } + + /** + * + */ + private void findFile() throws SchedulerException { + java.io.InputStream f = null; + + File file = new File(fileName); // files in filesystem + if (file == null || !file.exists()) { + // files in classpath + URL url = Thread.currentThread() + .getContextClassLoader() + .getResource(fileName); + if(url != null) { + file = new File(url.getPath()); + } + } + try { + f = new java.io.FileInputStream(file); + }catch (FileNotFoundException e) { + // ignore + } + + if (f == null && isFailOnFileNotFound()) { + throw new SchedulerException("File named '" + fileName + + "' does not exist."); + } else if (f == null) { + getLog().warn("File named '" + fileName + "' does not exist."); + } else { + fileFound = true; + try { + this.filePath = file.getPath(); + f.close(); + } catch (IOException ioe) { + getLog() + .warn("Error closing file named '" + fileName, ioe); + } + } + } + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/simpl/CascadingClassLoadHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/CascadingClassLoadHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/CascadingClassLoadHelper.java 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,200 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.simpl; + +import java.util.Iterator; +import java.util.LinkedList; +import java.net.URL; +import java.io.InputStream; + +import org.quartz.spi.ClassLoadHelper; + +/** + * A ClassLoadHelper uses all of the ClassLoadHelper + * types that are found in this package in its attempts to load a class, when + * one scheme is found to work, it is promoted to the scheme that will be used + * first the next time a class is loaded (in order to improve perfomance). + * + *

+ * This approach is used because of the wide variance in class loader behavior + * between the various environments in which Quartz runs (e.g. disparate + * application servers, stand-alone, mobile devices, etc.). Because of this + * disparity, Quartz ran into difficulty with a one class-load style fits-all + * design. Thus, this class loader finds the approach that works, then + * 'remembers' it. + *

+ * + * @see org.quartz.spi.ClassLoadHelper + * @see org.quartz.simpl.LoadingLoaderClassLoadHelper + * @see org.quartz.simpl.SimpleClassLoadHelper + * @see org.quartz.simpl.ThreadContextClassLoadHelper + * @see org.quartz.simpl.InitThreadContextClassLoadHelper + * + * @author jhouse + */ +public class CascadingClassLoadHelper implements ClassLoadHelper { + + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private LinkedList loadHelpers; + + private ClassLoadHelper bestCandidate; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Called to give the ClassLoadHelper a chance to initialize itself, + * including the oportunity to "steal" the class loader off of the calling + * thread, which is the thread that is initializing Quartz. + */ + public void initialize() { + loadHelpers = new LinkedList(); + + loadHelpers.add(new LoadingLoaderClassLoadHelper()); + loadHelpers.add(new SimpleClassLoadHelper()); + loadHelpers.add(new ThreadContextClassLoadHelper()); + loadHelpers.add(new InitThreadContextClassLoadHelper()); + + Iterator iter = loadHelpers.iterator(); + while (iter.hasNext()) { + ClassLoadHelper loadHelper = (ClassLoadHelper) iter.next(); + loadHelper.initialize(); + } + } + + /** + * Return the class with the given name. + */ + public Class loadClass(String name) throws ClassNotFoundException { + + if (bestCandidate != null) { + try { + return bestCandidate.loadClass(name); + } catch (Exception e) { + bestCandidate = null; + } + } + + ClassNotFoundException cnfe = null; + Class clazz = null; + ClassLoadHelper loadHelper = null; + + Iterator iter = loadHelpers.iterator(); + while (iter.hasNext()) { + loadHelper = (ClassLoadHelper) iter.next(); + + try { + clazz = loadHelper.loadClass(name); + break; + } catch (ClassNotFoundException e) { + cnfe = e; + } + } + + if (clazz == null) throw cnfe; + + bestCandidate = loadHelper; + + return clazz; + } + + /** + * Finds a resource with a given name. This method returns null if no + * resource with this name is found. + * @param name name of the desired resource + * @return a java.net.URL object + */ + public URL getResource(String name) { + + if (bestCandidate != null) { + try { + return bestCandidate.getResource(name); + } catch (Exception e) { + bestCandidate = null; + } + } + + URL result = null; + ClassLoadHelper loadHelper = null; + + Iterator iter = loadHelpers.iterator(); + while (iter.hasNext()) { + loadHelper = (ClassLoadHelper) iter.next(); + + result = loadHelper.getResource(name); + if (result != null) { + break; + } + } + + bestCandidate = loadHelper; + return result; + + } + + /** + * Finds a resource with a given name. This method returns null if no + * resource with this name is found. + * @param name name of the desired resource + * @return a java.io.InputStream object + */ + public InputStream getResourceAsStream(String name) { + + if (bestCandidate != null) { + try { + return bestCandidate.getResourceAsStream(name); + } catch (Exception e) { + bestCandidate = null; + } + } + + InputStream result = null; + ClassLoadHelper loadHelper = null; + + Iterator iter = loadHelpers.iterator(); + while (iter.hasNext()) { + loadHelper = (ClassLoadHelper) iter.next(); + + result = loadHelper.getResourceAsStream(name); + if (result != null) { + break; + } + } + + bestCandidate = loadHelper; + return result; + + } + +} Index: 3rdParty_sources/quartz/org/quartz/simpl/HostnameInstanceIdGenerator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/HostnameInstanceIdGenerator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/HostnameInstanceIdGenerator.java 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ +package org.quartz.simpl; + +import java.net.InetAddress; + +import org.quartz.SchedulerException; +import org.quartz.spi.InstanceIdGenerator; + +/** + *

+ * InstanceIdGenerator that names the scheduler instance using + * just the machine hostname. + *

+ * + *

+ * This class is useful when you know that your scheduler instance will be the + * only one running on a particular machine. Each time the scheduler is + * restarted, it will get the same instance id as long as the machine is not + * renamed. + *

+ * + * @see InstanceIdGenerator + * @see SimpleInstanceIdGenerator + */ +public class HostnameInstanceIdGenerator implements InstanceIdGenerator +{ + public String generateInstanceId() throws SchedulerException { + try { + return InetAddress.getLocalHost().getHostName(); + } + catch (Exception e) { + throw new SchedulerException("Couldn't get host name!", e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/simpl/InitThreadContextClassLoadHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/InitThreadContextClassLoadHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/InitThreadContextClassLoadHelper.java 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,96 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.simpl; + +import org.quartz.spi.ClassLoadHelper; + +import java.net.URL; +import java.io.InputStream; + +/** + * A ClassLoadHelper that uses either the context class loader + * of the thread that initialized Quartz. + * + * @see org.quartz.spi.ClassLoadHelper + * @see org.quartz.simpl.ThreadContextClassLoadHelper + * @see org.quartz.simpl.SimpleClassLoadHelper + * @see org.quartz.simpl.CascadingClassLoadHelper + * @see org.quartz.simpl.LoadingLoaderClassLoadHelper + * + * @author jhouse + */ +public class InitThreadContextClassLoadHelper implements ClassLoadHelper { + + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private ClassLoader initClassLoader; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Called to give the ClassLoadHelper a chance to initialize itself, + * including the oportunity to "steal" the class loader off of the calling + * thread, which is the thread that is initializing Quartz. + */ + public void initialize() { + initClassLoader = Thread.currentThread().getContextClassLoader(); + } + + /** + * Return the class with the given name. + */ + public Class loadClass(String name) throws ClassNotFoundException { + return initClassLoader.loadClass(name); + } + + /** + * Finds a resource with a given name. This method returns null if no + * resource with this name is found. + * @param name name of the desired resource + * @return a java.net.URL object + */ + public URL getResource(String name) { + return initClassLoader.getResource(name); + } + + /** + * Finds a resource with a given name. This method returns null if no + * resource with this name is found. + * @param name name of the desired resource + * @return a java.io.InputStream object + */ + public InputStream getResourceAsStream(String name) { + return initClassLoader.getResourceAsStream(name); + } +} Index: 3rdParty_sources/quartz/org/quartz/simpl/LoadingLoaderClassLoadHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/LoadingLoaderClassLoadHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/LoadingLoaderClassLoadHelper.java 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.simpl; + +import org.quartz.spi.ClassLoadHelper; + +import java.net.URL; +import java.io.InputStream; + +/** + * A ClassLoadHelper that uses either the loader of it's own + * class (this.getClass().getClassLoader().loadClass( .. )). + * + * @see org.quartz.spi.ClassLoadHelper + * @see org.quartz.simpl.InitThreadContextClassLoadHelper + * @see org.quartz.simpl.SimpleClassLoadHelper + * @see org.quartz.simpl.CascadingClassLoadHelper + * + * @author jhouse + */ +public class LoadingLoaderClassLoadHelper implements ClassLoadHelper { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Called to give the ClassLoadHelper a chance to initialize itself, + * including the oportunity to "steal" the class loader off of the calling + * thread, which is the thread that is initializing Quartz. + */ + public void initialize() { + } + + /** + * Return the class with the given name. + */ + public Class loadClass(String name) throws ClassNotFoundException { + return getClassLoader().loadClass(name); + } + + /** + * Finds a resource with a given name. This method returns null if no + * resource with this name is found. + * @param name name of the desired resource + * @return a java.net.URL object + */ + public URL getResource(String name) { + return getClassLoader().getResource(name); + } + + /** + * Finds a resource with a given name. This method returns null if no + * resource with this name is found. + * @param name name of the desired resource + * @return a java.io.InputStream object + */ + public InputStream getResourceAsStream(String name) { + return getClassLoader().getResourceAsStream(name); + } + + private ClassLoader getClassLoader() { + return this.getClass().getClassLoader(); + } +} Index: 3rdParty_sources/quartz/org/quartz/simpl/PropertySettingJobFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/PropertySettingJobFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/PropertySettingJobFactory.java 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,305 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ +package org.quartz.simpl; + +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.InvocationTargetException; +import java.util.Locale; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.Job; +import org.quartz.JobDataMap; +import org.quartz.SchedulerException; +import org.quartz.spi.TriggerFiredBundle; + + + +/** + * A JobFactory that instantiates the Job instance (using the default no-arg + * constructor, or more specifically: class.newInstance()), and + * then attempts to set all values in the JobExecutionContext's + * JobDataMap onto bean properties of the Job. + * + * @see org.quartz.spi.JobFactory + * @see SimpleJobFactory + * @see JobExecutionContext#getMergedJobDataMap() + * @see #setWarnIfPropertyNotFound(boolean) + * @see #setThrowIfPropertyNotFound(boolean) + * + * @author jhouse + */ +public class PropertySettingJobFactory extends SimpleJobFactory { + + private Log log = LogFactory.getLog(SimpleJobFactory.class); + + private boolean warnIfNotFound = true; + private boolean throwIfNotFound = false; + + public Job newJob(TriggerFiredBundle bundle) throws SchedulerException { + + Job job = super.newJob(bundle); + + JobDataMap jobDataMap = new JobDataMap(); + jobDataMap.putAll(bundle.getJobDetail().getJobDataMap()); + jobDataMap.putAll(bundle.getTrigger().getJobDataMap()); + + setBeanProps(job, jobDataMap); + + return job; + } + + protected void setBeanProps(Object obj, JobDataMap data) throws SchedulerException { + + BeanInfo bi = null; + try { + bi = Introspector.getBeanInfo(obj.getClass()); + } catch (IntrospectionException e1) { + if(isThrowIfPropertyNotFound()) { + throw new SchedulerException("Unable to introspect Job class.", e1); + } + if(isWarnIfPropertyNotFound()) { + log.warn("Unable to introspect Job class.", e1); + } + } + + PropertyDescriptor[] propDescs = bi.getPropertyDescriptors(); + + java.util.Iterator keys = data.keySet().iterator(); + while (keys.hasNext()) { + String name = (String) keys.next(); + String c = name.substring(0, 1).toUpperCase(Locale.US); + String methName = "set" + c + name.substring(1); + + java.lang.reflect.Method setMeth = getSetMethod(methName, propDescs); + + Class paramType = null; + Object o = null; + + try { + if (setMeth == null) { + if(isThrowIfPropertyNotFound()) { + throw new SchedulerException( + "No setter on Job class " + obj.getClass() + + " for property '" + name + "'"); + } + if(isWarnIfPropertyNotFound()) { + log.warn( + "No setter on Job class " + obj.getClass() + + " for property '" + name + "'"); + } + continue; + } + + paramType = setMeth.getParameterTypes()[0]; + o = data.get(name); + + if (paramType.equals(int.class)) { + if(o instanceof Integer) + setMeth.invoke(obj, + new Object[]{o}); + else if(o instanceof String) + setMeth.invoke(obj, + new Object[]{data.getIntegerFromString(name)}); + } else if (paramType.equals(long.class)) { + if(o instanceof Long) + setMeth.invoke(obj, + new Object[]{o}); + else if(o instanceof String) + setMeth.invoke(obj, + new Object[]{data.getLongFromString(name)}); + } else if (paramType.equals(float.class)) { + if(o instanceof Float) + setMeth.invoke(obj, + new Object[]{o}); + else if(o instanceof String) + setMeth.invoke(obj, + new Object[]{data.getFloatFromString(name)}); + } else if (paramType.equals(double.class)) { + if(o instanceof Double) + setMeth.invoke(obj, + new Object[]{o}); + else if(o instanceof String) + setMeth.invoke(obj, + new Object[]{data.getDoubleFromString(name)}); + } else if (paramType.equals(boolean.class)) { + if(o instanceof Boolean) + setMeth.invoke(obj, + new Object[]{o}); + else if(o instanceof String) + setMeth.invoke(obj, + new Object[]{data.getBooleanFromString(name)}); + } else if (paramType.equals(String.class)) { + if(o instanceof String) + setMeth.invoke(obj, + new Object[]{o}); + } else { + if(paramType.isAssignableFrom(o.getClass())) { + setMeth.invoke(obj, + new Object[]{o}); + } + else + throw new NoSuchMethodException(); + } + } catch (NumberFormatException nfe) { + if(isThrowIfPropertyNotFound()) { + throw new SchedulerException( + "The setter on Job class " + obj.getClass() + + " for property '" + name + + "' expects a " + paramType + + " but was given " + o, nfe); + } + if(isWarnIfPropertyNotFound()) { + log.warn( + "The setter on Job class " + obj.getClass() + + " for property '" + name + + "' expects a " + paramType + + " but was given " + o, nfe); + } + continue; + } catch (NoSuchMethodException e) { + if(isThrowIfPropertyNotFound()) { + throw new SchedulerException( + "The setter on Job class " + obj.getClass() + + " for property '" + name + + "' expects a " + paramType + + " but was given " + o.getClass()); + } + if(isWarnIfPropertyNotFound()) { + log.warn( + "The setter on Job class " + obj.getClass() + + " for property '" + name + + "' expects a " + paramType + + " but was given a " + o.getClass()); + } + continue; + } catch (IllegalArgumentException e) { + if(isThrowIfPropertyNotFound()) { + throw new SchedulerException( + "The setter on Job class " + obj.getClass() + + " for property '" + name + + "' expects a " + paramType + + " but was given " + o.getClass(),e ); + } + if(isWarnIfPropertyNotFound()) { + log.warn( + "The setter on Job class " + obj.getClass() + + " for property '" + name + + "' expects a " + paramType + + " but was given a " + o.getClass(), e); + } + continue; + } catch (IllegalAccessException e) { + if(isThrowIfPropertyNotFound()) { + throw new SchedulerException( + "The setter on Job class " + obj.getClass() + + " for property '" + name + + "' could not be accessed.", e); + } + if(isWarnIfPropertyNotFound()) { + log.warn( + "The setter on Job class " + obj.getClass() + + " for property '" + name + + "' expects a " + paramType + + "' could not be accessed.", e); + } + continue; + } catch (InvocationTargetException e) { + if(isThrowIfPropertyNotFound()) { + throw new SchedulerException( + "The setter on Job class " + obj.getClass() + + " for property '" + name + + "' could not be accessed.", e); + } + if(isWarnIfPropertyNotFound()) { + log.warn( + "The setter on Job class " + obj.getClass() + + " for property '" + name + + "' expects a " + paramType + + "' could not be accessed.", e); + } + continue; + } + } + } + + private java.lang.reflect.Method getSetMethod(String name, + PropertyDescriptor[] props) { + for (int i = 0; i < props.length; i++) { + java.lang.reflect.Method wMeth = props[i].getWriteMethod(); + + if(wMeth == null) + continue; + + if(wMeth.getParameterTypes().length != 1) + continue; + + if (wMeth.getName().equals(name)) return wMeth; + } + + return null; + } + + /** + * Whether the JobInstantiation should fail and throw and exception if + * a key (name) and value (type) found in the JobDataMap does not + * correspond to a proptery setter on the Job class. + * + * @return Returns the throwIfNotFound. + */ + public boolean isThrowIfPropertyNotFound() { + return throwIfNotFound; + } + + /** + * Whether the JobInstantiation should fail and throw and exception if + * a key (name) and value (type) found in the JobDataMap does not + * correspond to a proptery setter on the Job class. + * + * @param throwIfNotFound defaults to false. + */ + public void setThrowIfPropertyNotFound(boolean throwIfNotFound) { + this.throwIfNotFound = throwIfNotFound; + } + + /** + * Whether a warning should be logged if + * a key (name) and value (type) found in the JobDataMap does not + * correspond to a proptery setter on the Job class. + * + * @return Returns the warnIfNotFound. + */ + public boolean isWarnIfPropertyNotFound() { + return warnIfNotFound; + } + + /** + * Whether a warning should be logged if + * a key (name) and value (type) found in the JobDataMap does not + * correspond to a proptery setter on the Job class. + * + * @param warnIfNotFound defaults to true. + */ + public void setWarnIfPropertyNotFound(boolean warnIfNotFound) { + this.warnIfNotFound = warnIfNotFound; + } + + +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/simpl/RAMJobStore.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/RAMJobStore.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/RAMJobStore.java 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,1526 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.simpl; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; +import java.util.TreeSet; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.Calendar; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.JobPersistenceException; +import org.quartz.ObjectAlreadyExistsException; +import org.quartz.SchedulerException; +import org.quartz.Trigger; +import org.quartz.core.SchedulingContext; +import org.quartz.spi.ClassLoadHelper; +import org.quartz.spi.JobStore; +import org.quartz.spi.SchedulerSignaler; +import org.quartz.spi.TriggerFiredBundle; + +/** + *

+ * This class implements a {@link org.quartz.spi.JobStore} that + * utilizes RAM as its storage device. + *

+ * + *

+ * As you should know, the ramification of this is that access is extrememly + * fast, but the data is completely volatile - therefore this JobStore + * should not be used if true persistence between program shutdowns is + * required. + *

+ * + * @author James House + * @author Sharada Jambula + */ +public class RAMJobStore implements JobStore { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected HashMap jobsByFQN = new HashMap(1000); + + protected HashMap triggersByFQN = new HashMap(1000); + + protected HashMap jobsByGroup = new HashMap(25); + + protected HashMap triggersByGroup = new HashMap(25); + + protected TreeSet timeTriggers = new TreeSet(new TriggerComparator()); + + protected HashMap calendarsByName = new HashMap(25); + + protected ArrayList triggers = new ArrayList(1000); + + protected Object jobLock = new Object(); + + protected Object triggerLock = new Object(); + + protected HashSet pausedTriggerGroups = new HashSet(); + + protected HashSet blockedJobs = new HashSet(); + + protected long misfireThreshold = 5000l; + + protected SchedulerSignaler signaler; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a new RAMJobStore. + *

+ */ + public RAMJobStore() { + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected Log getLog() { + return LogFactory.getLog(RAMJobStore.class); + } + + /** + *

+ * Called by the QuartzScheduler before the JobStore is + * used, in order to give the it a chance to initialize. + *

+ */ + public void initialize(ClassLoadHelper loadHelper, + SchedulerSignaler signaler) { + + this.signaler = signaler; + + getLog().info("RAMJobStore initialized."); + } + + public void schedulerStarted() throws SchedulerException + { + // nothing to do + } + + public long getMisfireThreshold() { + return misfireThreshold; + } + + /** + * The the number of milliseconds by which a trigger must have missed its + * next-fire-time, in order for it to be considered "misfired" and thus + * have its misfire instruction applied. + * + * @param misfireThreshold + */ + public void setMisfireThreshold(long misfireThreshold) { + if (misfireThreshold < 1) + throw new IllegalArgumentException( + "Misfirethreashold must be larger than 0"); + this.misfireThreshold = misfireThreshold; + } + + /** + *

+ * Called by the QuartzScheduler to inform the JobStore that + * it should free up all of it's resources because the scheduler is + * shutting down. + *

+ */ + public void shutdown() { + } + + public boolean supportsPersistence() { + return false; + } + + /** + *

+ * Store the given {@link org.quartz.JobDetail} and {@link org.quartz.Trigger}. + *

+ * + * @param newJob + * The JobDetail to be stored. + * @param newTrigger + * The Trigger to be stored. + * @throws ObjectAlreadyExistsException + * if a Job with the same name/group already + * exists. + */ + public void storeJobAndTrigger(SchedulingContext ctxt, JobDetail newJob, + Trigger newTrigger) throws JobPersistenceException { + storeJob(ctxt, newJob, false); + storeTrigger(ctxt, newTrigger, false); + } + + /** + *

+ * Store the given {@link org.quartz.Job}. + *

+ * + * @param newJob + * The Job to be stored. + * @param replaceExisting + * If true, any Job existing in the + * JobStore with the same name & group should be + * over-written. + * @throws ObjectAlreadyExistsException + * if a Job with the same name/group already + * exists, and replaceExisting is set to false. + */ + public void storeJob(SchedulingContext ctxt, JobDetail newJob, + boolean replaceExisting) throws ObjectAlreadyExistsException { + JobWrapper jw = new JobWrapper(newJob); + + boolean repl = false; + + if (jobsByFQN.get(jw.key) != null) { + if (!replaceExisting) + throw new ObjectAlreadyExistsException(newJob); + repl = true; + } + + synchronized (jobLock) { + if (!repl) { + // get job group + HashMap grpMap = (HashMap) jobsByGroup.get(newJob.getGroup()); + if (grpMap == null) { + grpMap = new HashMap(100); + jobsByGroup.put(newJob.getGroup(), grpMap); + } + // add to jobs by group + grpMap.put(newJob.getName(), jw); + // add to jobs by FQN map + jobsByFQN.put(jw.key, jw); + } else { + // update job detail + JobWrapper orig = (JobWrapper) jobsByFQN.get(jw.key); + orig.jobDetail = newJob; + } + } + } + + /** + *

+ * Remove (delete) the {@link org.quartz.Job} with the given + * name, and any {@link org.quartz.Trigger} s that reference + * it. + *

+ * + * @param jobName + * The name of the Job to be removed. + * @param groupName + * The group name of the Job to be removed. + * @return true if a Job with the given name & + * group was found and removed from the store. + */ + public boolean removeJob(SchedulingContext ctxt, String jobName, + String groupName) { + String key = JobWrapper.getJobNameKey(jobName, groupName); + + boolean found = false; + + Trigger[] trigger = getTriggersForJob(ctxt, jobName, + groupName); + for (int i = 0; i < trigger.length; i++) { + Trigger trig = trigger[i]; + this.removeTrigger(ctxt, trig.getName(), trig.getGroup()); + found = true; + } + synchronized (jobLock) { + found = (jobsByFQN.remove(key) != null) | found; + if (found) { + + HashMap grpMap = (HashMap) jobsByGroup.get(groupName); + if (grpMap != null) { + grpMap.remove(jobName); + if (grpMap.size() == 0) jobsByGroup.remove(groupName); + } + } + } + + return found; + } + + /** + *

+ * Store the given {@link org.quartz.Trigger}. + *

+ * + * @param newTrigger + * The Trigger to be stored. + * @param replaceExisting + * If true, any Trigger existing in + * the JobStore with the same name & group should + * be over-written. + * @throws ObjectAlreadyExistsException + * if a Trigger with the same name/group already + * exists, and replaceExisting is set to false. + * + * @see #pauseTriggerGroup(SchedulingContext, String) + */ + public void storeTrigger(SchedulingContext ctxt, Trigger newTrigger, + boolean replaceExisting) throws JobPersistenceException { + TriggerWrapper tw = new TriggerWrapper(newTrigger); + + if (triggersByFQN.get(tw.key) != null) { + if (!replaceExisting) + throw new ObjectAlreadyExistsException(newTrigger); + + removeTrigger(ctxt, newTrigger.getName(), newTrigger.getGroup()); + } + + if (retrieveJob(ctxt, newTrigger.getJobName(), newTrigger.getJobGroup()) == null) + throw new JobPersistenceException("The job (" + + newTrigger.getFullJobName() + + ") referenced by the trigger does not exist."); + + synchronized (triggerLock) { + // add to triggers array + triggers.add(tw); + // add to triggers by group + HashMap grpMap = (HashMap) triggersByGroup.get(newTrigger + .getGroup()); + if (grpMap == null) { + grpMap = new HashMap(100); + triggersByGroup.put(newTrigger.getGroup(), grpMap); + } + grpMap.put(newTrigger.getName(), tw); + // add to triggers by FQN map + triggersByFQN.put(tw.key, tw); + + synchronized (pausedTriggerGroups) { + if (pausedTriggerGroups.contains(newTrigger.getGroup())) { + tw.state = TriggerWrapper.STATE_PAUSED; + if (blockedJobs.contains(tw.jobKey)) + tw.state = TriggerWrapper.STATE_PAUSED_BLOCKED; + } + else if (blockedJobs.contains(tw.jobKey)) + tw.state = TriggerWrapper.STATE_BLOCKED; + else + timeTriggers.add(tw); + } + } + } + + /** + *

+ * Remove (delete) the {@link org.quartz.Trigger} with the + * given name. + *

+ * + * @param triggerName + * The name of the Trigger to be removed. + * @param groupName + * The group name of the Trigger to be removed. + * @return true if a Trigger with the given + * name & group was found and removed from the store. + */ + public boolean removeTrigger(SchedulingContext ctxt, String triggerName, + String groupName) { + String key = TriggerWrapper.getTriggerNameKey(triggerName, groupName); + + boolean found = false; + + synchronized (triggerLock) { + // remove from triggers by FQN map + found = (triggersByFQN.remove(key) == null) ? false : true; + if (found) { + TriggerWrapper tw = null; + // remove from triggers by group + HashMap grpMap = (HashMap) triggersByGroup.get(groupName); + if (grpMap != null) { + grpMap.remove(triggerName); + if (grpMap.size() == 0) triggersByGroup.remove(groupName); + } + // remove from triggers array + Iterator tgs = triggers.iterator(); + while (tgs.hasNext()) { + tw = (TriggerWrapper) tgs.next(); + if (key.equals(tw.key)) { + tgs.remove(); + break; + } + } + timeTriggers.remove(tw); + + JobWrapper jw = (JobWrapper) jobsByFQN.get(JobWrapper + .getJobNameKey(tw.trigger.getJobName(), tw.trigger + .getJobGroup())); + Trigger[] trigs = getTriggersForJob(ctxt, tw.trigger + .getJobName(), tw.trigger.getJobGroup()); + if ((trigs == null || trigs.length == 0) + && !jw.jobDetail.isDurable()) + removeJob(ctxt, tw.trigger.getJobName(), tw.trigger + .getJobGroup()); + } + } + + return found; + } + + + /** + * @see org.quartz.spi.JobStore#replaceTrigger(org.quartz.core.SchedulingContext, java.lang.String, java.lang.String, org.quartz.Trigger) + */ + public boolean replaceTrigger(SchedulingContext ctxt, String triggerName, String groupName, Trigger newTrigger) throws JobPersistenceException { + String key = TriggerWrapper.getTriggerNameKey(triggerName, groupName); + + boolean found = false; + + synchronized (triggerLock) { + // remove from triggers by FQN map + TriggerWrapper tw = (TriggerWrapper) triggersByFQN.remove(key); + found = ( tw == null) ? false : true; + + if (found) { + + if(!tw.getTrigger().getJobName().equals(newTrigger.getJobName()) || + !tw.getTrigger().getJobGroup().equals(newTrigger.getJobGroup())) + throw new JobPersistenceException("New trigger is not related to the same job as the old trigger."); + + tw = null; + // remove from triggers by group + HashMap grpMap = (HashMap) triggersByGroup.get(groupName); + if (grpMap != null) { + grpMap.remove(triggerName); + if (grpMap.size() == 0) triggersByGroup.remove(groupName); + } + // remove from triggers array + Iterator tgs = triggers.iterator(); + while (tgs.hasNext()) { + tw = (TriggerWrapper) tgs.next(); + if (key.equals(tw.key)) { + tgs.remove(); + break; + } + } + timeTriggers.remove(tw); + + try { + storeTrigger(ctxt, newTrigger, false); + } + catch(JobPersistenceException jpe) { + storeTrigger(ctxt, tw.getTrigger(), false); // put previous trigger back... + throw jpe; + } + } + } + + return found; + } + + /** + *

+ * Retrieve the {@link org.quartz.JobDetail} for the given + * {@link org.quartz.Job}. + *

+ * + * @param jobName + * The name of the Job to be retrieved. + * @param groupName + * The group name of the Job to be retrieved. + * @return The desired Job, or null if there is no match. + */ + public JobDetail retrieveJob(SchedulingContext ctxt, String jobName, + String groupName) { + JobWrapper jw = (JobWrapper) jobsByFQN.get(JobWrapper.getJobNameKey( + jobName, groupName)); + if (jw != null) return jw.jobDetail; + + return null; + } + + /** + *

+ * Retrieve the given {@link org.quartz.Trigger}. + *

+ * + * @param jobName + * The name of the Trigger to be retrieved. + * @param groupName + * The group name of the Trigger to be retrieved. + * @return The desired Trigger, or null if there is no + * match. + */ + public Trigger retrieveTrigger(SchedulingContext ctxt, String triggerName, + String groupName) { + TriggerWrapper tw = (TriggerWrapper) triggersByFQN.get(TriggerWrapper + .getTriggerNameKey(triggerName, groupName)); + if (tw != null) return tw.getTrigger(); + + return null; + } + + /** + *

+ * Get the current state of the identified {@link Trigger}. + *

+ * + * @see Trigger#STATE_NORMAL + * @see Trigger#STATE_PAUSED + * @see Trigger#STATE_COMPLETE + * @see Trigger#STATE_ERROR + * @see Trigger#STATE_BLOCKED + * @see Trigger#STATE_NONE + */ + public int getTriggerState(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException { + TriggerWrapper tw = (TriggerWrapper) triggersByFQN.get(TriggerWrapper + .getTriggerNameKey(triggerName, groupName)); + if (tw == null) return Trigger.STATE_NONE; + + if (tw.state == TriggerWrapper.STATE_COMPLETE) + return Trigger.STATE_COMPLETE; + + if (tw.state == TriggerWrapper.STATE_PAUSED) + return Trigger.STATE_PAUSED; + + if (tw.state == TriggerWrapper.STATE_PAUSED_BLOCKED) + return Trigger.STATE_PAUSED; + + if (tw.state == TriggerWrapper.STATE_BLOCKED) + return Trigger.STATE_BLOCKED; + + if (tw.state == TriggerWrapper.STATE_ERROR) + return Trigger.STATE_ERROR; + + return Trigger.STATE_NORMAL; + } + + /** + *

+ * Store the given {@link org.quartz.Calendar}. + *

+ * + * @param calendar + * The Calendar to be stored. + * @param replaceExisting + * If true, any Calendar existing + * in the JobStore with the same name & group + * should be over-written. + * @param updateTriggers + * If true, any Triggers existing + * in the JobStore that reference an existing + * Calendar with the same name with have their next fire time + * re-computed with the new Calendar. + * @throws ObjectAlreadyExistsException + * if a Calendar with the same name already + * exists, and replaceExisting is set to false. + */ + public void storeCalendar(SchedulingContext ctxt, String name, + Calendar calendar, boolean replaceExisting, boolean updateTriggers) + throws ObjectAlreadyExistsException { + Object obj = calendarsByName.get(name); + + if (obj != null && replaceExisting == false) throw new ObjectAlreadyExistsException( + "Calendar with name '" + name + "' already exists."); + else if (obj != null) calendarsByName.remove(name); + + calendarsByName.put(name, calendar); + + if(obj != null && updateTriggers) { + synchronized (triggerLock) { + Iterator trigs = getTriggerWrappersForCalendar(name).iterator(); + while (trigs.hasNext()) { + TriggerWrapper tw = (TriggerWrapper) trigs.next(); + Trigger trig = tw.getTrigger(); + boolean removed = timeTriggers.remove(tw); + + trig.updateWithNewCalendar(calendar, getMisfireThreshold()); + + if(removed) + timeTriggers.add(tw); + } + } + } + } + + /** + *

+ * Remove (delete) the {@link org.quartz.Calendar} with the + * given name. + *

+ * + *

+ * If removal of the Calendar would result in + * s pointing to non-existent calendars, then a + * JobPersistenceException will be thrown.

+ * * + * @param calName The name of the Calendar to be removed. + * @return true if a Calendar with the given name + * was found and removed from the store. + */ + public boolean removeCalendar(SchedulingContext ctxt, String calName) + throws JobPersistenceException { + int numRefs = 0; + + synchronized (triggerLock) { + Iterator itr = triggers.iterator(); + while (itr.hasNext()) { + Trigger trigg = ((TriggerWrapper) itr.next()).trigger; + if (trigg.getCalendarName() != null + && trigg.getCalendarName().equals(calName)) numRefs++; + } + } + + if (numRefs > 0) + throw new JobPersistenceException( + "Calender cannot be removed if it referenced by a Trigger!"); + + return (calendarsByName.remove(calName) != null); + } + + /** + *

+ * Retrieve the given {@link org.quartz.Trigger}. + *

+ * + * @param calName + * The name of the Calendar to be retrieved. + * @return The desired Calendar, or null if there is no + * match. + */ + public Calendar retrieveCalendar(SchedulingContext ctxt, String calName) { + return (Calendar) calendarsByName.get(calName); + } + + /** + *

+ * Get the number of {@link org.quartz.JobDetail} s that are + * stored in the JobsStore. + *

+ */ + public int getNumberOfJobs(SchedulingContext ctxt) { + return jobsByFQN.size(); + } + + /** + *

+ * Get the number of {@link org.quartz.Trigger} s that are + * stored in the JobsStore. + *

+ */ + public int getNumberOfTriggers(SchedulingContext ctxt) { + return triggers.size(); + } + + /** + *

+ * Get the number of {@link org.quartz.Calendar} s that are + * stored in the JobsStore. + *

+ */ + public int getNumberOfCalendars(SchedulingContext ctxt) { + return calendarsByName.size(); + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Job} s that + * have the given group name. + *

+ */ + public String[] getJobNames(SchedulingContext ctxt, String groupName) { + String[] outList = null; + HashMap grpMap = (HashMap) jobsByGroup.get(groupName); + if (grpMap != null) { + synchronized (jobLock) { + outList = new String[grpMap.size()]; + int outListPos = 0; + Iterator keys = grpMap.keySet().iterator(); + while (keys.hasNext()) { + String key = (String) keys.next(); + JobWrapper jw = (JobWrapper) grpMap.get(key); + if (jw != null) + outList[outListPos++] = jw.jobDetail.getName(); + } + } + } else + outList = new String[0]; + + return outList; + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Calendar} s + * in the JobStore. + *

+ * + *

+ * If there are no Calendars in the given group name, the result should be + * a zero-length array (not null). + *

+ */ + public String[] getCalendarNames(SchedulingContext ctxt) { + Set names = calendarsByName.keySet(); + return (String[]) names.toArray(new String[names.size()]); + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Trigger} s + * that have the given group name. + *

+ */ + public String[] getTriggerNames(SchedulingContext ctxt, String groupName) { + String[] outList = null; + HashMap grpMap = (HashMap) triggersByGroup.get(groupName); + if (grpMap != null) { + synchronized (triggerLock) { + outList = new String[grpMap.size()]; + int outListPos = 0; + Iterator keys = grpMap.keySet().iterator(); + while (keys.hasNext()) { + String key = (String) keys.next(); + TriggerWrapper tw = (TriggerWrapper) grpMap.get(key); + if (tw != null) + outList[outListPos++] = tw.trigger.getName(); + } + } + } else + outList = new String[0]; + + return outList; + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Job} + * groups. + *

+ */ + public String[] getJobGroupNames(SchedulingContext ctxt) { + String[] outList = null; + + synchronized (jobLock) { + outList = new String[jobsByGroup.size()]; + int outListPos = 0; + Iterator keys = jobsByGroup.keySet().iterator(); + while (keys.hasNext()) { + outList[outListPos++] = (String) keys.next(); + } + } + + return outList; + } + + /** + *

+ * Get the names of all of the {@link org.quartz.Trigger} + * groups. + *

+ */ + public String[] getTriggerGroupNames(SchedulingContext ctxt) { + String[] outList = null; + + synchronized (triggerLock) { + outList = new String[triggersByGroup.size()]; + int outListPos = 0; + Iterator keys = triggersByGroup.keySet().iterator(); + while (keys.hasNext()) { + outList[outListPos++] = (String) keys.next(); + } + } + + return outList; + } + + /** + *

+ * Get all of the Triggers that are associated to the given Job. + *

+ * + *

+ * If there are no matches, a zero-length array should be returned. + *

+ */ + public Trigger[] getTriggersForJob(SchedulingContext ctxt, String jobName, + String groupName) { + ArrayList trigList = new ArrayList(); + + String jobKey = JobWrapper.getJobNameKey(jobName, groupName); + synchronized (triggerLock) { + for (int i = 0; i < triggers.size(); i++) { + TriggerWrapper tw = (TriggerWrapper) triggers.get(i); + if (tw.jobKey.equals(jobKey)) trigList.add(tw.trigger.clone()); + } + } + + return (Trigger[]) trigList.toArray(new Trigger[trigList.size()]); + } + + protected ArrayList getTriggerWrappersForJob(String jobName, String groupName) { + ArrayList trigList = new ArrayList(); + + String jobKey = JobWrapper.getJobNameKey(jobName, groupName); + synchronized (triggerLock) { + for (int i = 0; i < triggers.size(); i++) { + TriggerWrapper tw = (TriggerWrapper) triggers.get(i); + if (tw.jobKey.equals(jobKey)) trigList.add(tw); + } + } + + return trigList; + } + + protected ArrayList getTriggerWrappersForCalendar(String calName) { + ArrayList trigList = new ArrayList(); + + synchronized (triggerLock) { + for (int i = 0; i < triggers.size(); i++) { + TriggerWrapper tw = (TriggerWrapper) triggers.get(i); + String tcalName = tw.getTrigger().getCalendarName(); + if (tcalName != null && tcalName.equals(calName)) + trigList.add(tw); + } + } + + return trigList; + } + + /** + *

+ * Pause the {@link Trigger} with the given name. + *

+ * + */ + public void pauseTrigger(SchedulingContext ctxt, String triggerName, + String groupName) { + + TriggerWrapper tw = (TriggerWrapper) triggersByFQN.get(TriggerWrapper + .getTriggerNameKey(triggerName, groupName)); + + // does the trigger exist? + if (tw == null || tw.trigger == null) return; + // if the trigger is "complete" pausing it does not make sense... + if (tw.state == TriggerWrapper.STATE_COMPLETE) return; + + synchronized (triggerLock) { + if(tw.state == TriggerWrapper.STATE_BLOCKED) + tw.state = TriggerWrapper.STATE_PAUSED_BLOCKED; + else + tw.state = TriggerWrapper.STATE_PAUSED; + timeTriggers.remove(tw); + } + } + + /** + *

+ * Pause all of the {@link Trigger}s in the given group. + *

+ * + *

+ * The JobStore should "remember" that the group is paused, and impose the + * pause on any new triggers that are added to the group while the group is + * paused. + *

+ * + */ + public void pauseTriggerGroup(SchedulingContext ctxt, String groupName) { + + synchronized (pausedTriggerGroups) { + if (pausedTriggerGroups.contains(groupName)) return; + pausedTriggerGroups.add(groupName); + String[] names = getTriggerNames(ctxt, groupName); + + for (int i = 0; i < names.length; i++) { + pauseTrigger(ctxt, names[i], groupName); + } + } + } + + /** + *

+ * Pause the {@link org.quartz.JobDetail} with the given + * name - by pausing all of its current Triggers. + *

+ * + */ + public void pauseJob(SchedulingContext ctxt, String jobName, + String groupName) { + synchronized (pausedTriggerGroups) { + Trigger[] triggers = getTriggersForJob(ctxt, jobName, groupName); + for (int j = 0; j < triggers.length; j++) { + pauseTrigger(ctxt, triggers[j].getName(), triggers[j].getGroup()); + } + } + } + + /** + *

+ * Pause all of the {@link org.quartz.JobDetail}s in the + * given group - by pausing all of their Triggers. + *

+ * + * + *

+ * The JobStore should "remember" that the group is paused, and impose the + * pause on any new jobs that are added to the group while the group is + * paused. + *

+ */ + public void pauseJobGroup(SchedulingContext ctxt, String groupName) { + synchronized (pausedTriggerGroups) { + String[] jobNames = getJobNames(ctxt, groupName); + + for (int i = 0; i < jobNames.length; i++) { + Trigger[] triggers = getTriggersForJob(ctxt, jobNames[i], + groupName); + for (int j = 0; j < triggers.length; j++) { + pauseTrigger(ctxt, triggers[j].getName(), + triggers[j].getGroup()); + } + } + } + } + + /** + *

+ * Resume (un-pause) the {@link Trigger} with the given + * name. + *

+ * + *

+ * If the Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + */ + public void resumeTrigger(SchedulingContext ctxt, String triggerName, + String groupName) { + + TriggerWrapper tw = (TriggerWrapper) triggersByFQN.get(TriggerWrapper + .getTriggerNameKey(triggerName, groupName)); + + Trigger trig = tw.getTrigger(); + + // does the trigger exist? + if (tw == null || tw.trigger == null) return; + // if the trigger is not paused resuming it does not make sense... + if (tw.state != TriggerWrapper.STATE_PAUSED && + tw.state != TriggerWrapper.STATE_PAUSED_BLOCKED) + return; + + synchronized (triggerLock) { + if(blockedJobs.contains( JobWrapper.getJobNameKey(trig.getJobName(), trig.getJobGroup()) )) + tw.state = TriggerWrapper.STATE_BLOCKED; + else + tw.state = TriggerWrapper.STATE_WAITING; + + applyMisfire(tw); + + if (tw.state == TriggerWrapper.STATE_WAITING) timeTriggers.add(tw); + } + } + + /** + *

+ * Resume (un-pause) all of the {@link Trigger}s in the + * given group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + */ + public void resumeTriggerGroup(SchedulingContext ctxt, String groupName) { + + synchronized (pausedTriggerGroups) { + String[] names = getTriggerNames(ctxt, groupName); + + for (int i = 0; i < names.length; i++) { + resumeTrigger(ctxt, names[i], groupName); + } + pausedTriggerGroups.remove(groupName); + } + } + + /** + *

+ * Resume (un-pause) the {@link org.quartz.JobDetail} with + * the given name. + *

+ * + *

+ * If any of the Job'sTrigger s missed one + * or more fire-times, then the Trigger's misfire + * instruction will be applied. + *

+ * + */ + public void resumeJob(SchedulingContext ctxt, String jobName, + String groupName) { + + synchronized (pausedTriggerGroups) { + Trigger[] triggers = getTriggersForJob(ctxt, jobName, groupName); + for (int j = 0; j < triggers.length; j++) { + resumeTrigger(ctxt, triggers[j].getName(), triggers[j].getGroup()); + } + } + } + + /** + *

+ * Resume (un-pause) all of the {@link org.quartz.JobDetail}s + * in the given group. + *

+ * + *

+ * If any of the Job s had Trigger s that + * missed one or more fire-times, then the Trigger's + * misfire instruction will be applied. + *

+ * + */ + public void resumeJobGroup(SchedulingContext ctxt, String groupName) { + synchronized (pausedTriggerGroups) { + String[] jobNames = getJobNames(ctxt, groupName); + + for (int i = 0; i < jobNames.length; i++) { + Trigger[] triggers = getTriggersForJob(ctxt, jobNames[i], + groupName); + for (int j = 0; j < triggers.length; j++) { + resumeTrigger(ctxt, triggers[j].getName(), + triggers[j].getGroup()); + } + } + } + } + + /** + *

+ * Pause all triggers - equivalent of calling pauseTriggerGroup(group) + * on every group. + *

+ * + *

+ * When resumeAll() is called (to un-pause), trigger misfire + * instructions WILL be applied. + *

+ * + * @see #resumeAll(SchedulingContext) + * @see #pauseTriggerGroup(SchedulingContext, String) + */ + public void pauseAll(SchedulingContext ctxt) { + + synchronized (pausedTriggerGroups) { + String[] names = getTriggerGroupNames(ctxt); + + for (int i = 0; i < names.length; i++) { + pauseTriggerGroup(ctxt, names[i]); + } + } + } + + /** + *

+ * Resume (un-pause) all triggers - equivalent of calling resumeTriggerGroup(group) + * on every group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseAll(SchedulingContext) + */ + public void resumeAll(SchedulingContext ctxt) { + + synchronized (pausedTriggerGroups) { + String[] names = getTriggerGroupNames(ctxt); + + for (int i = 0; i < names.length; i++) { + resumeTriggerGroup(ctxt, names[i]); + } + } + } + + protected boolean applyMisfire(TriggerWrapper tw) { + + long misfireTime = System.currentTimeMillis(); + if (getMisfireThreshold() > 0) misfireTime -= getMisfireThreshold(); + + java.util.Date tnft = tw.trigger.getNextFireTime(); + if (tnft.getTime() > misfireTime) { return false; } + + Calendar cal = null; + if (tw.trigger.getCalendarName() != null) + cal = retrieveCalendar(null, tw.trigger.getCalendarName()); + + signaler.notifyTriggerListenersMisfired(tw.trigger); + + tw.trigger.updateAfterMisfire(cal); + + if (tw.trigger.getNextFireTime() == null) { + tw.state = TriggerWrapper.STATE_COMPLETE; + synchronized (triggerLock) { + timeTriggers.remove(tw); + } + } else if (tnft.equals(tw.trigger.getNextFireTime())) return false; + + return true; + } + + private static long ftrCtr = System.currentTimeMillis(); + + protected synchronized String getFiredTriggerRecordId() { + return String.valueOf(ftrCtr++); + } + + /** + *

+ * Get a handle to the next trigger to be fired, and mark it as 'reserved' + * by the calling scheduler. + *

+ * + * @see #releaseAcquiredTrigger(SchedulingContext, Trigger) + */ + public Trigger acquireNextTrigger(SchedulingContext ctxt, long noLaterThan) { + TriggerWrapper tw = null; + + synchronized (triggerLock) { + + while (tw == null) { + try { + tw = (TriggerWrapper) timeTriggers.first(); + } catch (java.util.NoSuchElementException nsee) { + return null; + } + + if (tw == null) return null; + + if (tw.trigger.getNextFireTime() == null) { + timeTriggers.remove(tw); + tw = null; + continue; + } + + timeTriggers.remove(tw); + + if (applyMisfire(tw)) { + if (tw.trigger.getNextFireTime() != null) + timeTriggers.add(tw); + tw = null; + continue; + } + + if(tw.trigger.getNextFireTime().getTime() > noLaterThan) { + timeTriggers.add(tw); + return null; + } + + tw.state = TriggerWrapper.STATE_ACQUIRED; + + tw.trigger.setFireInstanceId(getFiredTriggerRecordId()); + Trigger trig = (Trigger) tw.trigger.clone(); + return trig; + } + } + + return null; + } + + /** + *

+ * Inform the JobStore that the scheduler no longer plans to + * fire the given Trigger, that it had previously acquired + * (reserved). + *

+ */ + public void releaseAcquiredTrigger(SchedulingContext ctxt, Trigger trigger) { + synchronized (triggerLock) { + TriggerWrapper tw = (TriggerWrapper) triggersByFQN.get(TriggerWrapper + .getTriggerNameKey(trigger)); + if (tw != null && tw.state == TriggerWrapper.STATE_ACQUIRED) { + tw.state = TriggerWrapper.STATE_WAITING; + timeTriggers.add(tw); + } + } + } + + /** + *

+ * Inform the JobStore that the scheduler is now firing the + * given Trigger (executing its associated Job), + * that it had previously acquired (reserved). + *

+ */ + public TriggerFiredBundle triggerFired(SchedulingContext ctxt, + Trigger trigger) { + + synchronized (triggerLock) { + TriggerWrapper tw = (TriggerWrapper) triggersByFQN.get(TriggerWrapper + .getTriggerNameKey(trigger)); + // was the trigger deleted since being acquired? + if (tw == null || tw.trigger == null) return null; + // was the trigger completed since being acquired? + if (tw.state == TriggerWrapper.STATE_COMPLETE) return null; + // was the trigger paused since being acquired? + if (tw.state == TriggerWrapper.STATE_PAUSED) return null; + // was the trigger blocked since being acquired? + if (tw.state == TriggerWrapper.STATE_BLOCKED) return null; + // was the trigger paused and blocked since being acquired? + if (tw.state == TriggerWrapper.STATE_PAUSED_BLOCKED) return null; + + Calendar cal = null; + if (tw.trigger.getCalendarName() != null) + cal = retrieveCalendar(ctxt, tw.trigger.getCalendarName()); + Date prevFireTime = trigger.getPreviousFireTime(); + // call triggered on our copy, and the scheduler's copy + tw.trigger.triggered(cal); + trigger.triggered(cal); + //tw.state = TriggerWrapper.STATE_EXECUTING; + tw.state = TriggerWrapper.STATE_WAITING; + + TriggerFiredBundle bndle = new TriggerFiredBundle(retrieveJob(ctxt, + trigger.getJobName(), trigger.getJobGroup()), trigger, cal, + false, new Date(), trigger.getPreviousFireTime(), prevFireTime, + trigger.getNextFireTime()); + + JobDetail job = bndle.getJobDetail(); + + if (job.isStateful()) { + ArrayList trigs = getTriggerWrappersForJob(job.getName(), job + .getGroup()); + Iterator itr = trigs.iterator(); + while (itr.hasNext()) { + TriggerWrapper ttw = (TriggerWrapper) itr.next(); + if(ttw.state == TriggerWrapper.STATE_WAITING) + ttw.state = TriggerWrapper.STATE_BLOCKED; + if(ttw.state == TriggerWrapper.STATE_PAUSED) + ttw.state = TriggerWrapper.STATE_PAUSED_BLOCKED; + timeTriggers.remove(ttw); + } + blockedJobs.add(JobWrapper.getJobNameKey(job)); + } else if (tw.trigger.getNextFireTime() != null) { + synchronized (triggerLock) { + timeTriggers.add(tw); + } + } + + return bndle; + } + } + + /** + *

+ * Inform the JobStore that the scheduler has completed the + * firing of the given Trigger (and the execution its + * associated Job), and that the {@link org.quartz.JobDataMap} + * in the given JobDetail should be updated if the Job + * is stateful. + *

+ */ + public void triggeredJobComplete(SchedulingContext ctxt, Trigger trigger, + JobDetail jobDetail, int triggerInstCode) { + + synchronized (triggerLock) { + + String jobKey = JobWrapper.getJobNameKey(jobDetail.getName(), jobDetail + .getGroup()); + JobWrapper jw = (JobWrapper) jobsByFQN.get(jobKey); + TriggerWrapper tw = (TriggerWrapper) triggersByFQN.get(TriggerWrapper + .getTriggerNameKey(trigger)); + + // It's possible that the job is null if: + // 1- it was deleted during execution + // 2- RAMJobStore is being used only for volatile jobs / triggers + // from the JDBC job store + if (jw != null) { + JobDetail jd = jw.jobDetail; + + if (jobDetail.isStateful()) { + JobDataMap newData = jobDetail.getJobDataMap(); + if (newData != null) newData.clearDirtyFlag(); + jd.setJobDataMap(newData); + blockedJobs.remove(JobWrapper.getJobNameKey(jd)); + ArrayList trigs = getTriggerWrappersForJob(jd.getName(), jd + .getGroup()); + Iterator itr = trigs.iterator(); + while (itr.hasNext()) { + TriggerWrapper ttw = (TriggerWrapper) itr.next(); + if (ttw.state == TriggerWrapper.STATE_BLOCKED) { + ttw.state = TriggerWrapper.STATE_WAITING; + timeTriggers.add(ttw); + } + if (ttw.state == TriggerWrapper.STATE_PAUSED_BLOCKED) { + ttw.state = TriggerWrapper.STATE_PAUSED; + } + } + } + } + else { // even if it was deleted, there may be cleanup to do + blockedJobs.remove(JobWrapper.getJobNameKey(jobDetail)); + } + + // check for trigger deleted during execution... + if (tw != null) { + if (triggerInstCode == Trigger.INSTRUCTION_DELETE_TRIGGER) { + + if(trigger.getNextFireTime() == null) { + // double check for possible reschedule within job + // execution, which would cancel the need to delete... + if(tw.getTrigger().getNextFireTime() == null) + removeTrigger(ctxt, trigger.getName(), trigger.getGroup()); + } + else + removeTrigger(ctxt, trigger.getName(), trigger.getGroup()); + } + else if (triggerInstCode == Trigger.INSTRUCTION_SET_TRIGGER_COMPLETE) { + tw.state = TriggerWrapper.STATE_COMPLETE; + timeTriggers.remove(tw); + } + else if(triggerInstCode == Trigger.INSTRUCTION_SET_TRIGGER_ERROR) { + getLog().info("Trigger " + trigger.getFullName() + " set to ERROR state."); + tw.state = TriggerWrapper.STATE_ERROR; + } + else if (triggerInstCode == Trigger.INSTRUCTION_SET_ALL_JOB_TRIGGERS_ERROR) { + getLog().info("All triggers of Job " + + trigger.getFullJobName() + " set to ERROR state."); + setAllTriggersOfJobToState( + trigger.getJobName(), + trigger.getJobGroup(), + TriggerWrapper.STATE_ERROR); + } + else if (triggerInstCode == Trigger.INSTRUCTION_SET_ALL_JOB_TRIGGERS_COMPLETE) { + setAllTriggersOfJobToState( + trigger.getJobName(), + trigger.getJobGroup(), + TriggerWrapper.STATE_COMPLETE); + } + } + } + } + + protected void setAllTriggersOfJobToState(String jobName, String jobGroup, int state) { + ArrayList tws = getTriggerWrappersForJob(jobName, jobGroup); + Iterator itr = tws.iterator(); + while (itr.hasNext()) { + TriggerWrapper tw = (TriggerWrapper) itr.next(); + tw.state = state; + if(state != TriggerWrapper.STATE_WAITING) + timeTriggers.remove(tw); + } + } + + protected String peekTriggers() { + + StringBuffer str = new StringBuffer(); + TriggerWrapper tw = null; + + synchronized (triggerLock) { + Iterator itr = triggersByFQN.keySet().iterator(); + while (itr.hasNext()) { + tw = (TriggerWrapper) triggersByFQN.get(itr.next()); + str.append(tw.trigger.getName()); + str.append("/"); + } + } + str.append(" | "); + + synchronized (triggerLock) { + Iterator itr = timeTriggers.iterator(); + while (itr.hasNext()) { + tw = (TriggerWrapper) itr.next(); + str.append(tw.trigger.getName()); + str.append("->"); + } + } + + return str.toString(); + } + + /** + * @see org.quartz.spi.JobStore#getPausedTriggerGroups(org.quartz.core.SchedulingContext) + */ + public Set getPausedTriggerGroups(SchedulingContext ctxt) throws JobPersistenceException { + HashSet set = new HashSet(); + + set.addAll(pausedTriggerGroups); + + return set; + } + + +} + +/******************************************************************************* + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * + * Helper Classes. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + */ + +class TriggerComparator implements Comparator { + + public int compare(Object obj1, Object obj2) { + TriggerWrapper trig1 = (TriggerWrapper) obj1; + TriggerWrapper trig2 = (TriggerWrapper) obj2; + + int comp = trig1.trigger.compareTo(trig2.trigger); + + if (comp == 0) + return trig1.trigger.getFullName().compareTo(trig2.trigger.getFullName()); + + return comp; + } + + public boolean equals(Object obj) { + if (obj instanceof TriggerComparator) return true; + + return false; + } +} + +class JobWrapper { + + public String key; + + public JobDetail jobDetail; + + JobWrapper(JobDetail jobDetail) { + this.jobDetail = jobDetail; + key = getJobNameKey(jobDetail); + } + + JobWrapper(JobDetail jobDetail, String key) { + this.jobDetail = jobDetail; + this.key = key; + } + + static String getJobNameKey(JobDetail jobDetail) { + return jobDetail.getGroup() + "_$x$x$_" + jobDetail.getName(); + } + + static String getJobNameKey(String jobName, String groupName) { + return groupName + "_$x$x$_" + jobName; + } + + public boolean equals(Object obj) { + if (obj instanceof JobWrapper) { + JobWrapper jw = (JobWrapper) obj; + if (jw.key.equals(this.key)) return true; + } + + return false; + } + + public int hashCode() { + return key.hashCode(); + } + + +} + +class TriggerWrapper { + + public String key; + + public String jobKey; + + public Trigger trigger; + + public int state = STATE_WAITING; + + public final static int STATE_WAITING = 0; + + public final static int STATE_ACQUIRED = 1; + + public final static int STATE_EXECUTING = 2; + + public final static int STATE_COMPLETE = 3; + + public final static int STATE_PAUSED = 4; + + public final static int STATE_BLOCKED = 5; + + public final static int STATE_PAUSED_BLOCKED = 6; + + public final static int STATE_ERROR = 7; + + TriggerWrapper(Trigger trigger) { + this.trigger = trigger; + key = getTriggerNameKey(trigger); + this.jobKey = JobWrapper.getJobNameKey(trigger.getJobName(), trigger + .getJobGroup()); + } + + TriggerWrapper(Trigger trigger, String key) { + this.trigger = trigger; + this.key = key; + this.jobKey = JobWrapper.getJobNameKey(trigger.getJobName(), trigger + .getJobGroup()); + } + + static String getTriggerNameKey(Trigger trigger) { + return trigger.getGroup() + "_$x$x$_" + trigger.getName(); + } + + static String getTriggerNameKey(String triggerName, String groupName) { + return groupName + "_$x$x$_" + triggerName; + } + + public boolean equals(Object obj) { + if (obj instanceof TriggerWrapper) { + TriggerWrapper tw = (TriggerWrapper) obj; + if (tw.key.equals(this.key)) return true; + } + + return false; + } + + public int hashCode() { + return key.hashCode(); + } + + + public Trigger getTrigger() { + return this.trigger; + } + +} Index: 3rdParty_sources/quartz/org/quartz/simpl/SimpleClassLoadHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/SimpleClassLoadHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/SimpleClassLoadHelper.java 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,106 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.simpl; + +import org.quartz.spi.ClassLoadHelper; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Method; +import java.net.URL; +import java.io.InputStream; + +/** + * A ClassLoadHelper that simply calls Class.forName(..). + * + * @see org.quartz.spi.ClassLoadHelper + * @see org.quartz.simpl.ThreadContextClassLoadHelper + * @see org.quartz.simpl.CascadingClassLoadHelper + * @see org.quartz.simpl.LoadingLoaderClassLoadHelper + * + * @author jhouse + */ +public class SimpleClassLoadHelper implements ClassLoadHelper { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Called to give the ClassLoadHelper a chance to initialize itself, + * including the oportunity to "steal" the class loader off of the calling + * thread, which is the thread that is initializing Quartz. + */ + public void initialize() { + } + + /** + * Return the class with the given name. + */ + public Class loadClass(String name) throws ClassNotFoundException { + return Class.forName(name); + } + + /** + * Finds a resource with a given name. This method returns null if no + * resource with this name is found. + * @param name name of the desired resource + * @return a java.net.URL object + */ + public URL getResource(String name) { + return getClassLoader().getResource(name); + } + + /** + * Finds a resource with a given name. This method returns null if no + * resource with this name is found. + * @param name name of the desired resource + * @return a java.io.InputStream object + */ + public InputStream getResourceAsStream(String name) { + return getClassLoader().getResourceAsStream(name); + } + + private ClassLoader getClassLoader() { + // To follow the same behavior of Class.forName(...) I had to play + // dirty (Supported by Sun, IBM & BEA JVMs) + // ToDo - Test it more. + try { + // Get a reference to this class' class-loader + ClassLoader cl = this.getClass().getClassLoader(); + // Create a method instance represnting the protected + // getCallerClassLoader method of class ClassLoader + Method mthd = ClassLoader.class.getDeclaredMethod( + "getCallerClassLoader", new Class[0]); + // Make the method accessible. + AccessibleObject.setAccessible(new AccessibleObject[] {mthd}, true); + // Try to get the caller's class-loader + return (ClassLoader)mthd.invoke(cl, new Object[0]); + } catch (Exception all) { + // Use this class' class-loader + return this.getClass().getClassLoader(); + } + } + +} Index: 3rdParty_sources/quartz/org/quartz/simpl/SimpleInstanceIdGenerator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/SimpleInstanceIdGenerator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/SimpleInstanceIdGenerator.java 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ +package org.quartz.simpl; + +import java.net.InetAddress; + +import org.quartz.SchedulerException; +import org.quartz.spi.InstanceIdGenerator; + +/** + * The default InstanceIdGenerator used by Quartz when instance id is to be + * automatically generated. Instance id is of the form HOSTNAME + CURRENT_TIME. + * + * @see InstanceIdGenerator + * @see HostnameInstanceIdGenerator + */ +public class SimpleInstanceIdGenerator implements InstanceIdGenerator +{ + public String generateInstanceId() throws SchedulerException { + try { + return InetAddress.getLocalHost().getHostName() + System.currentTimeMillis(); + } + catch (Exception e) { + throw new SchedulerException("Couldn't get host name!", e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/simpl/SimpleJobFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/SimpleJobFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/SimpleJobFactory.java 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ +package org.quartz.simpl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.Job; +import org.quartz.JobDetail; +import org.quartz.SchedulerException; +import org.quartz.spi.JobFactory; +import org.quartz.spi.TriggerFiredBundle; + +/** + * The default JobFactory used by Quartz - simply calls + * newInstance() on the job class. + * + * @see JobFactory + * @see PropertySettingJobFactory + * + * @author jhouse + */ +public class SimpleJobFactory implements JobFactory { + + private Log log = LogFactory.getLog(SimpleJobFactory.class); + + public Job newJob(TriggerFiredBundle bundle) throws SchedulerException { + + JobDetail jobDetail = bundle.getJobDetail(); + Class jobClass = jobDetail.getJobClass(); + try { + if(log.isDebugEnabled()) + log.debug( + "Producing instance of Job '" + jobDetail.getFullName() + + "', class=" + jobClass.getName()); + + return (Job) jobClass.newInstance(); + } catch (Exception e) { + SchedulerException se = new SchedulerException( + "Problem instantiating class '" + + jobDetail.getJobClass().getName() + "'", e); + throw se; + } + } +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/simpl/SimpleThreadPool.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/SimpleThreadPool.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/SimpleThreadPool.java 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,553 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.simpl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.SchedulerConfigException; +import org.quartz.spi.ThreadPool; + +/** + *

+ * This is class is a simple implementation of a thread pool, based on the + * {@link org.quartz.spi.ThreadPool} interface. + *

+ * + *

+ * Runnable objects are sent to the pool with the {@link #runInThread(Runnable)} + * method, which blocks until a Thread becomes available. + *

+ * + *

+ * The pool has a fixed number of Threads, and does not grow or + * shrink based on demand. + *

+ * + * @author James House + * @author Juergen Donnerstag + */ +public class SimpleThreadPool implements ThreadPool { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private int count = -1; + + private int prio = Thread.NORM_PRIORITY; + + private boolean isShutdown = false; + + private boolean inheritLoader = false; + + private boolean inheritGroup = true; + + private boolean makeThreadsDaemons = false; + + private ThreadGroup threadGroup; + + private Runnable nextRunnable; + + private Object nextRunnableLock = new Object(); + + private WorkerThread[] workers; + + private String threadNamePrefix = "SimpleThreadPoolWorker"; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a new (unconfigured) SimpleThreadPool. + *

+ * + * @see #setThreadCount(int) + * @see #setThreadPriority(int) + */ + public SimpleThreadPool() { + } + + /** + *

+ * Create a new SimpleThreadPool with the specified number + * of Thread s that have the given priority. + *

+ * + * @param threadCount + * the number of worker Threads in the pool, must + * be > 0. + * @param threadPriority + * the thread priority for the worker threads. + * + * @see java.lang.Thread + */ + public SimpleThreadPool(int threadCount, int threadPriority) { + setThreadCount(threadCount); + setThreadPriority(threadPriority); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public Log getLog() { + return LogFactory.getLog(SimpleThreadPool.class); + } + + public int getPoolSize() { + return getThreadCount(); + } + + /** + *

+ * Set the number of worker threads in the pool - has no effect after + * initialize() has been called. + *

+ */ + public void setThreadCount(int count) { + this.count = count; + } + + /** + *

+ * Get the number of worker threads in the pool. + *

+ */ + public int getThreadCount() { + return count; + } + + /** + *

+ * Set the thread priority of worker threads in the pool - has no effect + * after initialize() has been called. + *

+ */ + public void setThreadPriority(int prio) { + this.prio = prio; + } + + /** + *

+ * Get the thread priority of worker threads in the pool. + *

+ */ + public int getThreadPriority() { + return prio; + } + + public void setThreadNamePrefix(String prfx) { + this.threadNamePrefix = prfx; + } + + public String getThreadNamePrefix() { + return threadNamePrefix; + } + + /** + * @return Returns the + * threadsInheritContextClassLoaderOfInitializingThread. + */ + public boolean isThreadsInheritContextClassLoaderOfInitializingThread() { + return inheritLoader; + } + + /** + * @param inheritLoader + * The threadsInheritContextClassLoaderOfInitializingThread to + * set. + */ + public void setThreadsInheritContextClassLoaderOfInitializingThread( + boolean inheritLoader) { + this.inheritLoader = inheritLoader; + } + + public boolean isThreadsInheritGroupOfInitializingThread() { + return inheritGroup; + } + + public void setThreadsInheritGroupOfInitializingThread( + boolean inheritGroup) { + this.inheritGroup = inheritGroup; + } + + + /** + * @return Returns the value of makeThreadsDaemons. + */ + public boolean isMakeThreadsDaemons() { + return makeThreadsDaemons; + } + + /** + * @param makeThreadsDaemons + * The value of makeThreadsDaemons to set. + */ + public void setMakeThreadsDaemons(boolean makeThreadsDaemons) { + this.makeThreadsDaemons = makeThreadsDaemons; + } + + public void initialize() throws SchedulerConfigException { + + if (count <= 0) + throw new SchedulerConfigException( + "Thread count must be > 0"); + if (prio <= 0 || prio > 9) + throw new SchedulerConfigException( + "Thread priority must be > 0 and <= 9"); + + if(isThreadsInheritGroupOfInitializingThread()) + threadGroup = Thread.currentThread().getThreadGroup(); + else { + // follow the threadGroup tree to the root thread group. + threadGroup = Thread.currentThread().getThreadGroup(); + ThreadGroup parent = threadGroup; + while ( !parent.getName().equals("main") ) + { + threadGroup = parent; + parent = threadGroup.getParent(); + } + threadGroup = new ThreadGroup(parent, "SimpleThreadPool"); + } + + + if (isThreadsInheritContextClassLoaderOfInitializingThread()) + getLog().info( + "Job execution threads will use class loader of thread: " + + Thread.currentThread().getName()); + + // create the worker threads and start them + workers = createWorkerThreads(count); + for (int i = 0; i < count; ++i) { + if (isThreadsInheritContextClassLoaderOfInitializingThread()) { + workers[i].setContextClassLoader(Thread.currentThread() + .getContextClassLoader()); + } + } + } + + protected WorkerThread[] createWorkerThreads(int count) + { + workers = new WorkerThread[count]; + for (int i = 0; i < count; ++i) { + workers[i] = new WorkerThread(this, threadGroup, + getThreadNamePrefix() + "-" + i, + getThreadPriority(), + isMakeThreadsDaemons()); + } + + return workers; + } + + /** + *

+ * Terminate any worker threads in this thread group. + *

+ * + *

+ * Jobs currently in progress will complete. + *

+ */ + public void shutdown() { + shutdown(true); + } + + /** + *

+ * Terminate any worker threads in this thread group. + *

+ * + *

+ * Jobs currently in progress will complete. + *

+ */ + public void shutdown(boolean waitForJobsToComplete) { + isShutdown = true; + + // signal each worker thread to shut down + for (int i = 0; i < workers.length; i++) { + if (workers[i] != null) workers[i].shutdown(); + } + + // Give waiting (wait(1000)) worker threads a chance to shut down. + // Active worker threads will shut down after finishing their + // current job. + synchronized (nextRunnableLock) { + nextRunnableLock.notifyAll(); + } + + if (waitForJobsToComplete == true) { + // Wait until all worker threads are shut down + int alive = workers.length; + while (alive > 0) { + alive = 0; + for (int i = 0; i < workers.length; i++) { + if (workers[i].isAlive()) { + try { + //if (logger.isDebugEnabled()) + getLog().debug( + "Waiting for thread no. " + i + + " to shut down"); + + // note: with waiting infinite - join(0) - the + // application + // may appear to 'hang'. Waiting for a finite time + // however + // requires an additional loop (alive). + alive++; + workers[i].join(200); + } catch (InterruptedException ex) { + } + } + } + } + + //if (logger.isDebugEnabled()) { + int activeCount = threadGroup.activeCount(); + if (activeCount > 0) + getLog() + .info( + "There are still " + + activeCount + + " worker threads active." + + " See javadoc runInThread(Runnable) for a possible explanation"); + + getLog().debug("shutdown complete"); + //} + } + } + + /** + *

+ * Run the given Runnable object in the next available + * Thread. If while waiting the thread pool is asked to + * shut down, the Runnable is executed immediately within a new additional + * thread. + *

+ * + * @param runnable + * the Runnable to be added. + */ + public boolean runInThread(Runnable runnable) { + if (runnable == null) return false; + + if (isShutdown) { + try { + getLog() + .info( + "SimpleThreadPool.runInThread(): thread pool has been shutdown. Runnable will not be executed"); + } catch(Exception e) { + // ignore to help with a tomcat glitch + } + + return false; + } + + synchronized (nextRunnableLock) { + + // Wait until a worker thread has taken the previous Runnable + // or until the thread pool is asked to shutdown. + while ((nextRunnable != null) && !isShutdown) { + try { + nextRunnableLock.wait(1000); + } catch (InterruptedException ignore) { + } + } + + // During normal operation, not shutdown, set the nextRunnable + // and notify the worker threads waiting (getNextRunnable()). + if (!isShutdown) { + nextRunnable = runnable; + nextRunnableLock.notifyAll(); + } + } + + // If the thread pool is going down, execute the Runnable + // within a new additional worker thread (no thread from the pool). + // note: the synchronized section should be as short (time) as + // possible. Starting a new thread is not a quick action. + if (isShutdown) { + new WorkerThread(this, threadGroup, + "WorkerThread-LastJob", prio, false, runnable); + } + + return true; + } + + /** + *

+ * Dequeue the next pending Runnable. + *

+ * + *

+ * getNextRunnable() should return null if within a specific time no new + * Runnable is available. This gives the worker thread the chance to check + * its shutdown flag. In case the worker thread is asked to shut down it + * will notify on nextRunnableLock, hence interrupt the wait state. That + * is, the time used for waiting need not be short. + *

+ */ + private Runnable getNextRunnable() throws InterruptedException { + Runnable toRun = null; + + // Wait for new Runnable (see runInThread()) and notify runInThread() + // in case the next Runnable is already waiting. + synchronized (nextRunnableLock) { + if (nextRunnable == null) nextRunnableLock.wait(1000); + + if (nextRunnable != null) { + toRun = nextRunnable; + nextRunnable = null; + nextRunnableLock.notifyAll(); + } + } + + return toRun; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * WorkerThread Class. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * A Worker loops, waiting to execute tasks. + *

+ */ + class WorkerThread extends Thread { + + // A flag that signals the WorkerThread to terminate. + private boolean run = true; + + private SimpleThreadPool tp; + + private Runnable runnable = null; + + /** + *

+ * Create a worker thread and start it. Waiting for the next Runnable, + * executing it, and waiting for the next Runnable, until the shutdown + * flag is set. + *

+ */ + WorkerThread(SimpleThreadPool tp, ThreadGroup threadGroup, String name, + int prio, boolean isDaemon) { + + this(tp, threadGroup, name, prio, isDaemon, null); + } + + /** + *

+ * Create a worker thread, start it, execute the runnable and terminate + * the thread (one time execution). + *

+ */ + WorkerThread(SimpleThreadPool tp, ThreadGroup threadGroup, String name, + int prio, boolean isDaemon, Runnable runnable) { + + super(threadGroup, name); + this.tp = tp; + this.runnable = runnable; + setPriority(prio); + setDaemon(isDaemon); + start(); + } + + /** + *

+ * Signal the thread that it should terminate. + *

+ */ + void shutdown() { + run = false; + + // @todo I'm not really sure if we should interrupt the thread. + // Javadoc mentions that it interrupts blocked I/O operations as + // well. Hence the job will most likely fail. I think we should + // shut the work thread gracefully, by letting the job finish + // uninterrupted. See SimpleThreadPool.shutdown() + //interrupt(); + } + + /** + *

+ * Loop, executing targets as they are received. + *

+ */ + public void run() { + boolean runOnce = (runnable != null); + + while (run) { + try { + if (runnable == null) runnable = tp.getNextRunnable(); + + if (runnable != null) runnable.run(); + } catch (InterruptedException unblock) { + // do nothing (loop will terminate if shutdown() was called + try { + getLog().error("worker threat got 'interrupt'ed.", unblock); + } catch(Exception e) { + // ignore to help with a tomcat glitch + } + } catch (Exception exceptionInRunnable) { + try { + getLog().error("Error while executing the Runnable: ", + exceptionInRunnable); + } catch(Exception e) { + // ignore to help with a tomcat glitch + } + } finally { + if (runOnce) run = false; + + runnable = null; + + // repair the thread in case the runnable mucked it up... + setPriority(tp.getThreadPriority()); + } + } + + //if (log.isDebugEnabled()) + try { + getLog().debug("WorkerThread is shutting down"); + } catch(Exception e) { + // ignore to help with a tomcat glitch + } +} + } +} Index: 3rdParty_sources/quartz/org/quartz/simpl/SimpleTimeBroker.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/SimpleTimeBroker.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/SimpleTimeBroker.java 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.simpl; + +import java.util.Date; + +import org.quartz.SchedulerConfigException; +import org.quartz.spi.TimeBroker; + +/** + *

+ * The interface to be implemented by classes that want to provide a mechanism + * by which the {@link org.quartz.core.QuartzScheduler} can + * reliably determine the current time. + *

+ * + *

+ * In general, the default implementation of this interface ({@link org.quartz.simpl.SimpleTimeBroker}- + * which simply uses System.getCurrentTimeMillis() )is + * sufficient. However situations may exist where this default scheme is + * lacking in its robustsness - especially when Quartz is used in a clustered + * configuration. For example, if one or more of the machines in the cluster + * has a system time that varies by more than a few seconds from the clocks on + * the other systems in the cluster, scheduling confusion will result. + *

+ * + * @see org.quartz.core.QuartzScheduler + * + * @author James House + */ +public class SimpleTimeBroker implements TimeBroker { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Get the current time, simply using new Date(). + *

+ */ + public Date getCurrentTime() { + return new Date(); + } + + public void initialize() throws SchedulerConfigException { + // do nothing... + } + + public void shutdown() { + // do nothing... + } + +} Index: 3rdParty_sources/quartz/org/quartz/simpl/ThreadContextClassLoadHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/ThreadContextClassLoadHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/ThreadContextClassLoadHelper.java 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.simpl; + +import org.quartz.spi.ClassLoadHelper; + +import java.net.URL; +import java.io.InputStream; + +/** + * A ClassLoadHelper that uses either the current thread's + * context class loader (Thread.currentThread().getContextClassLoader().loadClass( .. )). + * + * @see org.quartz.spi.ClassLoadHelper + * @see org.quartz.simpl.InitThreadContextClassLoadHelper + * @see org.quartz.simpl.SimpleClassLoadHelper + * @see org.quartz.simpl.CascadingClassLoadHelper + * @see org.quartz.simpl.LoadingLoaderClassLoadHelper + * + * @author jhouse + */ +public class ThreadContextClassLoadHelper implements ClassLoadHelper { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Called to give the ClassLoadHelper a chance to initialize itself, + * including the oportunity to "steal" the class loader off of the calling + * thread, which is the thread that is initializing Quartz. + */ + public void initialize() { + } + + /** + * Return the class with the given name. + */ + public Class loadClass(String name) throws ClassNotFoundException { + return getClassLoader().loadClass(name); + } + + /** + * Finds a resource with a given name. This method returns null if no + * resource with this name is found. + * @param name name of the desired resource + * @return a java.net.URL object + */ + public URL getResource(String name) { + return getClassLoader().getResource(name); + } + + /** + * Finds a resource with a given name. This method returns null if no + * resource with this name is found. + * @param name name of the desired resource + * @return a java.io.InputStream object + */ + public InputStream getResourceAsStream(String name) { + return getClassLoader().getResourceAsStream(name); + } + + + private ClassLoader getClassLoader() { + return Thread.currentThread().getContextClassLoader(); + } +} Index: 3rdParty_sources/quartz/org/quartz/simpl/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/simpl/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/simpl/package.html 17 Aug 2012 15:10:16 -0000 1.1 @@ -0,0 +1,17 @@ + + +Package org.quartz.simpl + + +

Contains simple / light-weight implementations (with no dependencies on +external libraries) of interfaces required by the +org.quartz.core.QuartzScheduler.

+ +
+
+
+See the Quartz project + at Open Symphony for more information. + + + Index: 3rdParty_sources/quartz/org/quartz/spi/ClassLoadHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/spi/ClassLoadHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/spi/ClassLoadHelper.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.spi; + +import java.net.URL; +import java.io.InputStream; + +/** + * An interface for classes wishing to provide the service of loading classes + * and resources within the scheduler... + * + * @author jhouse + */ +public interface ClassLoadHelper { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Called to give the ClassLoadHelper a chance to initialize itself, + * including the oportunity to "steal" the class loader off of the calling + * thread, which is the thread that is initializing Quartz. + */ + public void initialize(); + + /** + * Return the class with the given name. + */ + public Class loadClass(String name) throws ClassNotFoundException; + + /** + * Finds a resource with a given name. This method returns null if no + * resource with this name is found. + * @param name name of the desired resource + * @return a java.net.URL object + */ + public URL getResource(String name); + + /** + * Finds a resource with a given name. This method returns null if no + * resource with this name is found. + * @param name name of the desired resource + * @return a java.io.InputStream object + */ + public InputStream getResourceAsStream(String name); +} Index: 3rdParty_sources/quartz/org/quartz/spi/InstanceIdGenerator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/spi/InstanceIdGenerator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/spi/InstanceIdGenerator.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ +package org.quartz.spi; + +import org.quartz.SchedulerException; + +/** + *

+ * An InstanceIdGenerator is responsible for generating the clusterwide unique + * instance id for a Scheduler nodde. + *

+ * + *

+ * This interface may be of use to those wishing to have specific control over + * the mechanism by which the Scheduler instances in their + * application are named. + *

+ * + * @see org.quartz.simpl.SimpleInstanceIdGenerator + */ +public interface InstanceIdGenerator +{ + /** + * Generate the instance id for a Scheduler + * + * @return The clusterwide unique instance id. + */ + String generateInstanceId() throws SchedulerException; +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/spi/JobFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/spi/JobFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/spi/JobFactory.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ +package org.quartz.spi; + +import org.quartz.Job; +import org.quartz.SchedulerException; + +/** + *

+ * A JobFactory is responsible for producing instances of Job + * classes. + *

+ * + *

+ * This interface may be of use to those wishing to have their application + * produce Job instances via some special mechanism, such as to + * give the opertunity for dependency injection. + *

+ * + * @see org.quartz.Scheduler#setJobFactory(JobFactory) + * @see org.quartz.simpl.SimpleJobFactory + * @see org.quartz.simpl.PropertySettingJobFactory + * + * @author James House + */ +public interface JobFactory { + + /** + * Called by the scheduler at the time of the trigger firing, in order to + * produce a Job instance on which to call execute. + * + *

+ * It should be extremely rare for this method to throw an exception - + * basically only the the case where there is no way at all to instantiate + * and prepare the Job for execution. When the exception is thrown, the + * Scheduler will move all triggers associated with the Job into the + * Trigger.STATE_ERROR state, which will require human + * intervention (e.g. an application restart after fixing whatever + * configuration problem led to the issue wih instantiating the Job. + *

+ * + * @param bundle + * The TriggerFiredBundle from which the JobDetail + * and other info relating to the trigger firing can be obtained. + * @throws SchedulerException if there is a problem instantiating the Job. + * @return the newly instantiated Job + */ + public Job newJob(TriggerFiredBundle bundle) throws SchedulerException; + +} Index: 3rdParty_sources/quartz/org/quartz/spi/JobStore.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/spi/JobStore.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/spi/JobStore.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,662 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.spi; + +import java.util.Set; + +import org.quartz.Calendar; +import org.quartz.JobDetail; +import org.quartz.JobPersistenceException; +import org.quartz.ObjectAlreadyExistsException; +import org.quartz.SchedulerConfigException; +import org.quartz.SchedulerException; +import org.quartz.Trigger; +import org.quartz.core.SchedulingContext; + +/** + *

+ * The interface to be implemented by classes that want to provide a {@link org.quartz.Job} + * and {@link org.quartz.Trigger} storage mechanism for the + * {@link org.quartz.core.QuartzScheduler}'s use. + *

+ * + *

+ * Storage of Job s and Trigger s should be keyed + * on the combination of their name and group for uniqueness. + *

+ * + * @see org.quartz.core.QuartzScheduler + * @see org.quartz.Trigger + * @see org.quartz.Job + * @see org.quartz.JobDetail + * @see org.quartz.JobDataMap + * @see org.quartz.Calendar + * + * @author James House + */ +public interface JobStore { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Called by the QuartzScheduler before the JobStore is + * used, in order to give the it a chance to initialize. + *

+ */ + public void initialize(ClassLoadHelper loadHelper, + SchedulerSignaler signaler) throws SchedulerConfigException; + + /** + *

+ * Called by the QuartzScheduler to inform the JobStore that + * the scheduler has started. + *

+ */ + public void schedulerStarted() throws SchedulerException ; + + /** + *

+ * Called by the QuartzScheduler to inform the JobStore that + * it should free up all of it's resources because the scheduler is + * shutting down. + *

+ */ + public void shutdown(); + + public boolean supportsPersistence(); + + ///////////////////////////////////////////////////////////////////////////// + // + // Job & Trigger Storage methods + // + ///////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Store the given {@link org.quartz.JobDetail} and {@link org.quartz.Trigger}. + *

+ * + * @param newJob + * The JobDetail to be stored. + * @param newTrigger + * The Trigger to be stored. + * @throws ObjectAlreadyExistsException + * if a Job with the same name/group already + * exists. + */ + public void storeJobAndTrigger(SchedulingContext ctxt, JobDetail newJob, + Trigger newTrigger) throws ObjectAlreadyExistsException, + JobPersistenceException; + + /** + *

+ * Store the given {@link org.quartz.JobDetail}. + *

+ * + * @param newJob + * The JobDetail to be stored. + * @param replaceExisting + * If true, any Job existing in the + * JobStore with the same name & group should be + * over-written. + * @throws ObjectAlreadyExistsException + * if a Job with the same name/group already + * exists, and replaceExisting is set to false. + */ + public void storeJob(SchedulingContext ctxt, JobDetail newJob, + boolean replaceExisting) throws ObjectAlreadyExistsException, + JobPersistenceException; + + /** + *

+ * Remove (delete) the {@link org.quartz.Job} with the given + * name, and any {@link org.quartz.Trigger} s that reference + * it. + *

+ * + *

+ * If removal of the Job results in an empty group, the + * group should be removed from the JobStore's list of + * known group names. + *

+ * + * @param jobName + * The name of the Job to be removed. + * @param groupName + * The group name of the Job to be removed. + * @return true if a Job with the given name & + * group was found and removed from the store. + */ + public boolean removeJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException; + + /** + *

+ * Retrieve the {@link org.quartz.JobDetail} for the given + * {@link org.quartz.Job}. + *

+ * + * @param jobName + * The name of the Job to be retrieved. + * @param groupName + * The group name of the Job to be retrieved. + * @return The desired Job, or null if there is no match. + */ + public JobDetail retrieveJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException; + + /** + *

+ * Store the given {@link org.quartz.Trigger}. + *

+ * + * @param newTrigger + * The Trigger to be stored. + * @param replaceExisting + * If true, any Trigger existing in + * the JobStore with the same name & group should + * be over-written. + * @throws ObjectAlreadyExistsException + * if a Trigger with the same name/group already + * exists, and replaceExisting is set to false. + * + * @see #pauseTriggerGroup(SchedulingContext, String) + */ + public void storeTrigger(SchedulingContext ctxt, Trigger newTrigger, + boolean replaceExisting) throws ObjectAlreadyExistsException, + JobPersistenceException; + + /** + *

+ * Remove (delete) the {@link org.quartz.Trigger} with the + * given name. + *

+ * + *

+ * If removal of the Trigger results in an empty group, the + * group should be removed from the JobStore's list of + * known group names. + *

+ * + *

+ * If removal of the Trigger results in an 'orphaned' Job + * that is not 'durable', then the Job should be deleted + * also. + *

+ * + * @param triggerName + * The name of the Trigger to be removed. + * @param groupName + * The group name of the Trigger to be removed. + * @return true if a Trigger with the given + * name & group was found and removed from the store. + */ + public boolean removeTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException; + + /** + *

+ * Remove (delete) the {@link org.quartz.Trigger} with the + * given name, and store the new given one - which must be associated + * with the same job. + *

+ * + * @param triggerName + * The name of the Trigger to be removed. + * @param groupName + * The group name of the Trigger to be removed. + * @param newTrigger + * The new Trigger to be stored. + * @return true if a Trigger with the given + * name & group was found and removed from the store. + */ + public boolean replaceTrigger(SchedulingContext ctxt, String triggerName, + String groupName, Trigger newTrigger) throws JobPersistenceException; + + + /** + *

+ * Retrieve the given {@link org.quartz.Trigger}. + *

+ * + * @param triggerName + * The name of the Trigger to be retrieved. + * @param groupName + * The group name of the Trigger to be retrieved. + * @return The desired Trigger, or null if there is no + * match. + */ + public Trigger retrieveTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException; + + /** + *

+ * Store the given {@link org.quartz.Calendar}. + *

+ * + * @param calendar + * The Calendar to be stored. + * @param replaceExisting + * If true, any Calendar existing + * in the JobStore with the same name & group + * should be over-written. + * @param updateTriggers + * If true, any Triggers existing + * in the JobStore that reference an existing + * Calendar with the same name with have their next fire time + * re-computed with the new Calendar. + * @throws ObjectAlreadyExistsException + * if a Calendar with the same name already + * exists, and replaceExisting is set to false. + */ + public void storeCalendar(SchedulingContext ctxt, String name, + Calendar calendar, boolean replaceExisting, boolean updateTriggers) + throws ObjectAlreadyExistsException, JobPersistenceException; + + /** + *

+ * Remove (delete) the {@link org.quartz.Calendar} with the + * given name. + *

+ * + *

+ * If removal of the Calendar would result in + * s pointing to non-existent calendars, then a + * JobPersistenceException will be thrown.

+ * * + * @param calName The name of the Calendar to be removed. + * @return true if a Calendar with the given name + * was found and removed from the store. + */ + public boolean removeCalendar(SchedulingContext ctxt, String calName) + throws JobPersistenceException; + + /** + *

+ * Retrieve the given {@link org.quartz.Trigger}. + *

+ * + * @param calName + * The name of the Calendar to be retrieved. + * @return The desired Calendar, or null if there is no + * match. + */ + public Calendar retrieveCalendar(SchedulingContext ctxt, String calName) + throws JobPersistenceException; + + ///////////////////////////////////////////////////////////////////////////// + // + // Informational methods + // + ///////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Get the number of {@link org.quartz.Job} s that are + * stored in the JobsStore. + *

+ */ + public int getNumberOfJobs(SchedulingContext ctxt) + throws JobPersistenceException; + + /** + *

+ * Get the number of {@link org.quartz.Trigger} s that are + * stored in the JobsStore. + *

+ */ + public int getNumberOfTriggers(SchedulingContext ctxt) + throws JobPersistenceException; + + /** + *

+ * Get the number of {@link org.quartz.Calendar} s that are + * stored in the JobsStore. + *

+ */ + public int getNumberOfCalendars(SchedulingContext ctxt) + throws JobPersistenceException; + + /** + *

+ * Get the names of all of the {@link org.quartz.Job} s that + * have the given group name. + *

+ * + *

+ * If there are no jobs in the given group name, the result should be a + * zero-length array (not null). + *

+ */ + public String[] getJobNames(SchedulingContext ctxt, String groupName) + throws JobPersistenceException; + + /** + *

+ * Get the names of all of the {@link org.quartz.Trigger} s + * that have the given group name. + *

+ * + *

+ * If there are no triggers in the given group name, the result should be a + * zero-length array (not null). + *

+ */ + public String[] getTriggerNames(SchedulingContext ctxt, String groupName) + throws JobPersistenceException; + + /** + *

+ * Get the names of all of the {@link org.quartz.Job} + * groups. + *

+ * + *

+ * If there are no known group names, the result should be a zero-length + * array (not null). + *

+ */ + public String[] getJobGroupNames(SchedulingContext ctxt) + throws JobPersistenceException; + + /** + *

+ * Get the names of all of the {@link org.quartz.Trigger} + * groups. + *

+ * + *

+ * If there are no known group names, the result should be a zero-length + * array (not null). + *

+ */ + public String[] getTriggerGroupNames(SchedulingContext ctxt) + throws JobPersistenceException; + + /** + *

+ * Get the names of all of the {@link org.quartz.Calendar} s + * in the JobStore. + *

+ * + *

+ * If there are no Calendars in the given group name, the result should be + * a zero-length array (not null). + *

+ */ + public String[] getCalendarNames(SchedulingContext ctxt) + throws JobPersistenceException; + + /** + *

+ * Get all of the Triggers that are associated to the given Job. + *

+ * + *

+ * If there are no matches, a zero-length array should be returned. + *

+ */ + public Trigger[] getTriggersForJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException; + + /** + *

+ * Get the current state of the identified {@link Trigger}. + *

+ * + * @see Trigger#STATE_NORMAL + * @see Trigger#STATE_PAUSED + * @see Trigger#STATE_COMPLETE + * @see Trigger#STATE_ERROR + * @see Trigger#STATE_NONE + */ + public int getTriggerState(SchedulingContext ctxt, String triggerName, + String triggerGroup) throws JobPersistenceException; + + ///////////////////////////////////////////////////////////////////////////// + // + // Trigger State manipulation methods + // + ///////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Pause the {@link org.quartz.Trigger} with the given name. + *

+ * + * @see #resumeTrigger(SchedulingContext, String, String) + */ + public void pauseTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException; + + /** + *

+ * Pause all of the {@link org.quartz.Trigger}s in the + * given group. + *

+ * + * + *

+ * The JobStore should "remember" that the group is paused, and impose the + * pause on any new triggers that are added to the group while the group is + * paused. + *

+ * + * @see #resumeTriggerGroup(SchedulingContext, String) + */ + public void pauseTriggerGroup(SchedulingContext ctxt, String groupName) + throws JobPersistenceException; + + /** + *

+ * Pause the {@link org.quartz.Job} with the given name - by + * pausing all of its current Triggers. + *

+ * + * @see #resumeJob(SchedulingContext, String, String) + */ + public void pauseJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException; + + /** + *

+ * Pause all of the {@link org.quartz.Job}s in the given + * group - by pausing all of their Triggers. + *

+ * + *

+ * The JobStore should "remember" that the group is paused, and impose the + * pause on any new jobs that are added to the group while the group is + * paused. + *

+ * + * @see #resumeJobGroup(SchedulingContext, String) + */ + public void pauseJobGroup(SchedulingContext ctxt, String groupName) + throws JobPersistenceException; + + /** + *

+ * Resume (un-pause) the {@link org.quartz.Trigger} with the + * given name. + *

+ * + *

+ * If the Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseTrigger(SchedulingContext, String, String) + */ + public void resumeTrigger(SchedulingContext ctxt, String triggerName, + String groupName) throws JobPersistenceException; + + /** + *

+ * Resume (un-pause) all of the {@link org.quartz.Trigger}s + * in the given group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseTriggerGroup(SchedulingContext, String) + */ + public void resumeTriggerGroup(SchedulingContext ctxt, String groupName) + throws JobPersistenceException; + + public Set getPausedTriggerGroups(SchedulingContext ctxt) + throws JobPersistenceException; + + + /** + *

+ * Resume (un-pause) the {@link org.quartz.Job} with the + * given name. + *

+ * + *

+ * If any of the Job'sTrigger s missed one + * or more fire-times, then the Trigger's misfire + * instruction will be applied. + *

+ * + * @see #pauseJob(SchedulingContext, String, String) + */ + public void resumeJob(SchedulingContext ctxt, String jobName, + String groupName) throws JobPersistenceException; + + /** + *

+ * Resume (un-pause) all of the {@link org.quartz.Job}s in + * the given group. + *

+ * + *

+ * If any of the Job s had Trigger s that + * missed one or more fire-times, then the Trigger's + * misfire instruction will be applied. + *

+ * + * @see #pauseJobGroup(SchedulingContext, String) + */ + public void resumeJobGroup(SchedulingContext ctxt, String groupName) + throws JobPersistenceException; + + /** + *

+ * Pause all triggers - equivalent of calling pauseTriggerGroup(group) + * on every group. + *

+ * + *

+ * When resumeAll() is called (to un-pause), trigger misfire + * instructions WILL be applied. + *

+ * + * @see #resumeAll(SchedulingContext) + * @see #pauseTriggerGroup(SchedulingContext, String) + */ + public void pauseAll(SchedulingContext ctxt) throws JobPersistenceException; + + /** + *

+ * Resume (un-pause) all triggers - equivalent of calling resumeTriggerGroup(group) + * on every group. + *

+ * + *

+ * If any Trigger missed one or more fire-times, then the + * Trigger's misfire instruction will be applied. + *

+ * + * @see #pauseAll(SchedulingContext) + */ + public void resumeAll(SchedulingContext ctxt) + throws JobPersistenceException; + + ///////////////////////////////////////////////////////////////////////////// + // + // Trigger-Firing methods + // + ///////////////////////////////////////////////////////////////////////////// + + /** + *

+ * Get a handle to the next trigger to be fired, and mark it as 'reserved' + * by the calling scheduler. + *

+ * + * @param noLaterThan If > 0, the JobStore should only return a Trigger + * that will fire no later than the time represented in this value as + * milliseconds. + * @see #releaseAcquiredTrigger(SchedulingContext, Trigger) + */ + public Trigger acquireNextTrigger(SchedulingContext ctxt, long noLaterThan) + throws JobPersistenceException; + + /** + *

+ * Inform the JobStore that the scheduler no longer plans to + * fire the given Trigger, that it had previously acquired + * (reserved). + *

+ */ + public void releaseAcquiredTrigger(SchedulingContext ctxt, Trigger trigger) + throws JobPersistenceException; + + /** + *

+ * Inform the JobStore that the scheduler is now firing the + * given Trigger (executing its associated Job), + * that it had previously acquired (reserved). + *

+ * + * @return null if the trigger or it's job or calendar no longer exist, or + * if the trigger was not successfully put into the 'executing' + * state. + */ + public TriggerFiredBundle triggerFired(SchedulingContext ctxt, + Trigger trigger) throws JobPersistenceException; + + /** + *

+ * Inform the JobStore that the scheduler has completed the + * firing of the given Trigger (and the execution its + * associated Job), and that the {@link org.quartz.JobDataMap} + * in the given JobDetail should be updated if the Job + * is stateful. + *

+ */ + public void triggeredJobComplete(SchedulingContext ctxt, Trigger trigger, + JobDetail jobDetail, int triggerInstCode) + throws JobPersistenceException; + +} Index: 3rdParty_sources/quartz/org/quartz/spi/SchedulerPlugin.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/spi/SchedulerPlugin.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/spi/SchedulerPlugin.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,96 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.spi; + +import org.quartz.Scheduler; +import org.quartz.SchedulerException; + +/** + *

+ * Provides an interface for a class to become a "plugin" to Quartz. + *

+ * + *

+ * Plugins can do virtually anything you wish, though the most interesting ones + * will obviously interact with the scheduler in some way - either actively: by + * invoking actions on the scheduler, or passively: by being a JobListener, + * TriggerListener, and/or SchedulerListener. + *

+ * + *

+ * If you use {@link org.quartz.impl.StdSchedulerFactory} to + * initialize your Scheduler, it can also create and initialize your plugins - + * look at the configuration docs for details. + *

+ * + * @author James House + */ +public interface SchedulerPlugin { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Called during creation of the Scheduler in order to give + * the SchedulerPlugin a chance to initialize. + *

+ * + *

+ * At this point, the Scheduler's JobStore is not yet + * initialized. + *

+ * + * @param name + * The name by which the plugin is identified. + * @param scheduler + * The scheduler to which the plugin is registered. + * + * @throws SchedulerConfigException + * if there is an error initializing. + */ + public void initialize(String name, Scheduler scheduler) + throws SchedulerException; + + /** + *

+ * Called when the associated Scheduler is started, in order + * to let the plug-in know it can now make calls into the scheduler if it + * needs to. + *

+ */ + public void start(); + + /** + *

+ * Called in order to inform the SchedulerPlugin that it + * should free up all of it's resources because the scheduler is shutting + * down. + *

+ */ + public void shutdown(); + +} Index: 3rdParty_sources/quartz/org/quartz/spi/SchedulerSignaler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/spi/SchedulerSignaler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/spi/SchedulerSignaler.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.spi; + +import org.quartz.Trigger; + +/** + * An interface to be used by JobStore instances in order to + * communicate signals back to the QuartzScheduler. + * + * @author jhouse + */ +public interface SchedulerSignaler { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public void notifyTriggerListenersMisfired(Trigger trigger); + + public void signalSchedulingChange(); + +} Index: 3rdParty_sources/quartz/org/quartz/spi/ThreadPool.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/spi/ThreadPool.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/spi/ThreadPool.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.spi; + +import org.quartz.SchedulerConfigException; + +/** + *

+ * The interface to be implemented by classes that want to provide a thread + * pool for the {@link org.quartz.core.QuartzScheduler}'s use. + *

+ * + * @see org.quartz.core.QuartzScheduler + * + * @author James House + */ +public interface ThreadPool { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Execute the given {@link java.lang.Runnable} in the next + * available Thread. + *

+ * + *

+ * The implementation of this interface should not throw exceptions unless + * there is a serious problem (i.e. a serious misconfiguration). If there + * are no available threads, rather it should either queue the Runnable, or + * block until a thread is available, depending on the desired strategy. + *

+ */ + public boolean runInThread(Runnable runnable); + + /** + *

+ * Called by the QuartzScheduler before the ThreadPool is + * used, in order to give the it a chance to initialize. + *

+ */ + public void initialize() throws SchedulerConfigException; + + /** + *

+ * Called by the QuartzScheduler to inform the ThreadPool + * that it should free up all of it's resources because the scheduler is + * shutting down. + *

+ */ + public void shutdown(boolean waitForJobsToComplete); + + public int getPoolSize(); +} Index: 3rdParty_sources/quartz/org/quartz/spi/TimeBroker.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/spi/TimeBroker.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/spi/TimeBroker.java 17 Aug 2012 15:10:19 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.spi; + +import java.util.Date; + +import org.quartz.SchedulerConfigException; +import org.quartz.SchedulerException; + +/** + *

+ * The interface to be implemented by classes that want to provide a mechanism + * by which the {@link org.quartz.core.QuartzScheduler} can + * reliably determine the current time. + *

+ * + *

+ * In general, the default implementation of this interface ({@link org.quartz.simpl.SimpleTimeBroker}- + * which simply uses System.getCurrentTimeMillis() )is + * sufficient. However situations may exist where this default scheme is + * lacking in its robustsness - especially when Quartz is used in a clustered + * configuration. For example, if one or more of the machines in the cluster + * has a system time that varies by more than a few seconds from the clocks on + * the other systems in the cluster, scheduling confusion will result. + *

+ * + * @see org.quartz.core.QuartzScheduler + * + * @author James House + */ +public interface TimeBroker { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Get the current time, as known by the TimeBroker. + *

+ * + * @throws SchedulerException + * with the error code set to + * SchedulerException.ERR_TIME_BROKER_FAILURE + */ + public Date getCurrentTime() throws SchedulerException; + + /** + *

+ * Called by the QuartzScheduler before the TimeBroker is + * used, in order to give the it a chance to initialize. + *

+ */ + public void initialize() throws SchedulerConfigException; + + /** + *

+ * Called by the QuartzScheduler to inform the TimeBroker + * that it should free up all of it's resources because the scheduler is + * shutting down. + *

+ */ + public void shutdown(); + +} Index: 3rdParty_sources/quartz/org/quartz/spi/TriggerFiredBundle.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/spi/TriggerFiredBundle.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/spi/TriggerFiredBundle.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,138 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.spi; + +import java.util.Date; + +import org.quartz.Calendar; +import org.quartz.JobDetail; +import org.quartz.Trigger; + +/** + *

+ * A simple class (structure) used for returning execution-time data from the + * JobStore to the QuartzSchedulerThread. + *

+ * + * @see org.quartz.core.QuartzScheduler + * + * @author James House + */ +public class TriggerFiredBundle implements java.io.Serializable { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private JobDetail job; + + private Trigger trigger; + + private Calendar cal; + + private boolean jobIsRecovering; + + private Date fireTime; + + private Date scheduledFireTime; + + private Date prevFireTime; + + private Date nextFireTime; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public TriggerFiredBundle(JobDetail job, Trigger trigger, Calendar cal, + boolean jobIsRecovering, Date fireTime, Date scheduledFireTime, + Date prevFireTime, Date nextFireTime) { + this.job = job; + this.trigger = trigger; + this.cal = cal; + this.jobIsRecovering = jobIsRecovering; + this.fireTime = fireTime; + this.scheduledFireTime = scheduledFireTime; + this.prevFireTime = prevFireTime; + this.nextFireTime = nextFireTime; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public JobDetail getJobDetail() { + return job; + } + + public Trigger getTrigger() { + return trigger; + } + + public Calendar getCalendar() { + return cal; + } + + public boolean isRecovering() { + return jobIsRecovering; + } + + /** + * @return Returns the fireTime. + */ + public Date getFireTime() { + return fireTime; + } + + /** + * @return Returns the nextFireTime. + */ + public Date getNextFireTime() { + return nextFireTime; + } + + /** + * @return Returns the prevFireTime. + */ + public Date getPrevFireTime() { + return prevFireTime; + } + + /** + * @return Returns the scheduledFireTime. + */ + public Date getScheduledFireTime() { + return scheduledFireTime; + } + +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/spi/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/spi/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/spi/package.html 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,17 @@ + + +Package org.quartz.spi + + +

Contains Service Provider Interfaces that can be implemented by those +wishing to create and use custom versions of Quartz back-end/behind-the-scenes +services.

+ +
+
+
+See the Quartz project + at Open Symphony for more information. + + + Index: 3rdParty_sources/quartz/org/quartz/utils/ConnectionProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/utils/ConnectionProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/utils/ConnectionProvider.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.utils; + +import java.sql.Connection; +import java.sql.SQLException; + +/** + * Implementations of this interface used by DBConnectionManager + * to provide connections from various sources. + * + * @see DBConnectionManager + * @see PoolingConnectionProvider + * @see JNDIConnectionProvider + * @see org.quartz.utils.weblogic.WeblogicConnectionProvider + * + * @author Mohammad Rezaei + */ +public interface ConnectionProvider { + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * @return connection managed by this provider + * @throws SQLException + */ + public Connection getConnection() throws SQLException; + + + public void shutdown() throws SQLException; +} Index: 3rdParty_sources/quartz/org/quartz/utils/DBConnectionManager.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/utils/DBConnectionManager.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/utils/DBConnectionManager.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,145 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.utils; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.HashMap; + +/** + *

+ * Manages a collection of ConnectionProviders, and provides transparent access + * to their connections. + *

+ * + * @see ConnectionProvider + * @see PoolingConnectionProvider + * @see JNDIConnectionProvider + * @see org.quartz.utils.weblogic.WeblogicConnectionProvider + * + * @author James House + * @author Sharada Jambula + * @author Mohammad Rezaei + */ +public class DBConnectionManager { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static final String DB_PROPS_PREFIX = "org.quartz.db."; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private static DBConnectionManager instance = new DBConnectionManager(); + + private HashMap providers = new HashMap(); + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Private constructor + *

+ * + */ + private DBConnectionManager() { + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public void addConnectionProvider(String dataSourceName, + ConnectionProvider provider) { + this.providers.put(dataSourceName, provider); + } + + /** + * Get a database connection from the DataSource with the given name. + * + * @return a database connection + * @exception SQLException + * if an error occurs, or there is no DataSource with the + * given name. + */ + public Connection getConnection(String dsName) throws SQLException { + ConnectionProvider provider = (ConnectionProvider) providers + .get(dsName); + if (provider == null) + throw new SQLException("There is no DataSource named '" + + dsName + "'"); + + return provider.getConnection(); + } + + /** + * Get the class instance. + * + * @return an instance of this class + */ + public static DBConnectionManager getInstance() { + // since the instance variable is initialized at class loading time, + // it's not necessary to synchronize this method */ + return instance; + } + + /** + * Shuts down database connections from the DataSource with the given name, + * if applicable for the underlying provider. + * + * @return a database connection + * @exception SQLException + * if an error occurs, or there is no DataSource with the + * given name. + */ + public void shutdown(String dsName) throws SQLException { + + ConnectionProvider provider = (ConnectionProvider) providers + .get(dsName); + if (provider == null) + throw new SQLException("There is no DataSource named '" + + dsName + "'"); + + provider.shutdown(); + + } +} Index: 3rdParty_sources/quartz/org/quartz/utils/DirtyFlagMap.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/utils/DirtyFlagMap.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/utils/DirtyFlagMap.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,233 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.utils; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + *

+ * An implementation of Map that wraps another Map + * and flags itself 'dirty' when it is modified. + *

+ * + * @author James House + */ +public class DirtyFlagMap implements Map, Cloneable, java.io.Serializable { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + private static final long serialVersionUID = 1433884852607126222L; + + private boolean dirty = false; + private transient boolean locked = false; + private Map map; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Create a DirtyFlagMap that 'wraps' the given Map. + *

+ */ + public DirtyFlagMap(Map mapToWrap) { + if (mapToWrap == null) + throw new IllegalArgumentException("mapToWrap cannot be null!"); + + map = mapToWrap; + } + + /** + *

+ * Create a DirtyFlagMap that 'wraps' a HashMap. + *

+ * + * @see java.util.HashMap + */ + public DirtyFlagMap() { + map = new HashMap(); + } + + /** + *

+ * Create a DirtyFlagMap that 'wraps' a HashMap that has the + * given initial capacity. + *

+ * + * @see java.util.HashMap + */ + public DirtyFlagMap(int initialCapacity) { + map = new HashMap(initialCapacity); + } + + /** + *

+ * Create a DirtyFlagMap that 'wraps' a HashMap that has the + * given initial capacity and load factor. + *

+ * + * @see java.util.HashMap + */ + public DirtyFlagMap(int initialCapacity, float loadFactor) { + map = new HashMap(initialCapacity, loadFactor); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + + public void setMutable(boolean mutable) { + this.locked = !mutable; + if(locked) + map = Collections.unmodifiableMap(map); + else + map = new HashMap(map); + } + + + public boolean isMutable() { + return !locked; + } + + /** + *

+ * Clear the 'dirty' flag (set dirty flag to false). + *

+ */ + public void clearDirtyFlag() { + dirty = false; + } + + /** + *

+ * Determine whether the Map is flagged dirty. + *

+ */ + public boolean isDirty() { + return dirty; + } + + /** + *

+ * Get a direct handle to the underlying Map. + *

+ */ + public Map getWrappedMap() { + return map; + } + + public void clear() { + dirty = true; + + map.clear(); + } + + public boolean containsKey(Object key) { + return map.containsKey(key); + } + + public boolean containsValue(Object val) { + return map.containsValue(val); + } + + public Set entrySet() { + return map.entrySet(); + } + + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof DirtyFlagMap)) return false; + + return map.equals(((DirtyFlagMap) obj).getWrappedMap()); + } + + public Object get(Object key) { + return map.get(key); + } + + public boolean isEmpty() { + return map.isEmpty(); + } + + public Set keySet() { + return map.keySet(); + } + + public Object put(Object key, Object val) { + dirty = true; + + return map.put(key, val); + } + + public void putAll(Map t) { + if (!t.isEmpty()) dirty = true; + + map.putAll(t); + } + + public Object remove(Object key) { + Object obj = map.remove(key); + + if (obj != null) dirty = true; + + return obj; + } + + public int size() { + return map.size(); + } + + public Collection values() { + return map.values(); + } + + public Object clone() { + DirtyFlagMap copy; + try { + copy = (DirtyFlagMap) super.clone(); + if (map instanceof HashMap) + copy.map = (Map) ((HashMap) map).clone(); + } catch (CloneNotSupportedException ex) { + throw new IncompatibleClassChangeError("Not Cloneable."); + } + + return copy; + } + +} \ No newline at end of file Index: 3rdParty_sources/quartz/org/quartz/utils/JNDIConnectionProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/utils/JNDIConnectionProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/utils/JNDIConnectionProvider.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,191 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.utils; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Properties; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.sql.DataSource; +import javax.sql.XADataSource; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + *

+ * A ConnectionProvider that provides connections from a DataSource + * that is managed by an application server, and made available via JNDI. + *

+ * + * @see DBConnectionManager + * @see ConnectionProvider + * @see PoolingConnectionProvider + * + * @author James House + * @author Sharada Jambula + * @author Mohammad Rezaei + * @author Patrick Lightbody + * @author Srinivas Venkatarangaiah + */ +public class JNDIConnectionProvider implements ConnectionProvider { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private String url; + + private Properties props; + + private Object datasource; + + private boolean alwaysLookup = false; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Constructor + * + * @param jndiUrl + * The url for the datasource + */ + public JNDIConnectionProvider(String jndiUrl, boolean alwaysLookup) { + this.url = jndiUrl; + this.alwaysLookup = alwaysLookup; + init(); + } + + /** + * Constructor + * + * @param jndiUrl + * The URL for the DataSource + * @param jndiProps + * The JNDI properties to use when establishing the InitialContext + * for the lookup of the given URL. + */ + public JNDIConnectionProvider(String jndiUrl, Properties jndiProps, + boolean alwaysLookup) { + this.url = jndiUrl; + this.props = jndiProps; + this.alwaysLookup = alwaysLookup; + init(); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + Log getLog() { + return LogFactory.getLog(getClass()); + } + + private void init() { + + if (!isAlwaysLookup()) { + Context ctx = null; + try { + if (props != null) ctx = new InitialContext(props); + else + ctx = new InitialContext(); + + datasource = (DataSource) ctx.lookup(url); + } catch (Exception e) { + getLog().error( + "Error looking up datasource: " + e.getMessage(), e); + } + finally { + if(ctx != null) + try { ctx.close(); } catch(Exception ignore) {} + } + } + } + + public Connection getConnection() throws SQLException { + Context ctx = null; + try { + Object ds = this.datasource; + + if (ds == null || isAlwaysLookup()) { + if (props != null) ctx = new InitialContext(props); + else + ctx = new InitialContext(); + + ds = ctx.lookup(url); + if (!isAlwaysLookup()) this.datasource = ds; + } + + if (ds == null) + throw new SQLException( + "There is no object at the JNDI URL '" + url + "'"); + + if (ds instanceof XADataSource) return (((XADataSource) ds) + .getXAConnection().getConnection()); + else if (ds instanceof DataSource) return ((DataSource) ds) + .getConnection(); + else + throw new SQLException("Object at JNDI URL '" + url + + "' is not a DataSource."); + } catch (Exception e) { + this.datasource = null; + throw new SQLException( + "Could not retrieve datasource via JNDI url '" + url + "' " + + e.getClass().getName() + ": " + e.getMessage()); + } + finally { + if(ctx != null) + try { ctx.close(); } catch(Exception ignore) {} + } + } + + public boolean isAlwaysLookup() { + return alwaysLookup; + } + + public void setAlwaysLookup(boolean b) { + alwaysLookup = b; + } + + /* + * @see org.quartz.utils.ConnectionProvider#shutdown() + */ + public void shutdown() throws SQLException { + // do nothing + } + +} Index: 3rdParty_sources/quartz/org/quartz/utils/Key.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/utils/Key.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/utils/Key.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,97 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.utils; + +/** + *

+ * Object representing a job or trigger key. + *

+ * + * @author Jeffrey Wescott + */ +public class Key extends Pair { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Construct a new key with the given name and group. + * + * @param name + * the name + * @param group + * the group + */ + public Key(String name, String group) { + super(); + super.setFirst(name); + super.setSecond(group); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Get the name portion of the key. + *

+ * + * @return the name + */ + public String getName() { + return (String) getFirst(); + } + + /** + *

+ * Get the group portion of the key. + *

+ * + * @return the group + */ + public String getGroup() { + return (String) getSecond(); + } + + /** + *

+ * Return the string representation of the key. The format will be: + * <group>.<name>. + *

+ * + * @return the string representation of the key + */ + public String toString() { + return getGroup() + '.' + getName(); + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/utils/Pair.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/utils/Pair.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/utils/Pair.java 17 Aug 2012 15:10:20 -0000 1.1 @@ -0,0 +1,123 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ + +package org.quartz.utils; + +/** + *

+ * Utility class for storing two pieces of information together. + *

+ * + * @author Jeffrey Wescott + */ +public class Pair { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private Object first; + + private Object second; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + *

+ * Get the first object in the pair. + *

+ * + * @return the first object + */ + public final Object getFirst() { + return first; + } + + /** + *

+ * Set the value of the first object in the pair. + *

+ * + * @param first + * the first object + */ + public final void setFirst(Object first) { + this.first = first; + } + + /** + *

+ * Get the second object in the pair. + *

+ * + * @return the second object + */ + public final Object getSecond() { + return second; + } + + /** + *

+ * Set the second object in the pair. + *

+ * + * @param second + * the second object + */ + public final void setSecond(Object second) { + this.second = second; + } + + /** + *

+ * Test equality of this object with that. + *

+ * + * @param that + * object to compare + * @return true if objects are equal, false otherwise + */ + public boolean equals(Object that) { + if (this == that) { + return true; + } else { + try { + Pair other = (Pair) that; + return (this.first.equals(other.first) && this.second + .equals(other.second)); + } catch (ClassCastException e) { + return false; + } + } + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/utils/PoolingConnectionProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/utils/PoolingConnectionProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/utils/PoolingConnectionProvider.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,178 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.utils; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Properties; + +import org.apache.commons.dbcp.BasicDataSource; + +/** + *

+ * A ConnectionProvider implementation that creates it's own + * pool of connections. + *

+ * + *

+ * This class uses DBCP + * , an Apache-Jakarta-Commons product. + *

+ * + * @see DBConnectionManager + * @see ConnectionProvider + * + * @author Sharada Jambula + * @author James House + * @author Mohammad Rezaei + */ +public class PoolingConnectionProvider implements ConnectionProvider { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static final String DB_PROPS_PREFIX = "org.quartz.db."; + + public static final String DB_JNDI_DATASOURCE_URL = "jndiURL"; + + // The JDBC database driver + public static final String DB_DRIVER = "driver"; + + // The JDBC database URL + public static final String DB_URL = "URL"; + + // The database user name + public static final String DB_USER = "user"; + + // The database user password + public static final String DB_PASSWORD = "password"; + + public static final String DB_MAX_CONNECTIONS = "maxConnections"; + + public static final String DB_VALIDATION_QUERY = "validationQuery"; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private BasicDataSource datasource; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public PoolingConnectionProvider(String dbDriver, String dbURL, + String dbUser, String dbPassword, int maxConnections, + String dbValidationQuery) throws SQLException { + + initialize(dbDriver, dbURL, dbUser, dbPassword, maxConnections, + dbValidationQuery); + + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private void initialize(String dbDriver, String dbURL, String dbUser, + String dbPassword, int maxConnections, String dbValidationQuery) + throws SQLException { + if (dbDriver == null) + throw new SQLException("DB driver class name cannot be null!"); + if (dbURL == null) throw new SQLException("DB URL cannot be null!"); + if (maxConnections < 0) + throw new SQLException( + "Max connections must be greater than zero!"); + + datasource = new BasicDataSource(); + datasource.setDriverClassName(dbDriver); + datasource.setUrl(dbURL); + datasource.setUsername(dbUser); + datasource.setPassword(dbPassword); + datasource.setMaxActive(maxConnections); + if (dbValidationQuery != null) + datasource.setValidationQuery(dbValidationQuery); + } + + /** + *

+ * Create a connection pool using the given properties. + *

+ * + *

+ * The properties passed should contain either + *

    + *
  • JNDI DataSource URL {@link #DB_JNDI_DATASOURCE_URL} + *
+ * or + *
    + *
  • {@link #DB_DRIVER}- The database driver class name + *
  • {@link #DB_URL}- The database URL + *
  • {@link #DB_USER}- The database user + *
  • {@link #DB_PASSWORD}- The database password + *
  • {@link #DB_MAX_CONNECTIONS}- The maximum # connections in the pool + *
+ *

+ * + * @param config + * configuration properties + * @exception SQLException + * if an error occurs + */ + public PoolingConnectionProvider(Properties config) throws SQLException { + PropertiesParser cfg = new PropertiesParser(config); + String url = config.getProperty(DB_URL); + try { + initialize(config.getProperty(DB_DRIVER), url, config + .getProperty(DB_USER), config.getProperty(DB_PASSWORD), cfg + .getIntProperty(DB_MAX_CONNECTIONS, 3), cfg + .getStringProperty(DB_VALIDATION_QUERY)); + } catch (Exception e) { + throw new SQLException("DBPool '" + url + + "' could not be created: " + e.toString()); + } + } + + public Connection getConnection() throws SQLException { + return this.datasource.getConnection(); + } + + public void shutdown() throws SQLException { + this.datasource.close(); + } +} Index: 3rdParty_sources/quartz/org/quartz/utils/PropertiesParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/utils/PropertiesParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/utils/PropertiesParser.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,355 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.utils; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Properties; +import java.util.StringTokenizer; +import java.util.Vector; + +/** + *

+ * This is an utility calss used to parse the properties. + *

+ * + * @author James House + */ +public class PropertiesParser { + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + Properties props = null; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public PropertiesParser(Properties props) { + this.props = props; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public Properties getUnderlyingProperties() { + return props; + } + + public String getStringProperty(String name) { + String val = props.getProperty(name); + if (val == null) return null; + return val.trim(); + } + + public String getStringProperty(String name, String def) { + String val = props.getProperty(name, def); + if (val == null) return def; + val = val.trim(); + if (val.length() == 0) return def; + return val; + } + + public String[] getStringArrayProperty(String name) { + return getStringArrayProperty(name, null); + } + + public String[] getStringArrayProperty(String name, String[] def) { + String vals = getStringProperty(name); + if (vals == null) return def; + + if (vals != null && !vals.trim().equals("")) { + StringTokenizer stok = new StringTokenizer(vals, ","); + Vector strs = new Vector(); + try { + while (stok.hasMoreTokens()) { + strs.addElement(stok.nextToken()); + } + String[] outStrs = new String[strs.size()]; + for (int i = 0; i < strs.size(); i++) + outStrs[i] = (String) strs.elementAt(i); + return outStrs; + } catch (Exception e) { + return def; + } + } + + return def; + } + + public boolean getBooleanProperty(String name) { + String val = getStringProperty(name); + if (val == null) return false; + + return new Boolean(val).booleanValue(); + } + + public boolean getBooleanProperty(String name, boolean def) { + String val = getStringProperty(name); + if (val == null) return def; + + return new Boolean(val).booleanValue(); + } + + public byte getByteProperty(String name) throws NumberFormatException { + String val = getStringProperty(name); + if (val == null) throw new NumberFormatException(" null string"); + + try { + return Byte.parseByte(val); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + val + "'"); + } + } + + public byte getByteProperty(String name, byte def) + throws NumberFormatException { + String val = getStringProperty(name); + if (val == null) return def; + + try { + return Byte.parseByte(val); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + val + "'"); + } + } + + public char getCharProperty(String name) { + String param = getStringProperty(name); + if (param == null) return '\0'; + + if (param.length() == 0) return '\0'; + + return param.charAt(0); + } + + public char getCharProperty(String name, char def) { + String param = getStringProperty(name); + if (param == null) return def; + + if (param.length() == 0) return def; + + return param.charAt(0); + } + + public double getDoubleProperty(String name) throws NumberFormatException { + String val = getStringProperty(name); + if (val == null) throw new NumberFormatException(" null string"); + + try { + return Double.parseDouble(val); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + val + "'"); + } + } + + public double getDoubleProperty(String name, double def) + throws NumberFormatException { + String val = getStringProperty(name); + if (val == null) return def; + + try { + return Double.parseDouble(val); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + val + "'"); + } + } + + public float getFloatProperty(String name) throws NumberFormatException { + String val = getStringProperty(name); + if (val == null) throw new NumberFormatException(" null string"); + + try { + return Float.parseFloat(val); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + val + "'"); + } + } + + public float getFloatProperty(String name, float def) + throws NumberFormatException { + String val = getStringProperty(name); + if (val == null) return def; + + try { + return Float.parseFloat(val); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + val + "'"); + } + } + + public int getIntProperty(String name) throws NumberFormatException { + String val = getStringProperty(name); + if (val == null) throw new NumberFormatException(" null string"); + + try { + return Integer.parseInt(val); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + val + "'"); + } + } + + public int getIntProperty(String name, int def) + throws NumberFormatException { + String val = getStringProperty(name); + if (val == null) return def; + + try { + return Integer.parseInt(val); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + val + "'"); + } + } + + public int[] getIntArrayProperty(String name) throws NumberFormatException { + return getIntArrayProperty(name, null); + } + + public int[] getIntArrayProperty(String name, int[] def) + throws NumberFormatException { + String vals = getStringProperty(name); + if (vals == null) return def; + + if (vals != null && !vals.trim().equals("")) { + StringTokenizer stok = new StringTokenizer(vals, ","); + Vector ints = new Vector(); + try { + while (stok.hasMoreTokens()) { + try { + ints.addElement(new Integer(stok.nextToken())); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + vals + "'"); + } + } + int[] outInts = new int[ints.size()]; + for (int i = 0; i < ints.size(); i++) + outInts[i] = ((Integer) ints.elementAt(i)).intValue(); + return outInts; + } catch (Exception e) { + return def; + } + } + + return def; + } + + public long getLongProperty(String name) throws NumberFormatException { + String val = getStringProperty(name); + if (val == null) throw new NumberFormatException(" null string"); + + try { + return Long.parseLong(val); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + val + "'"); + } + } + + public long getLongProperty(String name, long def) + throws NumberFormatException { + String val = getStringProperty(name); + if (val == null) return def; + + try { + return Long.parseLong(val); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + val + "'"); + } + } + + public short getShortProperty(String name) throws NumberFormatException { + String val = getStringProperty(name); + if (val == null) throw new NumberFormatException(" null string"); + + try { + return Short.parseShort(val); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + val + "'"); + } + } + + public short getShortProperty(String name, short def) + throws NumberFormatException { + String val = getStringProperty(name); + if (val == null) return def; + + try { + return Short.parseShort(val); + } catch (NumberFormatException nfe) { + throw new NumberFormatException(" '" + val + "'"); + } + } + + public String[] getPropertyGroups(String prefix) { + Enumeration keys = props.propertyNames(); + HashMap groups = new HashMap(10); + + if (!prefix.endsWith(".")) prefix += "."; + + while (keys.hasMoreElements()) { + String key = (String) keys.nextElement(); + if (key.startsWith(prefix)) { + String groupName = key.substring(prefix.length(), key.indexOf( + '.', prefix.length())); + groups.put(groupName, groupName); + } + } + + return (String[]) groups.values().toArray(new String[groups.size()]); + } + + public Properties getPropertyGroup(String prefix) { + return getPropertyGroup(prefix, false); + } + + public Properties getPropertyGroup(String prefix, boolean stripPrefix) { + Enumeration keys = props.propertyNames(); + Properties group = new Properties(); + + if (!prefix.endsWith(".")) prefix += "."; + + while (keys.hasMoreElements()) { + String key = (String) keys.nextElement(); + if (key.startsWith(prefix)) { + if (stripPrefix) group.put(key.substring(prefix.length()), + props.getProperty(key)); + else + group.put(key, props.getProperty(key)); + } + } + + return group; + } +} Index: 3rdParty_sources/quartz/org/quartz/utils/TriggerStatus.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/utils/TriggerStatus.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/utils/TriggerStatus.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,139 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ + +package org.quartz.utils; + +import java.util.Date; + +/** + *

+ * Object representing a job or trigger key. + *

+ * + * @author James House + */ +public class TriggerStatus extends Pair { + + // TODO: Repackage under spi or root pkg ?, put status constants here. + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private Key key; + + private Key jobKey; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Construct a new TriggerStatus with the status name and nextFireTime. + * + * @param status + * the trigger's status + * @param nextFireTime + * the next time the trigger will fire + */ + public TriggerStatus(String status, Date nextFireTime) { + super(); + super.setFirst(status); + super.setSecond(nextFireTime); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * @return + */ + public Key getJobKey() { + return jobKey; + } + + /** + * @param jobKey + */ + public void setJobKey(Key jobKey) { + this.jobKey = jobKey; + } + + /** + * @return + */ + public Key getKey() { + return key; + } + + /** + * @param key + */ + public void setKey(Key key) { + this.key = key; + } + + /** + *

+ * Get the name portion of the key. + *

+ * + * @return the name + */ + public String getStatus() { + return (String) getFirst(); + } + + /** + *

+ * Get the group portion of the key. + *

+ * + * @return the group + */ + public Date getNextFireTime() { + return (Date) getSecond(); + } + + /** + *

+ * Return the string representation of the TriggerStatus. + *

+ * + */ + public String toString() { + return "status: " + getStatus() + ", next Fire = " + getNextFireTime(); + } +} + +// EOF Index: 3rdParty_sources/quartz/org/quartz/xml/CalendarBundle.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/xml/CalendarBundle.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/xml/CalendarBundle.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,132 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.xml; + +import org.quartz.Calendar; + +/** + * Wraps a Calendar. + * + * @author Chris Bonham + */ +public class CalendarBundle implements Calendar { + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected String calendarName; + + protected String className; + + protected Calendar calendar; + + protected boolean replace; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public CalendarBundle() { + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public String getCalendarName() { + return calendarName; + } + + public void setCalendarName(String calendarName) { + this.calendarName = calendarName; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) + throws ClassNotFoundException, InstantiationException, IllegalAccessException { + this.className = className; + createCalendar(); + } + + public Calendar getCalendar() { + return calendar; + } + + public void setCalendar(Calendar calendar) { + this.calendar = calendar; + } + + public boolean getReplace() { + return replace; + } + + public void setReplace(boolean replace) { + this.replace = replace; + } + + public Calendar getBaseCalendar() { + return calendar.getBaseCalendar(); + } + + public void setBaseCalendar(Calendar baseCalendar) { + if (baseCalendar instanceof CalendarBundle) { + baseCalendar = ((CalendarBundle)baseCalendar).getCalendar(); + } + calendar.setBaseCalendar(baseCalendar); + } + + public String getDescription() { + return calendar.getDescription(); + } + + public void setDescription(String description) { + calendar.setDescription(description); + } + + public boolean isTimeIncluded(long timeStamp) { + return calendar.isTimeIncluded(timeStamp); + } + + public long getNextIncludedTime(long timeStamp) { + return calendar.getNextIncludedTime(timeStamp); + } + + protected void createCalendar() + throws ClassNotFoundException, InstantiationException, IllegalAccessException { + Class clazz = Thread.currentThread().getContextClassLoader().loadClass(getClassName()); + setCalendar((Calendar)clazz.newInstance()); + } +} Index: 3rdParty_sources/quartz/org/quartz/xml/JobSchedulingBundle.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/xml/JobSchedulingBundle.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/xml/JobSchedulingBundle.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,124 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.xml; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import org.quartz.CronTrigger; +import org.quartz.JobDetail; +import org.quartz.Trigger; + +/** + * Wraps a JobDetail and Trigger. + * + * @author Chris Bonham + * @author James House + */ +public class JobSchedulingBundle { + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected JobDetail jobDetail; + + protected List triggers = new ArrayList(); + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public JobSchedulingBundle() { + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public JobDetail getJobDetail() { + return jobDetail; + } + + public void setJobDetail(JobDetail jobDetail) { + this.jobDetail = jobDetail; + } + + public List getTriggers() { + return triggers; + } + + public void setTriggers(List triggers) { + this.triggers = triggers; + } + + public void addTrigger(Trigger trigger) { + if (trigger.getStartTime() == null) { + trigger.setStartTime(new Date()); + } + + if (trigger instanceof CronTrigger) { + CronTrigger ct = (CronTrigger)trigger; + if (ct.getTimeZone() == null) { + ct.setTimeZone(TimeZone.getDefault()); + } + } + + triggers.add(trigger); + } + + public void removeTrigger(Trigger trigger) { + triggers.remove(trigger); + } + + public String getName() { + if (getJobDetail() != null) { + return getJobDetail().getName(); + } else { + return null; + } + } + public String getFullName() { + if (getJobDetail() != null) { + return getJobDetail().getFullName(); + } else { + return null; + } + } + + + public boolean isValid() { + return ((getJobDetail() != null) && (getTriggers() != null)); + } +} Index: 3rdParty_sources/quartz/org/quartz/xml/JobSchedulingDataProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/xml/JobSchedulingDataProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/xml/JobSchedulingDataProcessor.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,1276 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.xml; + +import java.beans.PropertyDescriptor; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; + +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.commons.beanutils.ConversionException; +import org.apache.commons.beanutils.Converter; +import org.apache.commons.beanutils.DynaBean; +import org.apache.commons.beanutils.DynaProperty; +import org.apache.commons.beanutils.PropertyUtils; +import org.apache.commons.digester.BeanPropertySetterRule; +import org.apache.commons.digester.Digester; +import org.apache.commons.digester.RuleSetBase; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.quartz.CronTrigger; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.JobListener; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.SimpleTrigger; +import org.quartz.Trigger; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.helpers.DefaultHandler; + + +/** + * Parses an XML file that declares Jobs and their schedules (Triggers). + * + * The xml document must conform to the format defined in + * "job_scheduling_data_1_2.dtd" or "job_scheduling_data_1_2.xsd" + * + * After creating an instance of this class, you should call one of the processFile() + * functions, after which you may call the getScheduledJobs() + * function to get a handle to the defined Jobs and Triggers, which can then be + * scheduled with the Scheduler. Alternatively, you could call + * the processFileAndScheduleJobs() function to do all of this + * in one step. + * + * The same instance can be used again and again, with the list of defined Jobs + * being cleared each time you call a processFile method, + * however a single instance is not thread-safe. + * + * @author Chris Bonham + * @author James House + */ +public class JobSchedulingDataProcessor extends DefaultHandler { + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constants. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + public static final String QUARTZ_PUBLIC_ID = "-//Quartz Enterprise Job Scheduler//DTD Job Scheduling Data 1.5//EN"; + + public static final String QUARTZ_SYSTEM_ID = "http://www.opensymphony.com/quartz/xml/job_scheduling_data_1_5.dtd"; + + public static final String QUARTZ_DTD = "/org/quartz/xml/job_scheduling_data_1_5.dtd"; + + public static final String QUARTZ_NS = "http://www.opensymphony.com/quartz/JobSchedulingData"; + + public static final String QUARTZ_SCHEMA = "http://www.opensymphony.com/quartz/xml/job_scheduling_data_1_5.xsd"; + + public static final String QUARTZ_XSD = "/org/quartz/xml/job_scheduling_data_1_5.xsd"; + + public static final String QUARTZ_SYSTEM_ID_DIR_PROP = "quartz.system.id.dir"; + + public static final String QUARTZ_XML_FILE_NAME = "quartz_jobs.xml"; + + public static final String QUARTZ_SYSTEM_ID_PREFIX = "jar:"; + + protected static final String TAG_QUARTZ = "quartz"; + + protected static final String TAG_OVERWRITE_EXISTING_JOBS = "overwrite-existing-jobs"; + + protected static final String TAG_JOB_LISTENER = "job-listener"; + + protected static final String TAG_CALENDAR = "calendar"; + + protected static final String TAG_CLASS_NAME = "class-name"; + + protected static final String TAG_DESCRIPTION = "description"; + + protected static final String TAG_BASE_CALENDAR = "base-calendar"; + + protected static final String TAG_MISFIRE_INSTRUCTION = "misfire-instruction"; + + protected static final String TAG_CALENDAR_NAME = "calendar-name"; + + protected static final String TAG_JOB = "job"; + + protected static final String TAG_JOB_DETAIL = "job-detail"; + + protected static final String TAG_NAME = "name"; + + protected static final String TAG_GROUP = "group"; + + protected static final String TAG_JOB_CLASS = "job-class"; + + protected static final String TAG_JOB_LISTENER_REF = "job-listener-ref"; + + protected static final String TAG_VOLATILITY = "volatility"; + + protected static final String TAG_DURABILITY = "durability"; + + protected static final String TAG_RECOVER = "recover"; + + protected static final String TAG_JOB_DATA_MAP = "job-data-map"; + + protected static final String TAG_ENTRY = "entry"; + + protected static final String TAG_KEY = "key"; + + protected static final String TAG_ALLOWS_TRANSIENT_DATA = "allows-transient-data"; + + protected static final String TAG_VALUE = "value"; + + protected static final String TAG_TRIGGER = "trigger"; + + protected static final String TAG_SIMPLE = "simple"; + + protected static final String TAG_CRON = "cron"; + + protected static final String TAG_JOB_NAME = "job-name"; + + protected static final String TAG_JOB_GROUP = "job-group"; + + protected static final String TAG_START_TIME = "start-time"; + + protected static final String TAG_END_TIME = "end-time"; + + protected static final String TAG_REPEAT_COUNT = "repeat-count"; + + protected static final String TAG_REPEAT_INTERVAL = "repeat-interval"; + + protected static final String TAG_CRON_EXPRESSION = "cron-expression"; + + protected static final String TAG_TIME_ZONE = "time-zone"; + + /** + * XML Schema dateTime datatype format. + *

+ * See + * http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/#dateTime + */ + protected static final String XSD_DATE_FORMAT = "yyyy-MM-dd'T'hh:mm:ss"; + + /** + * Legacy DTD version 1.0 date format. + */ + protected static final String DTD_DATE_FORMAT = "yyyy-MM-dd hh:mm:ss a"; + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + protected Map scheduledJobs = new HashMap(); + + protected List jobsToSchedule = new LinkedList(); + protected List calsToSchedule = new LinkedList(); + protected List listenersToSchedule = new LinkedList(); + + protected Collection validationExceptions = new ArrayList(); + + protected Digester digester; + + private boolean overWriteExistingJobs = true; + + private ThreadLocal schedLocal = new ThreadLocal(); + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Constructor for QuartzMetaDataProcessor. + */ + public JobSchedulingDataProcessor() { + this(true, true, true); + } + + /** + * Constructor for QuartzMetaDataProcessor. + * + * @param useContextClassLoader whether or not to use the context class loader. + * @param validating whether or not to validate XML. + * @param validatingSchema whether or not to validate XML schema. + */ + public JobSchedulingDataProcessor(boolean useContextClassLoader, boolean validating, boolean validatingSchema) { + initDigester(useContextClassLoader, validating, validatingSchema); + } + + /** + * Initializes the digester. + * + * @param useContextClassLoader whether or not to use the context class loader. + * @param validating whether or not to validate XML. + * @param validatingSchema whether or not to validate XML schema. + */ + protected void initDigester(boolean useContextClassLoader, boolean validating, boolean validatingSchema) { + digester = new Digester(); + digester.setNamespaceAware(true); + digester.setUseContextClassLoader(useContextClassLoader); + digester.setValidating(validating); + initSchemaValidation(validatingSchema); + digester.setEntityResolver(this); + digester.setErrorHandler(this); + + if(addCustomDigesterRules(digester)) + addDefaultDigesterRules(digester); + } + + /** + * Add the default set of digest rules + */ + protected void addDefaultDigesterRules(Digester digester) { + digester.addSetProperties(TAG_QUARTZ, TAG_OVERWRITE_EXISTING_JOBS, "overWriteExistingJobs"); + digester.addObjectCreate(TAG_QUARTZ + "/" + TAG_JOB_LISTENER, "jobListener","class-name"); + digester.addCallMethod(TAG_QUARTZ + "/" + TAG_JOB_LISTENER,"setName",1); + digester.addCallParam(TAG_QUARTZ + "/" + TAG_JOB_LISTENER,0,"name"); + digester.addSetNext(TAG_QUARTZ + "/" + TAG_JOB_LISTENER,"addListenerToSchedule"); + digester.addRuleSet(new CalendarRuleSet(TAG_QUARTZ + "/" + TAG_CALENDAR, "addCalendarToSchedule")); + digester.addRuleSet(new CalendarRuleSet("*/" + TAG_BASE_CALENDAR, "setBaseCalendar")); + digester.addObjectCreate(TAG_QUARTZ + "/" + TAG_JOB, JobSchedulingBundle.class); + digester.addObjectCreate(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL, JobDetail.class); + digester.addBeanPropertySetter(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_NAME, "name"); + digester.addBeanPropertySetter(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_GROUP, "group"); + digester.addBeanPropertySetter(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_DESCRIPTION, "description"); + digester.addBeanPropertySetter(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_JOB_CLASS, "jobClass"); + digester.addCallMethod(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_JOB_LISTENER_REF,"addJobListener",0 ); + digester.addBeanPropertySetter(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_VOLATILITY, "volatility"); + digester.addBeanPropertySetter(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_DURABILITY, "durability"); + digester.addBeanPropertySetter(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_RECOVER, "requestsRecovery"); + digester.addObjectCreate(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_JOB_DATA_MAP, JobDataMap.class); + digester.addSetProperties(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_JOB_DATA_MAP, TAG_ALLOWS_TRANSIENT_DATA, "allowsTransientData"); + digester.addCallMethod(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_JOB_DATA_MAP + "/" + TAG_ENTRY, "put", 2, new Class[] { Object.class, Object.class }); + digester.addCallParam(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_JOB_DATA_MAP + "/" + TAG_ENTRY + "/" + TAG_KEY, 0); + digester.addCallParam(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_JOB_DATA_MAP + "/" + TAG_ENTRY + "/" + TAG_VALUE, 1); + digester.addSetNext(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL + "/" + TAG_JOB_DATA_MAP, "setJobDataMap"); + digester.addSetNext(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_JOB_DETAIL, "setJobDetail"); + digester.addRuleSet(new TriggerRuleSet(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_TRIGGER + "/" + TAG_SIMPLE, SimpleTrigger.class)); + digester.addBeanPropertySetter(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_TRIGGER + "/" + TAG_SIMPLE + "/" + TAG_REPEAT_COUNT, "repeatCount"); + digester.addBeanPropertySetter(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_TRIGGER + "/" + TAG_SIMPLE + "/" + TAG_REPEAT_INTERVAL, "repeatInterval"); + digester.addSetNext(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_TRIGGER + "/" + TAG_SIMPLE, "addTrigger"); + digester.addRuleSet(new TriggerRuleSet(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_TRIGGER + "/" + TAG_CRON, CronTrigger.class)); + digester.addBeanPropertySetter(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_TRIGGER + "/" + TAG_CRON + "/" + TAG_CRON_EXPRESSION, "cronExpression"); + digester.addRule(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_TRIGGER + "/" + TAG_CRON + "/" + TAG_TIME_ZONE, new SimpleConverterRule("timeZone", new TimeZoneConverter(), TimeZone.class)); + digester.addSetNext(TAG_QUARTZ + "/" + TAG_JOB + "/" + TAG_TRIGGER + "/" + TAG_CRON, "addTrigger"); + digester.addSetNext(TAG_QUARTZ + "/" + TAG_JOB, "addJobToSchedule"); + } + + /** + * Template method provided as a hook for those who wish to extend this + * class and add more functionality. + * + * This method is invoked after the Digester is instantiated, and before + * the default set of rules are added. + * + * @param digester + * @return false, if the default rules should NOT be added + */ + protected boolean addCustomDigesterRules(Digester digester) { + // do nothing in base impl + return true; + } + + /** + * Initializes the digester for XML Schema validation. + * + * @param validating whether or not to validate XML. + */ + protected void initSchemaValidation(boolean validatingSchema) { + if (validatingSchema) { + String schemaUri = null; + URL url = getClass().getResource(QUARTZ_XSD); + if (url != null) { + schemaUri = url.toExternalForm(); + } + else { + schemaUri = QUARTZ_SCHEMA; + } + digester.setSchema(schemaUri); + } + } + + protected static Log getLog() { + return LogFactory.getLog(JobSchedulingDataProcessor.class); + } + + /** + * Returns whether to use the context class loader. + * + * @return whether to use the context class loader. + */ + public boolean getUseContextClassLoader() { + return digester.getUseContextClassLoader(); + } + + /** + * Sets whether to use the context class loader. + * + * @param useContextClassLoader boolean. + */ + public void setUseContextClassLoader(boolean useContextClassLoader) { + digester.setUseContextClassLoader(useContextClassLoader); + } + + /** + * Returns whether to overwrite existing jobs. + * + * @return whether to overwrite existing jobs. + */ + public boolean getOverWriteExistingJobs() { + return overWriteExistingJobs; + } + + /** + * Sets whether to overwrite existing jobs. + * + * @param overWriteExistingJobs boolean. + */ + public void setOverWriteExistingJobs(boolean overWriteExistingJobs) { + this.overWriteExistingJobs = overWriteExistingJobs; + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Process the xml file in the default location (a file named + * "quartz_jobs.xml" in the current working directory). + * + */ + public void processFile() throws Exception { + processFile(QUARTZ_XML_FILE_NAME); + } + + /** + * Process the xml file named fileName. + * + * @param fileName + * meta data file name. + */ + public void processFile(String fileName) throws Exception { + processFile(fileName, fileName); + } + + /** + * Process the xmlfile named fileName with the given system + * ID. + * + * @param fileName + * meta data file name. + * @param systemId + * system ID. + */ + public void processFile(String fileName, String systemId) + throws ValidationException, ParserConfigurationException, + SAXException, IOException, SchedulerException, + ClassNotFoundException, ParseException { + clearValidationExceptions(); + + scheduledJobs.clear(); + jobsToSchedule.clear(); + calsToSchedule.clear(); + + getLog().info("Parsing XML file: " + fileName + + " with systemId: " + systemId + + " validating: " + digester.getValidating() + + " validating schema: " + digester.getSchema()); + InputSource is = new InputSource(getInputStream(fileName)); + is.setSystemId(systemId); + digester.push(this); + digester.parse(is); + + maybeThrowValidationException(); + } + + /** + * Process the xmlfile named fileName with the given system + * ID. + * + * @param stream + * an input stream containing the xml content. + * @param systemId + * system ID. + */ + public void processStream(InputStream stream, String systemId) + throws ValidationException, ParserConfigurationException, + SAXException, IOException, SchedulerException, + ClassNotFoundException, ParseException { + clearValidationExceptions(); + + scheduledJobs.clear(); + jobsToSchedule.clear(); + calsToSchedule.clear(); + + getLog().info("Parsing XML from stream with systemId: " + systemId + + " validating: " + digester.getValidating() + + " validating schema: " + digester.getSchema()); + InputSource is = new InputSource(stream); + is.setSystemId(systemId); + digester.push(this); + digester.parse(is); + + maybeThrowValidationException(); + } + + /** + * Process the xml file in the default location, and schedule all of the + * jobs defined within it. + * + */ + public void processFileAndScheduleJobs(Scheduler sched, + boolean overWriteExistingJobs) throws SchedulerException, Exception { + processFileAndScheduleJobs(QUARTZ_XML_FILE_NAME, sched, + overWriteExistingJobs); + } + + /** + * Process the xml file in the given location, and schedule all of the + * jobs defined within it. + * + * @param fileName + * meta data file name. + */ + public void processFileAndScheduleJobs(String fileName, Scheduler sched, + boolean overWriteExistingJobs) throws Exception { + processFileAndScheduleJobs(fileName, fileName, sched, overWriteExistingJobs); + } + + /** + * Process the xml file in the given location, and schedule all of the + * jobs defined within it. + * + * @param fileName + * meta data file name. + */ + public void processFileAndScheduleJobs(String fileName, String systemId, + Scheduler sched, boolean overWriteExistingJobs) throws Exception { + schedLocal.set(sched); + try { + processFile(fileName, systemId); + scheduleJobs(getScheduledJobs(), sched, overWriteExistingJobs); + } finally { + schedLocal.set(null); + } + } + + /** + * Add the Jobs and Triggers defined in the given map of JobSchedulingBundle + * s to the given scheduler. + * + * @param jobBundles + * @param sched + * @param overWriteExistingJobs + * @throws Exception + */ + public void scheduleJobs(Map jobBundles, Scheduler sched, + boolean overWriteExistingJobs) throws Exception { + getLog().info("Scheduling " + jobsToSchedule.size() + " parsed jobs."); + + Iterator itr = calsToSchedule.iterator(); + while (itr.hasNext()) { + CalendarBundle bndle = (CalendarBundle) itr.next(); + addCalendar(sched, bndle); + } + + itr = jobsToSchedule.iterator(); + while (itr.hasNext()) { + JobSchedulingBundle bndle = (JobSchedulingBundle) itr.next(); + scheduleJob(bndle, sched, overWriteExistingJobs); + } + + itr = listenersToSchedule.iterator(); + while (itr.hasNext()) { + JobListener listener = (JobListener) itr.next(); + getLog().info("adding listener "+listener.getName()+" of class "+listener.getClass().getName()); + sched.addJobListener(listener); + } + getLog().info(jobBundles.size() + " scheduled jobs."); + } + + /** + * Returns a Map of scheduled jobs. + *

+ * The key is the job name and the value is a JobSchedulingBundle + * containing the JobDetail and Trigger. + * + * @return a Map of scheduled jobs. + */ + public Map getScheduledJobs() { + return Collections.unmodifiableMap(scheduledJobs); + } + + /** + * Returns a JobSchedulingBundle for the job name. + * + * @param name + * job name. + * @return a JobSchedulingBundle for the job name. + */ + public JobSchedulingBundle getScheduledJob(String name) { + return (JobSchedulingBundle) getScheduledJobs().get(name); + } + + /** + * Returns an InputStream from the fileName as a resource. + * + * @param fileName + * file name. + * @return an InputStream from the fileName as a resource. + */ + protected InputStream getInputStream(String fileName) { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + + InputStream is = cl.getResourceAsStream(fileName); + + return is; + } + + /** + * Schedules a given job and trigger (both wrapped by a JobSchedulingBundle). + * + * @param job + * job wrapper. + * @exception SchedulerException + * if the Job or Trigger cannot be added to the Scheduler, or + * there is an internal Scheduler error. + */ + public void scheduleJob(JobSchedulingBundle job) + throws SchedulerException { + scheduleJob(job, (Scheduler) schedLocal.get(), getOverWriteExistingJobs()); + } + + + public void addJobToSchedule(JobSchedulingBundle job) + { + jobsToSchedule.add(job); + } + + public void addCalendarToSchedule(CalendarBundle cal) + { + calsToSchedule.add(cal); + } + + public void addListenerToSchedule(JobListener listener) + { + listenersToSchedule.add(listener); + } + + /** + * Schedules a given job and trigger (both wrapped by a JobSchedulingBundle). + * + * @param job + * job wrapper. + * @param sched + * job scheduler. + * @param localOverWriteExistingJobs + * locally overwrite existing jobs. + * @exception SchedulerException + * if the Job or Trigger cannot be added to the Scheduler, or + * there is an internal Scheduler error. + */ + public void scheduleJob(JobSchedulingBundle job, Scheduler sched, boolean localOverWriteExistingJobs) + throws SchedulerException { + if ((job != null) && job.isValid()) { + JobDetail detail = job.getJobDetail(); + + JobDetail dupeJ = sched.getJobDetail(detail.getName(), detail.getGroup()); + + if ((dupeJ != null) && !localOverWriteExistingJobs) { + getLog().info("Not overwriting existing job: " + dupeJ.getFullName()); + return; + } + + if (dupeJ != null) { + getLog().info("Replacing job: " + detail.getFullName()); + } + else { + getLog().info("Adding job: " + detail.getFullName()); + } + + if (job.getTriggers().size() == 0 && !job.getJobDetail().isDurable()) { + throw new SchedulerException("A Job defined without any triggers must be durable"); + } + sched.addJob(detail, true); + + for (Iterator iter = job.getTriggers().iterator(); iter.hasNext(); ) { + Trigger trigger = (Trigger)iter.next(); + + Trigger dupeT = sched.getTrigger(trigger.getName(), trigger.getGroup()); + + trigger.setJobName(detail.getName()); + trigger.setJobGroup(detail.getGroup()); + + if(trigger.getStartTime() == null) + trigger.setStartTime(new Date()); + + if (dupeT != null) { + getLog().debug( + "Rescheduling job: " + detail.getFullName() + " with updated trigger: " + trigger.getFullName()); + if(!dupeT.getJobGroup().equals(trigger.getJobGroup()) || !dupeT.getJobName().equals(trigger.getJobName())) + getLog().warn("Possibly duplicately named triggers in jobs xml file!"); + sched.rescheduleJob(trigger.getName(), trigger.getGroup(), trigger); + } + else { + getLog().debug( + "Scheduling job: " + detail.getFullName() + " with trigger: " + trigger.getFullName()); + sched.scheduleJob(trigger); + } + } + + addScheduledJob(job); + } + } + + /** + * Adds a scheduled job. + * + * @param job + * job wrapper. + */ + protected void addScheduledJob(JobSchedulingBundle job) { + scheduledJobs.put(job.getFullName(), job); + } + + /** + * Adds a calendar. + * + * @param calendarBundle calendar bundle. + * @throws SchedulerException if the Calendar cannot be added to the Scheduler, or + * there is an internal Scheduler error. + */ + public void addCalendar(Scheduler sched, CalendarBundle calendarBundle) throws SchedulerException { + sched.addCalendar( + calendarBundle.getCalendarName(), + calendarBundle.getCalendar(), + calendarBundle.getReplace(), + true); + } + + /** + * EntityResolver interface. + *

+ * Allow the application to resolve external entities. + *

+ * Until quartz.dtd has a public ID, it must resolved as a + * system ID. Here's the order of resolution (if one fails, continue to the + * next). + *

    + *
  1. Tries to resolve the systemId with ClassLoader.getResourceAsStream(String). + *
  2. + *
  3. If the systemId starts with QUARTZ_SYSTEM_ID_PREFIX, + * then resolve the part after QUARTZ_SYSTEM_ID_PREFIX with + * ClassLoader.getResourceAsStream(String).
  4. + *
  5. Else try to resolve systemId as a URL. + *
  6. If systemId has a colon in it, create a new URL + *
  7. + *
  8. Else resolve systemId as a File and + * then call File.toURL().
  9. + * + *
+ *

+ * If the publicId does exist, resolve it as a URL. If the + * publicId is the Quartz public ID, then resolve it locally. + * + * @param publicId + * The public identifier of the external entity being referenced, + * or null if none was supplied. + * @param systemId + * The system identifier of the external entity being referenced. + * @return An InputSource object describing the new input source, or null + * to request that the parser open a regular URI connection to the + * system identifier. + * @exception SAXException + * Any SAX exception, possibly wrapping another exception. + * @exception IOException + * A Java-specific IO exception, possibly the result of + * creating a new InputStream or Reader for the InputSource. + */ + public InputSource resolveEntity(String publicId, String systemId) { + InputSource inputSource = null; + + InputStream is = null; + + URL url = null; + + try { + if (publicId == null) { + if (systemId != null) { + // resolve Quartz Schema locally + if (QUARTZ_SCHEMA.equals(systemId)) { + is = getClass().getResourceAsStream(QUARTZ_DTD); + } + else { + is = getInputStream(systemId); + + if (is == null) { + int start = systemId.indexOf(QUARTZ_SYSTEM_ID_PREFIX); + + if (start > -1) { + String fileName = systemId + .substring(QUARTZ_SYSTEM_ID_PREFIX.length()); + is = getInputStream(fileName); + } else { + if (systemId.indexOf(':') == -1) { + File file = new java.io.File(systemId); + url = file.toURL(); + } else { + url = new URL(systemId); + } + + is = url.openStream(); + } + } + } + } + } else { + // resolve Quartz DTD locally + if (QUARTZ_PUBLIC_ID.equals(publicId)) { + is = getClass().getResourceAsStream(QUARTZ_DTD); + } + else { + url = new URL(systemId); + is = url.openStream(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (is != null) { + inputSource = new InputSource(is); + inputSource.setPublicId(publicId); + inputSource.setSystemId(systemId); + } + + } + + return inputSource; + } + + /** + * ErrorHandler interface. + * + * Receive notification of a warning. + * + * @param exception + * The error information encapsulated in a SAX parse exception. + * @exception SAXException + * Any SAX exception, possibly wrapping another exception. + */ + public void warning(SAXParseException e) throws SAXException { + addValidationException(e); + } + + /** + * ErrorHandler interface. + * + * Receive notification of a recoverable error. + * + * @param exception + * The error information encapsulated in a SAX parse exception. + * @exception SAXException + * Any SAX exception, possibly wrapping another exception. + */ + public void error(SAXParseException e) throws SAXException { + addValidationException(e); + } + + /** + * ErrorHandler interface. + * + * Receive notification of a non-recoverable error. + * + * @param exception + * The error information encapsulated in a SAX parse exception. + * @exception SAXException + * Any SAX exception, possibly wrapping another exception. + */ + public void fatalError(SAXParseException e) throws SAXException { + addValidationException(e); + } + + /** + * Adds a detected validation exception. + * + * @param SAXException + * SAX exception. + */ + protected void addValidationException(SAXException e) { + validationExceptions.add(e); + } + + /** + * Resets the the number of detected validation exceptions. + */ + protected void clearValidationExceptions() { + validationExceptions.clear(); + } + + /** + * Throws a ValidationException if the number of validationExceptions + * detected is greater than zero. + * + * @exception ValidationException + * DTD validation exception. + */ + protected void maybeThrowValidationException() throws ValidationException { + if (validationExceptions.size() > 0) { + throw new ValidationException(validationExceptions); + } + } + + /** + * RuleSet for common Calendar tags. + * + * @author Chris Bonham + */ + public class CalendarRuleSet extends RuleSetBase { + protected String prefix; + protected String setNextMethodName; + + public CalendarRuleSet(String prefix, String setNextMethodName) { + super(); + this.prefix = prefix; + this.setNextMethodName = setNextMethodName; + } + + public void addRuleInstances(Digester digester) { + digester.addObjectCreate(prefix, CalendarBundle.class); + digester.addSetProperties(prefix, TAG_CLASS_NAME, "className"); + digester.addBeanPropertySetter(prefix + "/" + TAG_NAME, "calendarName"); + digester.addBeanPropertySetter(prefix + "/" + TAG_DESCRIPTION, "description"); + digester.addSetNext(prefix, setNextMethodName); + } + } + + /** + * RuleSet for common Trigger tags. + * + * @author Chris Bonham + */ + public class TriggerRuleSet extends RuleSetBase { + protected String prefix; + protected Class clazz; + + public TriggerRuleSet(String prefix, Class clazz) { + super(); + this.prefix = prefix; + if (!Trigger.class.isAssignableFrom(clazz)) { + throw new IllegalArgumentException("Class must be an instance of Trigger"); + } + this.clazz = clazz; + } + + public void addRuleInstances(Digester digester) { + digester.addObjectCreate(prefix, clazz); + digester.addBeanPropertySetter(prefix + "/" + TAG_NAME, "name"); + digester.addBeanPropertySetter(prefix + "/" + TAG_GROUP, "group"); + digester.addBeanPropertySetter(prefix + "/" + TAG_DESCRIPTION, "description"); + digester.addBeanPropertySetter(prefix + "/" + TAG_VOLATILITY, "volatility"); + digester.addRule(prefix + "/" + TAG_MISFIRE_INSTRUCTION, new MisfireInstructionRule("misfireInstruction")); + digester.addBeanPropertySetter(prefix + "/" + TAG_CALENDAR_NAME, "calendarName"); + digester.addBeanPropertySetter(prefix + "/" + TAG_JOB_NAME, "jobName"); + digester.addBeanPropertySetter(prefix + "/" + TAG_JOB_GROUP, "jobGroup"); + Converter converter = new DateConverter(new String[] { XSD_DATE_FORMAT, DTD_DATE_FORMAT }); + digester.addRule(prefix + "/" + TAG_START_TIME, new SimpleConverterRule("startTime", converter, Date.class)); + digester.addRule(prefix + "/" + TAG_END_TIME, new SimpleConverterRule("endTime", converter, Date.class)); + } + } + + /** + * This rule is needed to fix QUARTZ-153. + *

+ * Since the Jakarta Commons BeanUtils 1.6.x ConvertUtils class uses static utility + * methods, the DateConverter and TimeZoneConverter were + * overriding any previously registered converters for java.util.Date and + * java.util.TimeZone. + *

+ * Jakarta Commons BeanUtils 1.7.x fixes this issue by internally using per-context-classloader + * pseudo-singletons (see + * http://jakarta.apache.org/commons/beanutils/commons-beanutils-1.7.0/RELEASE-NOTES.txt). + * This ensures web applications in the same JVM are using independent converters + * based on their classloaders. However, the environment for QUARTZ-153 started Quartz + * using the QuartzInitializationServlet which started JobInitializationPlugin. + * In this case, the web classloader instances would be the same. + *

+ * To make sure the converters aren't overridden by the JobSchedulingDataProcessor, + * it's easier to just override BeanPropertySetterRule.end() to convert the + * body text to the specified class using the specified converter. + * + * @author Chris Bonham + */ + public class SimpleConverterRule extends BeanPropertySetterRule { + private Converter converter; + private Class clazz; + + /** + *

Construct rule that sets the given property from the body text.

+ * + * @param propertyName name of property to set + * @param converter converter to use + * @param clazz class to convert to + */ + public SimpleConverterRule(String propertyName, Converter converter, Class clazz) { + this.propertyName = propertyName; + if (converter == null) { + throw new IllegalArgumentException("Converter must not be null"); + } + this.converter = converter; + if (clazz == null) { + throw new IllegalArgumentException("Class must not be null"); + } + this.clazz = clazz; + } + + /** + * Process the end of this element. + * + * @param namespace the namespace URI of the matching element, or an + * empty string if the parser is not namespace aware or the element has + * no namespace + * @param name the local name if the parser is namespace aware, or just + * the element name otherwise + * + * @exception NoSuchMethodException if the bean does not + * have a writeable property of the specified name + */ + public void end(String namespace, String name) throws Exception { + + String property = propertyName; + + if (property == null) { + // If we don't have a specific property name, + // use the element name. + property = name; + } + + // Get a reference to the top object + Object top = this.digester.peek(); + + // log some debugging information + if (getDigester().getLogger().isDebugEnabled()) { + getDigester().getLogger().debug("[BeanPropertySetterRule]{" + getDigester().getMatch() + + "} Set " + top.getClass().getName() + " property " + + property + " with text " + bodyText); + } + + // Force an exception if the property does not exist + // (BeanUtils.setProperty() silently returns in this case) + if (top instanceof DynaBean) { + DynaProperty desc = + ((DynaBean) top).getDynaClass().getDynaProperty(property); + if (desc == null) { + throw new NoSuchMethodException + ("Bean has no property named " + property); + } + } else /* this is a standard JavaBean */ { + PropertyDescriptor desc = + PropertyUtils.getPropertyDescriptor(top, property); + if (desc == null) { + throw new NoSuchMethodException + ("Bean has no property named " + property); + } + } + + // Set the property only using this converter + Object value = converter.convert(clazz, bodyText); + PropertyUtils.setProperty(top, property, value); + } + } + + /** + * This rule translates the trigger misfire instruction constant name into its + * corresponding value. + * + * @TODO Consider removing this class and using a + * org.apache.commons.digester.Substitutor strategy once + * Jakarta Commons Digester 1.6 is final. + * + * @author Chris Bonham + */ + public class MisfireInstructionRule extends BeanPropertySetterRule { + /** + *

Construct rule that sets the given property from the body text.

+ * + * @param propertyName name of property to set + */ + public MisfireInstructionRule(String propertyName) { + this.propertyName = propertyName; + } + + /** + * Process the body text of this element. + * + * @param namespace the namespace URI of the matching element, or an + * empty string if the parser is not namespace aware or the element has + * no namespace + * @param name the local name if the parser is namespace aware, or just + * the element name otherwise + * @param text The text of the body of this element + */ + public void body(String namespace, String name, String text) + throws Exception { + super.body(namespace, name, text); + this.bodyText = getConstantValue(bodyText); + } + + /** + * Returns the value for the constant name. + * If the constant can't be found or any exceptions occur, + * return 0. + * + * @param constantName constant name. + * @return the value for the constant name. + */ + private String getConstantValue(String constantName) { + String value = "0"; + + Object top = this.digester.peek(); + if (top != null) { + Class clazz = top.getClass(); + try { + java.lang.reflect.Field field = clazz.getField(constantName); + Object fieldValue = field.get(top); + if (fieldValue != null) { + value = fieldValue.toString(); + } + } + catch (Exception e) { + // ignore + } + } + + return value; + } + } + + /** + *

Standard {@link Converter} implementation that converts an incoming + * String into a java.util.Date object, optionally using a + * default value or throwing a {@link ConversionException} if a conversion + * error occurs.

+ */ + public final class DateConverter implements Converter { + + // ----------------------------------------------------------- Constructors + + /** + * Create a {@link Converter} that will throw a {@link ConversionException} + * if a conversion error occurs. + */ + public DateConverter() { + this.defaultValue = null; + this.useDefault = false; + } + + /** + * Create a {@link Converter} that will return the specified default value + * if a conversion error occurs. + * + * @param defaultValue The default value to be returned + */ + public DateConverter(Object defaultValue) { + this.defaultValue = defaultValue; + this.useDefault = true; + } + + public DateConverter(String[] formats) { + this(); + + int len = formats.length; + dateFormats = new DateFormat[len]; + for (int i = 0; i < len; i++) { + dateFormats[i] = new SimpleDateFormat(formats[i]); + } + } + + // ----------------------------------------------------- Instance Variables + + /** + * The default value specified to our Constructor, if any. + */ + private Object defaultValue = null; + + /** + * Should we return the default value on conversion errors? + */ + private boolean useDefault = true; + + private DateFormat[] dateFormats; + + // --------------------------------------------------------- Public Methods + + /** + * Convert the specified input object into an output object of the + * specified type. + * + * @param type Data type to which this value should be converted + * @param value The input value to be converted + * + * @exception ConversionException if conversion cannot be performed + * successfully + */ + public Object convert(Class type, Object value) { + + if (value == null) { + if (useDefault) { + return (defaultValue); + } + else { + return (null); + } + } + + if (String.class.equals(type)) { + if ((value instanceof Date) && (dateFormats != null)) { + return (dateFormats[0].format((Date) value)); + } + else { + return (value.toString()); + } + } + + if (value instanceof Date) { + return (value); + } + + try { + if (Date.class.isAssignableFrom(type) && dateFormats != null) { + return parseDate(value); + } + else { + return (value.toString()); + } + } + catch (Exception e) { + if (useDefault) { + return (defaultValue); + } + else { + throw new ConversionException(e); + } + } + } + + protected Date parseDate(Object value) throws ParseException { + Date date = null; + + int len = dateFormats.length; + for (int i = 0; i < len; i++) { + + try { + date = (dateFormats[i].parse(value.toString())); + break; + } + catch (ParseException e) { + // if this is the last format, throw the exception + if (i == (len - 1)) { + throw e; + } + } + } + + return date; + } + } + + /** + *

Standard {@link Converter} implementation that converts an incoming + * String into a java.util.TimeZone object throwing a + * {@link ConversionException} if a conversion error occurs.

+ */ + public final class TimeZoneConverter implements Converter { + // ----------------------------------------------------------- Constructors + + /** + * Create a {@link Converter} that will throw a {@link ConversionException} + * if a conversion error occurs. + */ + public TimeZoneConverter() { + } + + // --------------------------------------------------------- Public Methods + + /** + * Convert the specified input object into an output object of the + * specified type. + * + * @param type Data type to which this value should be converted + * @param value The input value to be converted + * + * @exception ConversionException if conversion cannot be performed + * successfully + */ + public Object convert(Class type, Object value) { + + if (value == null) { + return (null); + } + + if (value instanceof TimeZone) { + return (value); + } + + try { + if (String.class.equals(value.getClass())) { + return (TimeZone.getTimeZone((String) value)); + } + else { + return (value.toString()); + } + } + catch (Exception e) { + throw new ConversionException(e); + } + } + } +} Index: 3rdParty_sources/quartz/org/quartz/xml/ValidationException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/xml/ValidationException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/xml/ValidationException.java 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,124 @@ +/* + * Copyright 2004-2005 OpenSymphony + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + */ + +/* + * Previously Copyright (c) 2001-2004 James House + */ +package org.quartz.xml; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; + +/** + * Reports QuartzMetaDataProcessor validation exceptions. + * + * @author Chris Bonham + */ +public class ValidationException extends Exception { + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Data members. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + private Collection validationExceptions = new ArrayList(); + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Constructors. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Constructor for ValidationException. + */ + public ValidationException() { + super(); + } + + /** + * Constructor for ValidationException. + * + * @param message + * exception message. + */ + public ValidationException(String message) { + super(message); + } + + /** + * Constructor for ValidationException. + * + * @param validationExceptions + * collection of validation exceptions. + */ + public ValidationException(Collection errors) { + this(); + this.validationExceptions = Collections + .unmodifiableCollection(validationExceptions); + } + + /* + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Interface. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + */ + + /** + * Returns collection of errors. + * + * @return collection of errors. + */ + public Collection getValidationExceptions() { + return validationExceptions; + } + + /** + * Returns the detail message string. + * + * @return the detail message string. + */ + public String getMessage() { + if (getValidationExceptions().size() == 0) { return super.getMessage(); } + + StringBuffer sb = new StringBuffer(); + + boolean first = true; + + for (Iterator iter = getValidationExceptions().iterator(); iter + .hasNext(); ) { + Exception e = (Exception) iter.next(); + + if (!first) { + sb.append('\n'); + first = false; + } + + sb.append(e.getMessage()); + } + + return sb.toString(); + } +} Index: 3rdParty_sources/quartz/org/quartz/xml/job_scheduling_data_1_5.dtd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/xml/job_scheduling_data_1_5.dtd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/xml/job_scheduling_data_1_5.dtd 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,172 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: 3rdParty_sources/quartz/org/quartz/xml/job_scheduling_data_1_5.xsd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/quartz/org/quartz/xml/job_scheduling_data_1_5.xsd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/quartz/org/quartz/xml/job_scheduling_data_1_5.xsd 17 Aug 2012 15:10:21 -0000 1.1 @@ -0,0 +1,388 @@ + + + + + + Copyright (c) 2004-2005 by OpenSymphony + All rights reserved. + + Previously Copyright (c) 2001-2004 James House + + And Previously Copyright Third Eye Consulting, Inc. (c) 2004 + + + + + + ... + + + The instance documents may indicate the published version of + the schema using the xsi:schemaLocation attribute for the Quartz + namespace with the following location: + + http://www.opensymphony.com/quartz/xml/job_scheduling_data_1_5.xsd + ]]> + + + + Root level node + + + + + + + + + + Version of the XML Schema instance + + + + + Whether the existing jobs will be overwritten. + + + + + + + Define a Job Listener + + + + Job Listener class name + + + + + logical name for listener + + + + + + Define a Calendar + + + + + + + + + Calendar class name + + + + + Flag to replace existing calendar + + + + + + Define a Job + + + + + + + + + Define a JobDetail + + + + + + + + + + + + + + + + + + Name of the JobDetail or Trigger + + + + + Group in which the JobDetail or Trigger resides + + + + + Fully qualified name of the Job class + + + + + logical name of the Job Listener + + + + + Whether the Job is volatile + + + + + Whether the Job is durable + + + + + Whether the Job is recoverable + + + + + Define a JobDataMap + + + + + + + Whether the JobDataMap allows transient data. + + + + + + Define a JobDataMap entry + + + + + + + + + Define a JobDataMap key + + + + + Define a JobDataMap value + + + + + Define a Trigger + + + + + + + + + Common Trigger definitions + + + + + + + + + + + + + Define a Trigger Misfire Instruction + + + + + + + + + + + + + + Define a Trigger Calendar name + + + + + Define a SimpleTrigger + + + + + + + + + + + + + + + + + + + + + + + Name of the Job + + + + + Group in which the Job resides + + + + + Start time of the job + + + + + End time of the job + + + + + Number of times to repeat the Trigger (-1 for indefinite) + + + + + + + + Time interval (in milliseconds) at which the Trigger should repeat + + + + + Define a CronTrigger + + + + + + + + + + + + + + + + + + + + + + + + Cron expression (see JavaDoc for examples) + + Special thanks to Chris Thatcher (thatcher@butterfly.net) for the regular expression! + + Regular expressions are not my strong point but I believe this is complete, + with the caveat that order for expressions like 3-0 is not legal but will pass, + and month and day names must be capitalized. + If you want to examine the correctness look for the [\s] to denote the + seperation of individual regular expressions. This is how I break them up visually + to examine them: + + SECONDS: + ( + ((([0-9] | [0-5][0-9]),)*([0-9]|[0-5][0-9])) + | (([0-9]|[0-5][0-9])(/|-)([0-9]|[0-5][0-9])) + | ([\?]) + | ([\*]) + ) [\s] + MINUTES: + ( + ((([0-9] | [0-5][0-9]),)*([0-9]|[0-5][0-9])) + | (([0-9]|[0-5][0-9])(/|-)([0-9]|[0-5][0-9])) + | ([\?]) + | ([\*]) + ) [\s] + HOURS: + ( + ((([0-9]|[0-1][0-9]|[2][0-3]),)*([0-9]|[0-1][0-9]|[2][0-3])) + | (([0-9]|[0-1][0-9]|[2][0-3])(/|-)([0-9]|[0-1][0-9]|[2][0-3])) + | ([\?]) + | ([\*]) + ) [\s] + DAY OF MONTH: + ( + ((([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1]),)*([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])(C)?) + | (([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])(/|-)([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])(C)?) + | (L) + | ([\?]) + | ([\*]) + )[\s] + MONTH: + ( + ((([1-9]|0[1-9]|1[0-2]),)*([1-9]|0[1-9]|1[0-2])) + | (([1-9]|0[1-9]|1[0-2])(/|-)([1-9]|0[1-9]|1[0-2])) + | (((JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC),)*(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)) + | ((JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(-|/)(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)) + | ([\?]) + | ([\*]) + )[\s] + DAY OF WEEK: + ( + (([1-7],)*([1-7])) + | ([1-7](/|-)([1-7])) + | (((MON|TUE|WED|THU|FRI|SAT|SUN),)*(MON|TUE|WED|THU|FRI|SAT|SUN)(C)?) + | ((MON|TUE|WED|THU|FRI|SAT|SUN)(-|/)(MON|TUE|WED|THU|FRI|SAT|SUN)(C)?) + | (([1-7]|(MON|TUE|WED|THU|FRI|SAT|SUN))(L)?) + | ([1-7]#([1-7])?) + | ([\?]) + | ([\*]) + ) + YEAR (OPTIONAL): + ([\s]19[7-9][0-9]|20[0-9]{2})? + + + + + + + + + Valid java.util.Timezone ID + + + Index: 3rdParty_sources/spring/org/springframework/aop/Advisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/Advisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/Advisor.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import org.aopalliance.aop.Advice; + +/** + * Base interface holding AOP advice (action to take at a joinpoint) + * and a filter determining the applicability of the advice (such as + * a pointcut). This interface is not for use by Spring users, but to + * allow for commonality in support for different types of advice. + * + *

Spring AOP is based around around advice delivered via method + * interception, compliant with the AOP Alliance interception API. + * The Advisor interface allows support for different types of advice, + * such as before and after advice, which need not be + * implemented using interception. + * + * @author Rod Johnson + */ +public interface Advisor { + + /** + * Return the advice part of this aspect. An advice may be an + * interceptor, a before advice, a throws advice, etc. + * @return the advice that should apply if the pointcut matches + * @see org.aopalliance.intercept.MethodInterceptor + * @see BeforeAdvice + * @see ThrowsAdvice + * @see AfterReturningAdvice + */ + Advice getAdvice(); + + /** + * Return whether this advice is associated with a particular instance + * (for example, creating a mixin) or shared with all instances of + * the advised class obtained from the same Spring bean factory. + *

Note that this method is not currently used by the framework. + * Typical Advisor implementations always return true. + * Use singleton/prototype bean definitions or appropriate programmatic + * proxy creation to ensure that Advisors have the correct lifecycle model. + * @return whether this advice is associated with a particular target instance + */ + boolean isPerInstance(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/AfterAdvice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/AfterAdvice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/AfterAdvice.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import org.aopalliance.aop.Advice; + +/** + * Common marker interface for after advice, + * such as {@link AfterReturningAdvice} and {@link ThrowsAdvice}. + * + * @author Juergen Hoeller + * @since 2.0.3 + * @see BeforeAdvice + */ +public interface AfterAdvice extends Advice { + +} Index: 3rdParty_sources/spring/org/springframework/aop/AfterReturningAdvice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/AfterReturningAdvice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/AfterReturningAdvice.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import java.lang.reflect.Method; + +/** + * After returning advice is invoked only on normal method return, not if an + * exception is thrown. Such advice can see the return value, but cannot change it. + * + * @author Rod Johnson + * @see MethodBeforeAdvice + * @see ThrowsAdvice + */ +public interface AfterReturningAdvice extends AfterAdvice { + + /** + * Callback after a given method successfully returned. + * @param returnValue the value returned by the method, if any + * @param method method being invoked + * @param args arguments to the method + * @param target target of the method invocation. May be null. + * @throws Throwable if this object wishes to abort the call. + * Any exception thrown will be returned to the caller if it's + * allowed by the method signature. Otherwise the exception + * will be wrapped as a runtime exception. + */ + void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable; + +} Index: 3rdParty_sources/spring/org/springframework/aop/AopInvocationException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/AopInvocationException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/AopInvocationException.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import org.springframework.core.NestedRuntimeException; + +/** + * Exception that gets thrown when an AOP invocation failed + * because of misconfiguration or unexpected runtime issues. + * + * @author Juergen Hoeller + * @since 2.0 + */ +public class AopInvocationException extends NestedRuntimeException { + + /** + * Constructor for AopInvocationException. + * @param msg the detail message + */ + public AopInvocationException(String msg) { + super(msg); + } + + /** + * Constructor for AopInvocationException. + * @param msg the detail message + * @param cause the root cause + */ + public AopInvocationException(String msg, Throwable cause) { + super(msg, cause); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/BeforeAdvice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/BeforeAdvice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/BeforeAdvice.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,32 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import org.aopalliance.aop.Advice; + +/** + * Common marker interface for before advice, such as {@link MethodBeforeAdvice}. + * + *

Spring supports only method before advice. Although this is unlikely to change, + * this API is designed to allow field advice in future if desired. + * + * @author Rod Johnson + * @see AfterAdvice + */ +public interface BeforeAdvice extends Advice { + +} Index: 3rdParty_sources/spring/org/springframework/aop/ClassFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/ClassFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/ClassFilter.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +/** + * Filter that restricts matching of a pointcut or introduction to + * a given set of target classes. + * + *

Can be used as part of a {@link Pointcut} or for the entire + * targeting of an {@link IntroductionAdvisor}. + * + * @author Rod Johnson + * @see Pointcut + * @see MethodMatcher + */ +public interface ClassFilter { + + /** + * Should the pointcut apply to the given interface or target class? + * @param clazz the candidate target class + * @return whether the advice should apply to the given target class + */ + boolean matches(Class clazz); + + + /** + * Canonical instance of a ClassFilter that matches all classes. + */ + ClassFilter TRUE = TrueClassFilter.INSTANCE; + +} Index: 3rdParty_sources/spring/org/springframework/aop/DynamicIntroductionAdvice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/DynamicIntroductionAdvice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/DynamicIntroductionAdvice.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import org.aopalliance.aop.Advice; + +/** + * Subinterface of AOP Alliance Advice that allows additional interfaces + * to be implemented by an Advice, and available via a proxy using that + * interceptor. This is a fundamental AOP concept called introduction. + * + *

Introductions are often mixins, enabling the building of composite + * objects that can achieve many of the goals of multiple inheritance in Java. + * + *

Compared to {qlink IntroductionInfo}, this interface allows an advice to + * implement a range of interfaces that is not necessarily known in advance. + * Thus an {@link IntroductionAdvisor} can be used to specify which interfaces + * will be exposed in an advised object. + * + * @author Rod Johnson + * @since 1.1.1 + * @see IntroductionInfo + * @see IntroductionAdvisor + */ +public interface DynamicIntroductionAdvice extends Advice { + + /** + * Does this introduction advice implement the given interface? + * @param intf the interface to check + * @return whether the advice implements the specified interface + */ + boolean implementsInterface(Class intf); + +} Index: 3rdParty_sources/spring/org/springframework/aop/IntroductionAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/IntroductionAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/IntroductionAdvisor.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +/** + * Superinterface for advisors that perform one or more AOP introductions. + * + *

This interface cannot be implemented directly; subinterfaces must + * provide the advice type implementing the introduction. + * + *

Introduction is the implementation of additional interfaces + * (not implemented by a target) via AOP advice. + * + * @author Rod Johnson + * @since 04.04.2003 + * @see IntroductionInterceptor + */ +public interface IntroductionAdvisor extends Advisor, IntroductionInfo { + + /** + * Return the filter determining which target classes this introduction + * should apply to. + *

This represents the class part of a pointcut. Note that method + * matching doesn't make sense to introductions. + * @return the class filter + */ + ClassFilter getClassFilter(); + + /** + * Can the advised interfaces be implemented by the introduction advice? + * Invoked before adding an IntroductionAdvisor. + * @throws IllegalArgumentException if the advised interfaces can't be + * implemented by the introduction advice + */ + void validateInterfaces() throws IllegalArgumentException; + +} Index: 3rdParty_sources/spring/org/springframework/aop/IntroductionAwareMethodMatcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/IntroductionAwareMethodMatcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/IntroductionAwareMethodMatcher.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import java.lang.reflect.Method; + +/** + * A specialized type of MethodMatcher that takes into account introductions when + * matching methods. If there are no introductions on the target class, a method + * matcher may be able to optimize matching more effectively for example. + * + * @author Adrian Colyer + * @since 2.0 + */ +public interface IntroductionAwareMethodMatcher extends MethodMatcher { + + /** + * Perform static checking whether the given method matches. This may be invoked + * instead of the 2-arg {@link #matches(java.lang.reflect.Method, Class)} method + * if the caller supports the extended IntroductionAwareMethodMatcher interface. + * @param method the candidate method + * @param targetClass the target class (may be null, in which case + * the candidate class must be taken to be the method's declaring class) + * @param hasIntroductions true if the object on whose behalf we are + * asking is the subject on one or more introductions; false otherwise + * @return whether or not this method matches statically + */ + boolean matches(Method method, Class targetClass, boolean hasIntroductions); + +} Index: 3rdParty_sources/spring/org/springframework/aop/IntroductionInfo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/IntroductionInfo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/IntroductionInfo.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +/** + * Interface supplying the information necessary to describe an introduction. + * + *

{@link IntroductionAdvisor IntroductionAdvisors} must implement this + * interface. If an {@link org.aopalliance.aop.Advice} implements this, + * it may be used as an introduction without an {@link IntroductionAdvisor}. + * In this case, the advice is self-describing, providing not only the + * necessary behavior, but describing the interfaces it introduces. + * + * @author Rod Johnson + * @since 1.1.1 + */ +public interface IntroductionInfo { + + /** + * Return the additional interfaces introduced by this Advisor or Advice. + * @return the introduced interfaces + */ + Class[] getInterfaces(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/IntroductionInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/IntroductionInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/IntroductionInterceptor.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import org.aopalliance.intercept.MethodInterceptor; + +/** + * Subinterface of AOP Alliance MethodInterceptor that allows additional interfaces + * to be implemented by the interceptor, and available via a proxy using that + * interceptor. This is a fundamental AOP concept called introduction. + * + *

Introductions are often mixins, enabling the building of composite + * objects that can achieve many of the goals of multiple inheritance in Java. + * + * @author Rod Johnson + * @see DynamicIntroductionAdvice + */ +public interface IntroductionInterceptor extends MethodInterceptor, DynamicIntroductionAdvice { + +} Index: 3rdParty_sources/spring/org/springframework/aop/MethodBeforeAdvice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/MethodBeforeAdvice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/MethodBeforeAdvice.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import java.lang.reflect.Method; + +/** + * Advice invoked before a method is invoked. Such advices cannot + * prevent the method call proceeding, unless they throw a Throwable. + * + * @see AfterReturningAdvice + * @see ThrowsAdvice + * + * @author Rod Johnson + */ +public interface MethodBeforeAdvice extends BeforeAdvice { + + /** + * Callback before a given method is invoked. + * @param method method being invoked + * @param args arguments to the method + * @param target target of the method invocation. May be null. + * @throws Throwable if this object wishes to abort the call. + * Any exception thrown will be returned to the caller if it's + * allowed by the method signature. Otherwise the exception + * will be wrapped as a runtime exception. + */ + void before(Method method, Object[] args, Object target) throws Throwable; + +} Index: 3rdParty_sources/spring/org/springframework/aop/MethodMatcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/MethodMatcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/MethodMatcher.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,97 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import java.lang.reflect.Method; + +/** + * Part of a {@link Pointcut}: Checks whether the target method is eligible for advice. + * + *

A MethodMatcher may be evaluated statically or at runtime (dynamically). + * Static matching involves method and (possibly) method attributes. Dynamic matching + * also makes arguments for a particular call available, and any effects of running + * previous advice applying to the joinpoint. + * + *

If an implementation returns false from its {@link #isRuntime()} + * method, evaluation can be performed statically, and the result will be the same + * for all invocations of this method, whatever their arguments. This means that + * if the {@link #isRuntime()} method returns false, the 3-arg + * {@link #matches(java.lang.reflect.Method, Class, Object[])} method will never be invoked. + * + *

If an implementation returns true from its 2-arg + * {@link #matches(java.lang.reflect.Method, Class)} method and its {@link #isRuntime()} method + * returns true, the 3-arg {@link #matches(java.lang.reflect.Method, Class, Object[])} + * method will be invoked immediately before each potential execution of the related advice, + * to decide whether the advice should run. All previous advice, such as earlier interceptors + * in an interceptor chain, will have run, so any state changes they have produced in + * parameters or ThreadLocal state will be available at the time of evaluation. + * + * @author Rod Johnson + * @since 11.11.2003 + * @see Pointcut + * @see ClassFilter + */ +public interface MethodMatcher { + + /** + * Perform static checking whether the given method matches. If this + * returns false or if the {@link #isRuntime()} method + * returns false, no runtime check (i.e. no. + * {@link #matches(java.lang.reflect.Method, Class, Object[])} call) will be made. + * @param method the candidate method + * @param targetClass the target class (may be null, in which case + * the candidate class must be taken to be the method's declaring class) + * @return whether or not this method matches statically + */ + boolean matches(Method method, Class targetClass); + + /** + * Is this MethodMatcher dynamic, that is, must a final call be made on the + * {@link #matches(java.lang.reflect.Method, Class, Object[])} method at + * runtime even if the 2-arg matches method returns true? + *

Can be invoked when an AOP proxy is created, and need not be invoked + * again before each method invocation, + * @return whether or not a runtime match via the 3-arg + * {@link #matches(java.lang.reflect.Method, Class, Object[])} method + * is required if static matching passed + */ + boolean isRuntime(); + + /** + * Check whether there a runtime (dynamic) match for this method, + * which must have matched statically. + *

This method is invoked only if the 2-arg matches method returns + * true for the given method and target class, and if the + * {@link #isRuntime()} method returns true. Invoked + * immediately before potential running of the advice, after any + * advice earlier in the advice chain has run. + * @param method the candidate method + * @param targetClass the target class (may be null, in which case + * the candidate class must be taken to be the method's declaring class) + * @param args arguments to the method + * @return whether there's a runtime match + * @see MethodMatcher#matches(Method, Class) + */ + boolean matches(Method method, Class targetClass, Object[] args); + + + /** + * Canonical instance that matches all methods. + */ + MethodMatcher TRUE = TrueMethodMatcher.INSTANCE; + +} Index: 3rdParty_sources/spring/org/springframework/aop/Pointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/Pointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/Pointcut.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +/** + * Core Spring pointcut abstraction. + * + *

A pointcut is composed of a {@link ClassFilter} and a {@link MethodMatcher}. + * Both these basic terms and a Pointcut itself can be combined to build up combinations + * (e.g. through {@link org.springframework.aop.support.ComposablePointcut}). + * + * @author Rod Johnson + * @see ClassFilter + * @see MethodMatcher + * @see org.springframework.aop.support.Pointcuts + * @see org.springframework.aop.support.ClassFilters + * @see org.springframework.aop.support.MethodMatchers + */ +public interface Pointcut { + + /** + * Return the ClassFilter for this pointcut. + * @return the ClassFilter (never null) + */ + ClassFilter getClassFilter(); + + /** + * Return the MethodMatcher for this pointcut. + * @return the MethodMatcher (never null) + */ + MethodMatcher getMethodMatcher(); + + + /** + * Canonical Pointcut instance that always matches. + */ + Pointcut TRUE = TruePointcut.INSTANCE; + +} Index: 3rdParty_sources/spring/org/springframework/aop/PointcutAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/PointcutAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/PointcutAdvisor.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +/** + * Superinterface for all Advisors that are driven by a pointcut. + * This covers nearly all advisors except introduction advisors, + * for which method-level matching doesn't apply. + * + * @author Rod Johnson + */ +public interface PointcutAdvisor extends Advisor { + + /** + * Get the Pointcut that drives this advisor. + */ + Pointcut getPointcut(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/ProxyMethodInvocation.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/ProxyMethodInvocation.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/ProxyMethodInvocation.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,86 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import org.aopalliance.intercept.MethodInvocation; + +/** + * Extension of the AOP Alliance {@link org.aopalliance.intercept.MethodInvocation} + * interface, allowing access to the proxy that the method invocation was made through. + * + *

Useful to be able to substitute return values with the proxy, + * if necessary, for example if the invocation target returned itself. + * + * @author Juergen Hoeller + * @author Adrian Colyer + * @since 1.1.3 + * @see org.springframework.aop.framework.ReflectiveMethodInvocation + * @see org.springframework.aop.support.DelegatingIntroductionInterceptor + */ +public interface ProxyMethodInvocation extends MethodInvocation { + + /** + * Return the proxy that this method invocation was made through. + * @return the original proxy object + */ + Object getProxy(); + + /** + * Create a clone of this object. If cloning is done before proceed() + * is invoked on this object, proceed() can be invoked once per clone + * to invoke the joinpoint (and the rest of the advice chain) more than once. + * @return an invocable clone of this invocation. + * proceed() can be called once per clone. + */ + MethodInvocation invocableClone(); + + /** + * Create a clone of this object. If cloning is done before proceed() + * is invoked on this object, proceed() can be invoked once per clone + * to invoke the joinpoint (and the rest of the advice chain) more than once. + * @param arguments the arguments that the cloned invocation is supposed to use, + * overriding the original arguments + * @return an invocable clone of this invocation. + * proceed() can be called once per clone. + */ + MethodInvocation invocableClone(Object[] arguments); + + /** + * Set the arguments to be used on subsequent invocations in the any advice + * in this chain. + * @param arguments the argument array + */ + void setArguments(Object[] arguments); + + /** + * Add the specified user attribute with the given value to this invocation. + *

Such attributes are not used within the AOP framework itself. They are + * just kept as part of the invocation object, for use in special interceptors. + * @param key the name of the attribute + * @param value the value of the attribute, or null to reset it + */ + void setUserAttribute(String key, Object value); + + /** + * Return the value of the specified user attribute. + * @param key the name of the attribute + * @return the value of the attribute, or null if not set + * @see #setUserAttribute + */ + Object getUserAttribute(String key); + +} Index: 3rdParty_sources/spring/org/springframework/aop/RawTargetAccess.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/RawTargetAccess.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/RawTargetAccess.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +/** + * Marker for AOP proxy interfaces (in particular: introduction interfaces) + * that explicitly intend to return the raw target object (which would normally + * get replaced with the proxy object when returned from a method invocation). + * + *

Note that this is a marker interface in the style of {@link java.io.Serializable}, + * semantically applying to a declared interface rather than to the full class + * of a concrete object. In other words, this marker applies to a particular + * interface only (typically an introduction interface that does not serve + * as the primary interface of an AOP proxy), and hence does not affect + * other interfaces that a concrete AOP proxy may implement. + * + * @author Juergen Hoeller + * @since 2.0.5 + * @see org.springframework.aop.scope.ScopedObject + */ +public interface RawTargetAccess { + +} Index: 3rdParty_sources/spring/org/springframework/aop/SpringProxy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/SpringProxy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/SpringProxy.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +/** + * Marker interface implemented by all AOP proxies. Used to detect + * whether or not objects are Spring-generated proxies. + * + * @author Rob Harrop + * @since 2.0.1 + * @see org.springframework.aop.support.AopUtils#isAopProxy(Object) + */ +public interface SpringProxy { + +} Index: 3rdParty_sources/spring/org/springframework/aop/TargetClassAware.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/TargetClassAware.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/TargetClassAware.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +/** + * Minimal interface for exposing the target class behind a proxy. + * + *

Implemented by AOP proxy objects and proxy factories + * (via {@link org.springframework.aop.framework.Advised}} + * as well as by {@link TargetSource TargetSources}. + * + * @author Juergen Hoeller + * @since 2.0.3 + * @see org.springframework.aop.support.AopUtils#getTargetClass(Object) + */ +public interface TargetClassAware { + + /** + * Return the target class behind the implementing object + * (typically a proxy configuration or an actual proxy). + * @return the target Class, or null if not known + */ + Class getTargetClass(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/TargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/TargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/TargetSource.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,70 @@ +/*< + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +/** + * A TargetSource is used to obtain the current "target" of + * an AOP invocation, which will be invoked via reflection if no around + * advice chooses to end the interceptor chain itself. + * + *

If a TargetSource is "static", it will always return + * the same target, allowing optimizations in the AOP framework. Dynamic + * target sources can support pooling, hot swapping, etc. + * + *

Application developers don't usually need to work with + * TargetSources directly: this is an AOP framework interface. + * + * @author Rod Johnson + */ +public interface TargetSource extends TargetClassAware { + + /** + * Return the type of targets returned by this {@link TargetSource}. + *

Can return null, although certain usages of a + * TargetSource might just work with a predetermined + * target class. + * @return the type of targets returned by this {@link TargetSource} + */ + Class getTargetClass(); + + /** + * Will all calls to {@link #getTarget()} return the same object? + *

In that case, there will be no need to invoke + * {@link #releaseTarget(Object)}, and the AOP framework can cache + * the return value of {@link #getTarget()}. + * @return true if the target is immutable + * @see #getTarget + */ + boolean isStatic(); + + /** + * Return a target instance. Invoked immediately before the + * AOP framework calls the "target" of an AOP method invocation. + * @return the target object, which contains the joinpoint + * @throws Exception if the target object can't be resolved + */ + Object getTarget() throws Exception; + + /** + * Release the given target object obtained from the + * {@link #getTarget()} method. + * @param target object obtained from a call to {@link #getTarget()} + * @throws Exception if the object can't be released + */ + void releaseTarget(Object target) throws Exception; + +} Index: 3rdParty_sources/spring/org/springframework/aop/ThrowsAdvice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/ThrowsAdvice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/ThrowsAdvice.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +/** + * Tag interface for throws advice. + * + *

There are not any methods on this interface, as methods are invoked by + * reflection. Implementing classes must implement methods of the form: + * + *

void afterThrowing([Method, args, target], ThrowableSubclass);
+ * + *

Some examples of valid methods would be: + * + *

public void afterThrowing(Exception ex)
+ *
public void afterThrowing(RemoteException)
+ *
public void afterThrowing(Method method, Object[] args, Object target, Exception ex)
+ *
public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)
+ * + * The first three arguments are optional, and only useful if we want further + * information about the joinpoint, as in AspectJ after-throwing advice. + * + *

Note: If a throws-advice method throws an exception itself, it will + * override the original exception (i.e. change the exception thrown to the user). + * The overriding exception will typically be a RuntimeException; this is compatible + * with any method signature. However, if a throws-advice method throws a checked + * exception, it will have to match the declared exceptions of the target method + * and is hence to some degree coupled to specific target method signatures. + * Do not throw an undeclared checked exception that is incompatible with + * the target method's signature! + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see AfterReturningAdvice + * @see MethodBeforeAdvice + */ +public interface ThrowsAdvice extends AfterAdvice { + +} Index: 3rdParty_sources/spring/org/springframework/aop/TrueClassFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/TrueClassFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/TrueClassFilter.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import java.io.Serializable; + +/** + * Canonical ClassFilter instance that matches all classes. + * + * @author Rod Johnson + */ +class TrueClassFilter implements ClassFilter, Serializable { + + public static final TrueClassFilter INSTANCE = new TrueClassFilter(); + + /** + * Enforce Singleton pattern. + */ + private TrueClassFilter() { + } + + public boolean matches(Class clazz) { + return true; + } + + /** + * Required to support serialization. Replaces with canonical + * instance on deserialization, protecting Singleton pattern. + * Alternative to overriding equals(). + */ + private Object readResolve() { + return INSTANCE; + } + + public String toString() { + return "ClassFilter.TRUE"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/TrueMethodMatcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/TrueMethodMatcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/TrueMethodMatcher.java 17 Aug 2012 15:11:46 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import java.io.Serializable; +import java.lang.reflect.Method; + +/** + * Canonical MethodMatcher instance that matches all methods. + * + * @author Rod Johnson + */ +class TrueMethodMatcher implements MethodMatcher, Serializable { + + public static final TrueMethodMatcher INSTANCE = new TrueMethodMatcher(); + + /** + * Enforce Singleton pattern. + */ + private TrueMethodMatcher() { + } + + public boolean isRuntime() { + return false; + } + + public boolean matches(Method method, Class targetClass) { + return true; + } + + public boolean matches(Method method, Class targetClass, Object[] args) { + // Should never be invoked as isRuntime returns false. + throw new UnsupportedOperationException(); + } + + /** + * Required to support serialization. Replaces with canonical + * instance on deserialization, protecting Singleton pattern. + * Alternative to overriding equals(). + */ + private Object readResolve() { + return INSTANCE; + } + + public String toString() { + return "MethodMatcher.TRUE"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/TruePointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/TruePointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/TruePointcut.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop; + +import java.io.Serializable; + +/** + * Canonical Pointcut instance that always matches. + * + * @author Rod Johnson + */ +class TruePointcut implements Pointcut, Serializable { + + public static final TruePointcut INSTANCE = new TruePointcut(); + + /** + * Enforce Singleton pattern. + */ + private TruePointcut() { + } + + public ClassFilter getClassFilter() { + return ClassFilter.TRUE; + } + + public MethodMatcher getMethodMatcher() { + return MethodMatcher.TRUE; + } + + /** + * Required to support serialization. Replaces with canonical + * instance on deserialization, protecting Singleton pattern. + * Alternative to overriding equals(). + */ + private Object readResolve() { + return INSTANCE; + } + + public String toString() { + return "Pointcut.TRUE"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/package.html 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,24 @@ + + + +Core Spring AOP interfaces, built on AOP Alliance AOP interoperability interfaces. + +
Any AOP Alliance MethodInterceptor is usable in Spring. + +
Spring AOP also offers: +

    +
  • Introduction support +
  • A Pointcut abstraction, supporting "static" pointcuts + (class and method-based) and "dynamic" pointcuts (also considering method arguments). + There are currently no AOP Alliance interfaces for pointcuts. +
  • A full range of advice types, including around, before, after returning and throws advice. +
  • Extensibility allowing arbitrary custom advice types to + be plugged in without modifying the core framework. +
+ +
+Spring AOP can be used programmatically or (preferably) +integrated with the Spring IoC container. + + + Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AbstractAspectJAdvice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AbstractAspectJAdvice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AbstractAspectJAdvice.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,691 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import org.aopalliance.aop.Advice; +import org.aopalliance.intercept.MethodInvocation; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.weaver.tools.JoinPointMatch; +import org.aspectj.weaver.tools.PointcutParameter; + +import org.springframework.aop.AopInvocationException; +import org.springframework.aop.MethodMatcher; +import org.springframework.aop.Pointcut; +import org.springframework.aop.ProxyMethodInvocation; +import org.springframework.aop.interceptor.ExposeInvocationInterceptor; +import org.springframework.aop.support.ComposablePointcut; +import org.springframework.aop.support.MethodMatchers; +import org.springframework.aop.support.StaticMethodMatcher; +import org.springframework.core.JdkVersion; +import org.springframework.core.LocalVariableTableParameterNameDiscoverer; +import org.springframework.core.ParameterNameDiscoverer; +import org.springframework.core.PrioritizedParameterNameDiscoverer; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.CollectionUtils; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; + +/** + * Base class for AOP Alliance {@link org.aopalliance.aop.Advice} classes + * wrapping an AspectJ aspect or an AspectJ-annotated advice method. + * + * @author Rod Johnson + * @author Adrian Colyer + * @author Juergen Hoeller + * @author Ramnivas Laddad + * @since 2.0 + */ +public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedenceInformation { + + /** + * Key used in ReflectiveMethodInvocation userAtributes map for the current joinpoint. + */ + protected static final String JOIN_POINT_KEY = JoinPoint.class.getName(); + + + /** + * Lazily instantiate joinpoint for the current invocation. + * Requires MethodInvocation to be bound with ExposeInvocationInterceptor. + *

Do not use if access is available to the current ReflectiveMethodInvocation + * (in an around advice). + * @return current AspectJ joinpoint, or through an exception if we're not in a + * Spring AOP invocation. + */ + public static JoinPoint currentJoinPoint() { + MethodInvocation mi = ExposeInvocationInterceptor.currentInvocation(); + if (!(mi instanceof ProxyMethodInvocation)) { + throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi); + } + ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi; + JoinPoint jp = (JoinPoint) pmi.getUserAttribute(JOIN_POINT_KEY); + if (jp == null) { + jp = new MethodInvocationProceedingJoinPoint(pmi); + pmi.setUserAttribute(JOIN_POINT_KEY, jp); + } + return jp; + } + + + protected final Method aspectJAdviceMethod; + + /** The total number of arguments we have to populate on advice dispatch */ + private final int adviceInvocationArgumentCount; + + private final AspectJExpressionPointcut pointcut; + + private final AspectInstanceFactory aspectInstanceFactory; + + /** + * The name of the aspect (ref bean) in which this advice was defined (used + * when determining advice precedence so that we can determine + * whether two pieces of advice come from the same aspect). + */ + private String aspectName; + + /** + * The order of declaration of this advice within the aspect. + */ + private int declarationOrder; + + /** + * This will be non-null if the creator of this advice object knows the argument names + * and sets them explicitly + */ + private String[] argumentNames = null; + + /** Non-null if after throwing advice binds the thrown value */ + private String throwingName = null; + + /** Non-null if after returning advice binds the return value */ + private String returningName = null; + + private Class discoveredReturningType = Object.class; + + private Class discoveredThrowingType = Object.class; + + /** + * Index for thisJoinPoint argument (currently only + * supported at index 0 if present at all) + */ + private int joinPointArgumentIndex = -1; + + /** + * Index for thisJoinPointStaticPart argument (currently only + * supported at index 0 if present at all) + */ + private int joinPointStaticPartArgumentIndex = -1; + + private Map argumentBindings = null; + + private boolean argumentsIntrospected = false; + + // The actual type is java.lang.reflect.Type, + // but for JDK 1.4 compatibility we use Object as the static type. + private Object discoveredReturningGenericType; + // Note: Unlike return type, no such generic information is needed for the throwing type, + // since Java doesn't allow exception types to be parameterized. + + + /** + * Create a new AbstractAspectJAdvice for the given advice method. + * @param aspectJAdviceMethod the AspectJ-style advice method + * @param pointcut the AspectJ expression pointcut + * @param aspectInstanceFactory the factory for aspect instances + */ + public AbstractAspectJAdvice( + Method aspectJAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aspectInstanceFactory) { + + Assert.notNull(aspectJAdviceMethod, "Advice method must not be null"); + this.aspectJAdviceMethod = aspectJAdviceMethod; + this.adviceInvocationArgumentCount = this.aspectJAdviceMethod.getParameterTypes().length; + this.pointcut = pointcut; + this.aspectInstanceFactory = aspectInstanceFactory; + } + + + /** + * Return the AspectJ-style advice method. + */ + public final Method getAspectJAdviceMethod() { + return this.aspectJAdviceMethod; + } + + /** + * Return the AspectJ expression pointcut. + */ + public final AspectJExpressionPointcut getPointcut() { + calculateArgumentBindings(); + return this.pointcut; + } + + /** + * Build a 'safe' pointcut that excludes the AspectJ advice method itself. + * @return a composable pointcut that builds on the original AspectJ expression pointcut + * @see #getPointcut() + */ + public final Pointcut buildSafePointcut() { + Pointcut pc = getPointcut(); + MethodMatcher safeMethodMatcher = MethodMatchers.intersection( + new AdviceExcludingMethodMatcher(this.aspectJAdviceMethod), pc.getMethodMatcher()); + return new ComposablePointcut(pc.getClassFilter(), safeMethodMatcher); + } + + /** + * Return the factory for aspect instances. + */ + public final AspectInstanceFactory getAspectInstanceFactory() { + return this.aspectInstanceFactory; + } + + /** + * Return the ClassLoader for aspect instances. + */ + public final ClassLoader getAspectClassLoader() { + return this.aspectInstanceFactory.getAspectClassLoader(); + } + + public int getOrder() { + return this.aspectInstanceFactory.getOrder(); + } + + + public void setAspectName(String name) { + this.aspectName = name; + } + + public String getAspectName() { + return this.aspectName; + } + + /** + * Sets the declaration order of this advice within the aspect + */ + public void setDeclarationOrder(int order) { + this.declarationOrder = order; + } + + public int getDeclarationOrder() { + return this.declarationOrder; + } + + /** + * Set by creator of this advice object if the argument names are known. + *

This could be for example because they have been explicitly specified in XML, + * or in an advice annotation. + * @param argNames comma delimited list of arg names + */ + public void setArgumentNames(String argNames) { + String[] tokens = StringUtils.commaDelimitedListToStringArray(argNames); + setArgumentNamesFromStringArray(tokens); + } + + public void setArgumentNamesFromStringArray(String[] args) { + this.argumentNames = new String[args.length]; + for (int i = 0; i < args.length; i++) { + this.argumentNames[i] = StringUtils.trimWhitespace(args[i]); + if (!isVariableName(this.argumentNames[i])) { + throw new IllegalArgumentException( + "'argumentNames' property of AbstractAspectJAdvice contains an argument name '" + + this.argumentNames[i] + "' that is not a valid Java identifier"); + } + } + if (argumentNames != null) { + if (aspectJAdviceMethod.getParameterTypes().length == argumentNames.length + 1) { + // May need to add implicit join point arg name... + Class firstArgType = aspectJAdviceMethod.getParameterTypes()[0]; + if (firstArgType == JoinPoint.class || + firstArgType == ProceedingJoinPoint.class || + firstArgType == JoinPoint.StaticPart.class) { + String[] oldNames = argumentNames; + argumentNames = new String[oldNames.length + 1]; + argumentNames[0] = "THIS_JOIN_POINT"; + System.arraycopy(oldNames, 0, argumentNames, 1, oldNames.length); + } + } + } + } + + public void setReturningName(String name) { + throw new UnsupportedOperationException("Only afterReturning advice can be used to bind a return value"); + } + + /** + * We need to hold the returning name at this level for argument binding calculations, + * this method allows the afterReturning advice subclass to set the name. + */ + protected void setReturningNameNoCheck(String name) { + // name could be a variable or a type... + if (isVariableName(name)) { + this.returningName = name; + } + else { + // assume a type + try { + this.discoveredReturningType = ClassUtils.forName(name, getAspectClassLoader()); + } + catch (Throwable ex) { + throw new IllegalArgumentException("Returning name '" + name + + "' is neither a valid argument name nor the fully-qualified name of a Java type on the classpath. " + + "Root cause: " + ex); + } + } + } + + protected Class getDiscoveredReturningType() { + return this.discoveredReturningType; + } + + protected Object getDiscoveredReturningGenericType() { + return this.discoveredReturningGenericType; + } + + public void setThrowingName(String name) { + throw new UnsupportedOperationException("Only afterThrowing advice can be used to bind a thrown exception"); + } + + /** + * We need to hold the throwing name at this level for argument binding calculations, + * this method allows the afterThrowing advice subclass to set the name. + */ + protected void setThrowingNameNoCheck(String name) { + // name could be a variable or a type... + if (isVariableName(name)) { + this.throwingName = name; + } + else { + // assume a type + try { + this.discoveredThrowingType = ClassUtils.forName(name, getAspectClassLoader()); + } + catch (Throwable ex) { + throw new IllegalArgumentException("Throwing name '" + name + + "' is neither a valid argument name nor the fully-qualified name of a Java type on the classpath. " + + "Root cause: " + ex); + } + } + } + + protected Class getDiscoveredThrowingType() { + return this.discoveredThrowingType; + } + + private boolean isVariableName(String name) { + char[] chars = name.toCharArray(); + if (!Character.isJavaIdentifierStart(chars[0])) { + return false; + } + for (int i = 1; i < chars.length; i++) { + if (!Character.isJavaIdentifierPart(chars[i])) { + return false; + } + } + return true; + } + + + /** + * Do as much work as we can as part of the set-up so that argument binding + * on subsequent advice invocations can be as fast as possible. + *

If the first argument is of type JoinPoint or ProceedingJoinPoint then we + * pass a JoinPoint in that position (ProceedingJoinPoint for around advice). + *

If the first argument is of type JoinPoint.StaticPart + * then we pass a JoinPoint.StaticPart in that position. + *

Remaining arguments have to be bound by pointcut evaluation at + * a given join point. We will get back a map from argument name to + * value. We need to calculate which advice parameter needs to be bound + * to which argument name. There are multiple strategies for determining + * this binding, which are arranged in a ChainOfResponsibility. + */ + public synchronized final void calculateArgumentBindings() { + // The simple case... nothing to bind. + if (this.argumentsIntrospected || this.adviceInvocationArgumentCount == 0) { + return; + } + + int numUnboundArgs = this.adviceInvocationArgumentCount; + Class[] parameterTypes = this.aspectJAdviceMethod.getParameterTypes(); + if (maybeBindJoinPoint(parameterTypes[0]) || maybeBindProceedingJoinPoint(parameterTypes[0])) { + numUnboundArgs--; + } + else if (maybeBindJoinPointStaticPart(parameterTypes[0])) { + numUnboundArgs--; + } + + if (numUnboundArgs > 0) { + // need to bind arguments by name as returned from the pointcut match + bindArgumentsByName(numUnboundArgs); + } + + this.argumentsIntrospected = true; + } + + private boolean maybeBindJoinPoint(Class candidateParameterType) { + if (candidateParameterType.equals(JoinPoint.class)) { + this.joinPointArgumentIndex = 0; + return true; + } + else { + return false; + } + } + + private boolean maybeBindProceedingJoinPoint(Class candidateParameterType) { + if (candidateParameterType.equals(ProceedingJoinPoint.class)) { + if (!supportsProceedingJoinPoint()) { + throw new IllegalArgumentException("ProceedingJoinPoint is only supported for around advice"); + } + this.joinPointArgumentIndex = 0; + return true; + } + else { + return false; + } + } + + protected boolean supportsProceedingJoinPoint() { + return false; + } + + private boolean maybeBindJoinPointStaticPart(Class candidateParameterType) { + if (candidateParameterType.equals(JoinPoint.StaticPart.class)) { + this.joinPointStaticPartArgumentIndex = 0; + return true; + } + else { + return false; + } + } + + private void bindArgumentsByName(int numArgumentsExpectingToBind) { + if (this.argumentNames == null) { + this.argumentNames = createParameterNameDiscoverer().getParameterNames(this.aspectJAdviceMethod); + } + if (this.argumentNames != null) { + // We have been able to determine the arg names. + bindExplicitArguments(numArgumentsExpectingToBind); + } + else { + throw new IllegalStateException("Advice method [" + this.aspectJAdviceMethod.getName() + "] " + + "requires " + numArgumentsExpectingToBind + " arguments to be bound by name, but " + + "the argument names were not specified and could not be discovered."); + } + } + + /** + * Create a ParameterNameDiscoverer to be used for argument binding. + *

The default implementation creates a {@link PrioritizedParameterNameDiscoverer} + * containing a {@link LocalVariableTableParameterNameDiscoverer} and an + * {@link AspectJAdviceParameterNameDiscoverer}. + */ + protected ParameterNameDiscoverer createParameterNameDiscoverer() { + // We need to discover them, or if that fails, guess, + // and if we can't guess with 100% accuracy, fail. + PrioritizedParameterNameDiscoverer discoverer = new PrioritizedParameterNameDiscoverer(); + discoverer.addDiscoverer(new LocalVariableTableParameterNameDiscoverer()); + AspectJAdviceParameterNameDiscoverer adviceParameterNameDiscoverer = + new AspectJAdviceParameterNameDiscoverer(this.pointcut.getExpression()); + adviceParameterNameDiscoverer.setReturningName(this.returningName); + adviceParameterNameDiscoverer.setThrowingName(this.throwingName); + // Last in chain, so if we're called and we fail, that's bad... + adviceParameterNameDiscoverer.setRaiseExceptions(true); + discoverer.addDiscoverer(adviceParameterNameDiscoverer); + return discoverer; + } + + private void bindExplicitArguments(int numArgumentsLeftToBind) { + this.argumentBindings = new HashMap(); + + int numExpectedArgumentNames = this.aspectJAdviceMethod.getParameterTypes().length; + if (this.argumentNames.length != numExpectedArgumentNames) { + throw new IllegalStateException("Expecting to find " + numExpectedArgumentNames + + " arguments to bind by name in advice, but actually found " + + this.argumentNames.length + " arguments."); + } + + // So we match in number... + int argumentIndexOffset = this.adviceInvocationArgumentCount - numArgumentsLeftToBind; + for (int i = argumentIndexOffset; i < this.argumentNames.length; i++) { + this.argumentBindings.put(this.argumentNames[i],new Integer(i)); + } + + // Check that returning and throwing were in the argument names list if + // specified, and find the discovered argument types. + if (this.returningName != null) { + if (!this.argumentBindings.containsKey(this.returningName)) { + throw new IllegalStateException("Returning argument name '" + + this.returningName + "' was not bound in advice arguments"); + } + else { + Integer index = (Integer) this.argumentBindings.get(this.returningName); + this.discoveredReturningType = this.aspectJAdviceMethod.getParameterTypes()[index.intValue()]; + if (JdkVersion.isAtLeastJava15()) { + this.discoveredReturningGenericType = + this.aspectJAdviceMethod.getGenericParameterTypes()[index.intValue()]; + } + } + } + if (this.throwingName != null) { + if (!this.argumentBindings.containsKey(this.throwingName)) { + throw new IllegalStateException("Throwing argument name '" + + this.throwingName + "' was not bound in advice arguments"); + } + else { + Integer index = (Integer) this.argumentBindings.get(this.throwingName); + this.discoveredThrowingType = this.aspectJAdviceMethod.getParameterTypes()[index.intValue()]; + } + } + + // configure the pointcut expression accordingly. + configurePointcutParameters(argumentIndexOffset); + } + + /** + * All parameters from argumentIndexOffset onwards are candidates for + * pointcut parameters - but returning and throwing vars are handled differently + * and must be removed from the list if present. + */ + private void configurePointcutParameters(int argumentIndexOffset) { + int numParametersToRemove = argumentIndexOffset; + if (this.returningName != null) { + numParametersToRemove++; + } + if (this.throwingName != null) { + numParametersToRemove++; + } + String[] pointcutParameterNames = new String[this.argumentNames.length - numParametersToRemove]; + Class[] pointcutParameterTypes = new Class[pointcutParameterNames.length]; + Class[] methodParameterTypes = this.aspectJAdviceMethod.getParameterTypes(); + + int index = 0; + for (int i = 0; i < this.argumentNames.length; i++) { + if (i < argumentIndexOffset) { + continue; + } + if (this.argumentNames[i].equals(this.returningName) || + this.argumentNames[i].equals(this.throwingName)) { + continue; + } + pointcutParameterNames[index] = this.argumentNames[i]; + pointcutParameterTypes[index] = methodParameterTypes[i]; + index++; + } + + this.pointcut.setParameterNames(pointcutParameterNames); + this.pointcut.setParameterTypes(pointcutParameterTypes); + } + + /** + * Take the arguments at the method execution join point and output a set of arguments + * to the advice method + * @param jp the current JoinPoint + * @param jpMatch the join point match that matched this execution join point + * @param returnValue the return value from the method execution (may be null) + * @param ex the exception thrown by the method execution (may be null) + * @return the empty array if there are no arguments + */ + protected Object[] argBinding(JoinPoint jp, JoinPointMatch jpMatch, Object returnValue, Throwable ex) { + calculateArgumentBindings(); + + // AMC start + Object[] adviceInvocationArgs = new Object[this.adviceInvocationArgumentCount]; + int numBound = 0; + + if (this.joinPointArgumentIndex != -1) { + adviceInvocationArgs[this.joinPointArgumentIndex] = jp; + numBound++; + } + else if (this.joinPointStaticPartArgumentIndex != -1) { + adviceInvocationArgs[this.joinPointStaticPartArgumentIndex] = jp.getStaticPart(); + numBound++; + } + + if (!CollectionUtils.isEmpty(this.argumentBindings)) { + // binding from pointcut match + if (jpMatch != null) { + PointcutParameter[] parameterBindings = jpMatch.getParameterBindings(); + for (int i = 0; i < parameterBindings.length; i++) { + PointcutParameter parameter = parameterBindings[i]; + String name = parameter.getName(); + Integer index = (Integer) this.argumentBindings.get(name); + adviceInvocationArgs[index.intValue()] = parameter.getBinding(); + numBound++; + } + } + // binding from returning clause + if (this.returningName != null) { + Integer index = (Integer) this.argumentBindings.get(this.returningName); + adviceInvocationArgs[index.intValue()] = returnValue; + numBound++; + } + // binding from thrown exception + if (this.throwingName != null) { + Integer index = (Integer) this.argumentBindings.get(this.throwingName); + adviceInvocationArgs[index.intValue()] = ex; + numBound++; + } + } + + if (numBound != this.adviceInvocationArgumentCount) { + throw new IllegalStateException("Required to bind " + this.adviceInvocationArgumentCount + + " arguments, but only bound " + numBound + " (JoinPointMatch " + + (jpMatch == null ? "was NOT" : "WAS") + + " bound in invocation)"); + } + + return adviceInvocationArgs; + } + + + /** + * Invoke the advice method. + * @param jpMatch the JoinPointMatch that matched this execution join point + * @param returnValue the return value from the method execution (may be null) + * @param ex the exception thrown by the method execution (may be null) + * @return the invocation result + * @throws Throwable in case of invocation failure + */ + protected Object invokeAdviceMethod(JoinPointMatch jpMatch, Object returnValue, Throwable ex) throws Throwable { + return invokeAdviceMethodWithGivenArgs(argBinding(getJoinPoint(), jpMatch, returnValue, ex)); + } + + // As above, but in this case we are given the join point. + protected Object invokeAdviceMethod(JoinPoint jp, JoinPointMatch jpMatch, Object returnValue, Throwable t) + throws Throwable { + + return invokeAdviceMethodWithGivenArgs(argBinding(jp, jpMatch, returnValue, t)); + } + + protected Object invokeAdviceMethodWithGivenArgs(Object[] args) throws Throwable { + Object[] actualArgs = args; + if (this.aspectJAdviceMethod.getParameterTypes().length == 0) { + actualArgs = null; + } + try { + ReflectionUtils.makeAccessible(this.aspectJAdviceMethod); + // TODO AopUtils.invokeJoinpointUsingReflection + return this.aspectJAdviceMethod.invoke(this.aspectInstanceFactory.getAspectInstance(), actualArgs); + } + catch (IllegalArgumentException ex) { + throw new AopInvocationException("Mismatch on arguments to advice method [" + + this.aspectJAdviceMethod + "]; pointcut expression [" + + this.pointcut.getPointcutExpression() + "]", ex); + } + catch (InvocationTargetException ex) { + throw ex.getTargetException(); + } + } + + /** + * Overridden in around advice to return proceeding join point. + */ + protected JoinPoint getJoinPoint() { + return currentJoinPoint(); + } + + /** + * Get the current join point match at the join point we are being dispatched on. + */ + protected JoinPointMatch getJoinPointMatch() { + MethodInvocation mi = ExposeInvocationInterceptor.currentInvocation(); + if (!(mi instanceof ProxyMethodInvocation)) { + throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi); + } + return getJoinPointMatch((ProxyMethodInvocation) mi); + } + + // Note: We can't use JoinPointMatch.getClass().getName() as the key, since + // Spring AOP does all the matching at a join point, and then all the invocations. + // Under this scenario, if we just use JoinPointMatch as the key, then + // 'last man wins' which is not what we want at all. + // Using the expression is guaranteed to be safe, since 2 identical expressions + // are guaranteed to bind in exactly the same way. + protected JoinPointMatch getJoinPointMatch(ProxyMethodInvocation pmi) { + return (JoinPointMatch) pmi.getUserAttribute(this.pointcut.getExpression()); + } + + + public String toString() { + return getClass().getName() + ": advice method [" + this.aspectJAdviceMethod + "]; " + + "aspect name '" + this.aspectName + "'"; + } + + + /** + * MethodMatcher that excludes the specified advice method. + * @see AbstractAspectJAdvice#buildSafePointcut() + */ + private static class AdviceExcludingMethodMatcher extends StaticMethodMatcher { + + private final Method adviceMethod; + + public AdviceExcludingMethodMatcher(Method adviceMethod) { + this.adviceMethod = adviceMethod; + } + + public boolean matches(Method method, Class targetClass) { + return !this.adviceMethod.equals(method); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectInstanceFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectInstanceFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectInstanceFactory.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import org.springframework.core.Ordered; + +/** + * Interface implemented to provide an instance of an AspectJ aspect. + * Decouples from Spring's bean factory. + * + *

Extends the {@link org.springframework.core.Ordered} interface + * to express an order value for the underlying aspect in a chain. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see org.springframework.beans.factory.BeanFactory#getBean + */ +public interface AspectInstanceFactory extends Ordered { + + /** + * Create an instance of this factory's aspect. + * @return the aspect instance (never null) + */ + Object getAspectInstance(); + + /** + * Expose the aspect class loader that this factory uses. + * @return the aspect class loader (never null) + */ + ClassLoader getAspectClassLoader(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,826 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.weaver.tools.PointcutParser; +import org.aspectj.weaver.tools.PointcutPrimitive; + +import org.springframework.core.ParameterNameDiscoverer; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +/** + * {@link ParameterNameDiscoverer} implementation that tries to deduce parameter names + * for an advice method from the pointcut expression, returning, and throwing clauses. + * If an unambiguous interpretation is not available, it returns null. + * + *

This class interprets arguments in the following way: + *

    + *
  1. If the first parameter of the method is of type {@link JoinPoint} + * or {@link ProceedingJoinPoint}, it is assumed to be for passing + * thisJoinPoint to the advice, and the parameter name will + * be assigned the value "thisJoinPoint".
  2. + *
  3. If the first parameter of the method is of type + * JoinPoint.StaticPart, it is assumed to be for passing + * "thisJoinPointStaticPart" to the advice, and the parameter name + * will be assigned the value "thisJoinPointStaticPart".
  4. + *
  5. If a {@link #setThrowingName(String) throwingName} has been set, and + * there are no unbound arguments of type Throwable+, then an + * {@link IllegalArgumentException} is raised. If there is more than one + * unbound argument of type Throwable+, then an + * {@link AmbiguousBindingException} is raised. If there is exactly one + * unbound argument of type Throwable+, then the corresponding + * parameter name is assigned the value <throwingName>.
  6. + *
  7. If there remain unbound arguments, then the pointcut expression is + * examined. Let a be the number of annotation-based pointcut + * expressions (@annotation, @this, @target, @args, + * @within, @withincode) that are used in binding form. Usage in + * binding form has itself to be deduced: if the expression inside the + * pointcut is a single string literal that meets Java variable name + * conventions it is assumed to be a variable name. If a is + * zero we proceed to the next stage. If a > 1 then an + * AmbiguousBindingException is raised. If a == 1, + * and there are no unbound arguments of type Annotation+, + * then an IllegalArgumentException is raised. if there is + * exactly one such argument, then the corresponding parameter name is + * assigned the value from the pointcut expression.
  8. + *
  9. If a returningName has been set, and there are no unbound arguments + * then an IllegalArgumentException is raised. If there is + * more than one unbound argument then an + * AmbiguousBindingException is raised. If there is exactly + * one unbound argument then the corresponding parameter name is assigned + * the value <returningName>.
  10. + *
  11. If there remain unbound arguments, then the pointcut expression is + * examined once more for this, target, and + * args pointcut expressions used in the binding form (binding + * forms are deduced as described for the annotation based pointcuts). If + * there remains more than one unbound argument of a primitive type (which + * can only be bound in args) then an + * AmbiguousBindingException is raised. If there is exactly + * one argument of a primitive type, then if exactly one args + * bound variable was found, we assign the corresponding parameter name + * the variable name. If there were no args bound variables + * found an IllegalStateException is raised. If there are + * multiple args bound variables, an + * AmbiguousBindingException is raised. At this point, if + * there remains more than one unbound argument we raise an + * AmbiguousBindingException. If there are no unbound arguments + * remaining, we are done. If there is exactly one unbound argument + * remaining, and only one candidate variable name unbound from + * this, target, or args, it is + * assigned as the corresponding parameter name. If there are multiple + * possibilities, an AmbiguousBindingException is raised.
  12. + *
+ * + *

The behavior on raising an IllegalArgumentException or + * AmbiguousBindingException is configurable to allow this discoverer + * to be used as part of a chain-of-responsibility. By default the condition will + * be logged and the getParameterNames(..) method will simply return + * null. If the {@link #setRaiseExceptions(boolean) raiseExceptions} + * property is set to true, the conditions will be thrown as + * IllegalArgumentException and AmbiguousBindingException, + * respectively. + * + *

Was that perfectly clear? ;) + * + *

Short version: If an unambiguous binding can be deduced, then it is. + * If the advice requirements cannot possibly be satisfied, then null + * is returned. By setting the {@link #setRaiseExceptions(boolean) raiseExceptions} + * property to true, descriptive exceptions will be thrown instead of + * returning null in the case that the parameter names cannot be discovered. + * + * @author Adrian Colyer + * @since 2.0 + */ +public class AspectJAdviceParameterNameDiscoverer implements ParameterNameDiscoverer { + + private static final String ANNOTATION_CLASS_NAME = "java.lang.annotation.Annotation"; + + private static final String THIS_JOIN_POINT = "thisJoinPoint"; + private static final String THIS_JOIN_POINT_STATIC_PART = "thisJoinPointStaticPart"; + + // Steps in the binding algorithm... + private static final int STEP_JOIN_POINT_BINDING = 1; + private static final int STEP_THROWING_BINDING = 2; + private static final int STEP_ANNOTATION_BINDING = 3; + private static final int STEP_RETURNING_BINDING = 4; + private static final int STEP_PRIMITIVE_ARGS_BINDING = 5; + private static final int STEP_THIS_TARGET_ARGS_BINDING = 6; + private static final int STEP_REFERENCE_PCUT_BINDING = 7; + private static final int STEP_FINISHED = 8; + + private static final Set singleValuedAnnotationPcds = new HashSet(); + private static final Set nonReferencePointcutTokens = new HashSet(); + + private static Class annotationClass; + + + static { + singleValuedAnnotationPcds.add("@this"); + singleValuedAnnotationPcds.add("@target"); + singleValuedAnnotationPcds.add("@within"); + singleValuedAnnotationPcds.add("@withincode"); + singleValuedAnnotationPcds.add("@annotation"); + + Set pointcutPrimitives = PointcutParser.getAllSupportedPointcutPrimitives(); + for (Iterator iterator = pointcutPrimitives.iterator(); iterator.hasNext();) { + PointcutPrimitive primitive = (PointcutPrimitive) iterator.next(); + nonReferencePointcutTokens.add(primitive.getName()); + } + nonReferencePointcutTokens.add("&&"); + nonReferencePointcutTokens.add("!"); + nonReferencePointcutTokens.add("||"); + nonReferencePointcutTokens.add("and"); + nonReferencePointcutTokens.add("or"); + nonReferencePointcutTokens.add("not"); + + try { + annotationClass = ClassUtils.forName(ANNOTATION_CLASS_NAME, + AspectJAdviceParameterNameDiscoverer.class.getClassLoader()); + } + catch (ClassNotFoundException ex) { + // Running on < JDK 1.5, this is OK... + annotationClass = null; + } + } + + + private boolean raiseExceptions; + + /** + * If the advice is afterReturning, and binds the return value, this is the parameter name used. + */ + private String returningName; + + /** + * If the advice is afterThrowing, and binds the thrown value, this is the parameter name used. + */ + private String throwingName; + + /** + * The pointcut expression associated with the advice, as a simple String. + */ + private String pointcutExpression; + + private Class[] argumentTypes; + + private String[] parameterNameBindings; + + private int numberOfRemainingUnboundArguments; + + private int algorithmicStep = STEP_JOIN_POINT_BINDING; + + + /** + * Create a new discoverer that attempts to discover parameter names + * from the given pointcut expression. + */ + public AspectJAdviceParameterNameDiscoverer(String pointcutExpression) { + this.pointcutExpression = pointcutExpression; + } + + /** + * Indicate whether {@link IllegalArgumentException} and {@link AmbiguousBindingException} + * must be thrown as appropriate in the case of failing to deduce advice parameter names. + * @param raiseExceptions true if exceptions are to be thrown + */ + public void setRaiseExceptions(boolean raiseExceptions) { + this.raiseExceptions = raiseExceptions; + } + + /** + * If afterReturning advice binds the return value, the + * returning variable name must be specified. + * @param returningName the name of the returning variable + */ + public void setReturningName(String returningName) { + this.returningName = returningName; + } + + /** + * If afterThrowing advice binds the thrown value, the + * throwing variable name must be specified. + * @param throwingName the name of the throwing variable + */ + public void setThrowingName(String throwingName) { + this.throwingName = throwingName; + } + + /** + * Deduce the parameter names for an advice method. + *

See the {@link AspectJAdviceParameterNameDiscoverer class level javadoc} + * for this class for details of the algorithm used. + * @param method the target {@link Method} + * @return the parameter names + */ + public String[] getParameterNames(Method method) { + this.argumentTypes = method.getParameterTypes(); + this.numberOfRemainingUnboundArguments = this.argumentTypes.length; + this.parameterNameBindings = new String[this.numberOfRemainingUnboundArguments]; + this.algorithmicStep = STEP_JOIN_POINT_BINDING; + + int minimumNumberUnboundArgs = 0; + if (this.returningName != null) { + minimumNumberUnboundArgs++; + } + if (this.throwingName != null) { + minimumNumberUnboundArgs++; + } + if (this.numberOfRemainingUnboundArguments < minimumNumberUnboundArgs) { + throw new IllegalStateException( + "Not enough arguments in method to satisfy binding of returning and throwing variables"); + } + + try { + while ((this.numberOfRemainingUnboundArguments > 0) && (this.algorithmicStep < STEP_FINISHED)) { + switch (this.algorithmicStep++) { + case STEP_JOIN_POINT_BINDING: + if (!maybeBindThisJoinPoint()) { + maybeBindThisJoinPointStaticPart(); + } + break; + case STEP_THROWING_BINDING: + maybeBindThrowingVariable(); + break; + case STEP_ANNOTATION_BINDING: + maybeBindAnnotationsFromPointcutExpression(); + break; + case STEP_RETURNING_BINDING: + maybeBindReturningVariable(); + break; + case STEP_PRIMITIVE_ARGS_BINDING: + maybeBindPrimitiveArgsFromPointcutExpression(); + break; + case STEP_THIS_TARGET_ARGS_BINDING: + maybeBindThisOrTargetOrArgsFromPointcutExpression(); + break; + case STEP_REFERENCE_PCUT_BINDING: + maybeBindReferencePointcutParameter(); + break; + default: + throw new IllegalStateException("Unknown algorithmic step: " + (this.algorithmicStep - 1)); + } + } + } + catch (AmbiguousBindingException ambigEx) { + if (this.raiseExceptions) { + throw ambigEx; + } + else { + return null; + } + } + catch (IllegalArgumentException ex) { + if (this.raiseExceptions) { + throw ex; + } + else { + return null; + } + } + + if (this.numberOfRemainingUnboundArguments == 0) { + return this.parameterNameBindings; + } + else { + if (this.raiseExceptions) { + throw new IllegalStateException("Failed to bind all argument names: " + + this.numberOfRemainingUnboundArguments + " argument(s) could not be bound"); + } + else { + // convention for failing is to return null, allowing participation in a chain of responsibility + return null; + } + } + } + + /** + * An advice method can never be a constructor in Spring. + * @return null + * @throws UnsupportedOperationException if + * {@link #setRaiseExceptions(boolean) raiseExceptions} has been set to true + */ + public String[] getParameterNames(Constructor ctor) { + if (this.raiseExceptions) { + throw new UnsupportedOperationException("An advice method can never be a constructor"); + } + else { + // we return null rather than throw an exception so that we behave well + // in a chain-of-responsibility. + return null; + } + } + + + private void bindParameterName(int index, String name) { + this.parameterNameBindings[index] = name; + this.numberOfRemainingUnboundArguments--; + } + + /** + * If the first parameter is of type JoinPoint or ProceedingJoinPoint,bind "thisJoinPoint" as + * parameter name and return true, else return false. + */ + private boolean maybeBindThisJoinPoint() { + if ((this.argumentTypes[0] == JoinPoint.class) || (this.argumentTypes[0] == ProceedingJoinPoint.class)) { + bindParameterName(0, THIS_JOIN_POINT); + return true; + } + else { + return false; + } + } + + private void maybeBindThisJoinPointStaticPart() { + if (this.argumentTypes[0] == JoinPoint.StaticPart.class) { + bindParameterName(0, THIS_JOIN_POINT_STATIC_PART); + } + } + + /** + * If a throwing name was specified and there is exactly one choice remaining + * (argument that is a subtype of Throwable) then bind it. + */ + private void maybeBindThrowingVariable() { + if (this.throwingName == null) { + return; + } + + // So there is binding work to do... + int throwableIndex = -1; + for (int i = 0; i < this.argumentTypes.length; i++) { + if (isUnbound(i) && isSubtypeOf(Throwable.class, i)) { + if (throwableIndex == -1) { + throwableIndex = i; + } + else { + // Second candidate we've found - ambiguous binding + throw new AmbiguousBindingException("Binding of throwing parameter '" + + this.throwingName + "' is ambiguous: could be bound to argument " + + throwableIndex + " or argument " + i); + } + } + } + + if (throwableIndex == -1) { + throw new IllegalStateException("Binding of throwing parameter '" + this.throwingName + + "' could not be completed as no available arguments are a subtype of Throwable"); + } + else { + bindParameterName(throwableIndex, this.throwingName); + } + } + + /** + * If a returning variable was specified and there is only one choice remaining, bind it. + */ + private void maybeBindReturningVariable() { + if (this.numberOfRemainingUnboundArguments == 0) { + throw new IllegalStateException( + "Algorithm assumes that there must be at least one unbound parameter on entry to this method"); + } + + if (this.returningName != null) { + if (this.numberOfRemainingUnboundArguments > 1) { + throw new AmbiguousBindingException("Binding of returning parameter '" + this.returningName + + "' is ambiguous, there are " + this.numberOfRemainingUnboundArguments + " candidates."); + } + + // We're all set... find the unbound parameter, and bind it. + for (int i = 0; i < this.parameterNameBindings.length; i++) { + if (this.parameterNameBindings[i] == null) { + bindParameterName(i, this.returningName); + break; + } + } + } + } + + + /** + * Parse the string pointcut expression looking for: + * @this, @target, @args, @within, @withincode, @annotation. + * If we find one of these pointcut expressions, try and extract a candidate variable + * name (or variable names, in the case of args). + *

Some more support from AspectJ in doing this exercise would be nice... :) + */ + private void maybeBindAnnotationsFromPointcutExpression() { + List varNames = new ArrayList(); + String[] tokens = StringUtils.tokenizeToStringArray(this.pointcutExpression, " "); + for (int i = 0; i < tokens.length; i++) { + String toMatch = tokens[i]; + int firstParenIndex = toMatch.indexOf("("); + if (firstParenIndex != -1) { + toMatch = toMatch.substring(0, firstParenIndex); + } + if (singleValuedAnnotationPcds.contains(toMatch)) { + PointcutBody body = getPointcutBody(tokens, i); + i += body.numTokensConsumed; + String varName = maybeExtractVariableName(body.text); + if (varName != null) { + varNames.add(varName); + } + } + else if (tokens[i].startsWith("@args(") || tokens[i].equals("@args")) { + PointcutBody body = getPointcutBody(tokens, i); + i += body.numTokensConsumed; + maybeExtractVariableNamesFromArgs(body.text, varNames); + } + } + + bindAnnotationsFromVarNames(varNames); + } + + /** + * Match the given list of extracted variable names to argument slots. + */ + private void bindAnnotationsFromVarNames(List varNames) { + if (!varNames.isEmpty()) { + // we have work to do... + int numAnnotationSlots = countNumberOfUnboundAnnotationArguments(); + if (numAnnotationSlots > 1) { + throw new AmbiguousBindingException("Found " + varNames.size() + + " potential annotation variable(s), and " + + numAnnotationSlots + " potential argument slots"); + } + else if (numAnnotationSlots == 1) { + if (varNames.size() == 1) { + // it's a match + findAndBind(annotationClass, (String) varNames.get(0)); + } + else { + // multiple candidate vars, but only one slot + throw new IllegalArgumentException("Found " + varNames.size() + + " candidate annotation binding variables" + + " but only one potential argument binding slot"); + } + } + else { + // no slots so presume those candidate vars were actually type names + } + } + } + + /* + * If the token starts meets Java identifier conventions, it's in. + */ + private String maybeExtractVariableName(String candidateToken) { + if (candidateToken == null || candidateToken.equals("")) { + return null; + } + if (Character.isJavaIdentifierStart(candidateToken.charAt(0)) && + Character.isLowerCase(candidateToken.charAt(0))) { + char[] tokenChars = candidateToken.toCharArray(); + for (int i = 0; i < tokenChars.length; i++) { + if (!Character.isJavaIdentifierPart(tokenChars[i])) { + return null; + } + } + return candidateToken; + } + else { + return null; + } + } + + /** + * Given an args pointcut body (could be args or at_args), + * add any candidate variable names to the given list. + */ + private void maybeExtractVariableNamesFromArgs(String argsSpec, List varNames) { + if (argsSpec == null) { + return; + } + + String[] tokens = StringUtils.tokenizeToStringArray(argsSpec, ","); + for (int i = 0; i < tokens.length; i++) { + tokens[i] = StringUtils.trimWhitespace(tokens[i]); + String varName = maybeExtractVariableName(tokens[i]); + if (varName != null) { + varNames.add(varName); + } + } + } + + /** + * Parse the string pointcut expression looking for this(), target() and args() expressions. + * If we find one, try and extract a candidate variable name and bind it. + */ + private void maybeBindThisOrTargetOrArgsFromPointcutExpression() { + if (this.numberOfRemainingUnboundArguments > 1) { + throw new AmbiguousBindingException("Still " + this.numberOfRemainingUnboundArguments + + " unbound args at this(),target(),args() binding stage, with no way to determine between them"); + } + + List varNames = new ArrayList(); + String[] tokens = StringUtils.tokenizeToStringArray(this.pointcutExpression, " "); + for (int i = 0; i < tokens.length; i++) { + if (tokens[i].equals("this") || + tokens[i].startsWith("this(") || + tokens[i].equals("target") || + tokens[i].startsWith("target(")) { + PointcutBody body = getPointcutBody(tokens, i); + i += body.numTokensConsumed; + String varName = maybeExtractVariableName(body.text); + if (varName != null) { + varNames.add(varName); + } + } + else if (tokens[i].equals("args") || tokens[i].startsWith("args(")) { + PointcutBody body = getPointcutBody(tokens, i); + i += body.numTokensConsumed; + List candidateVarNames = new ArrayList(); + maybeExtractVariableNamesFromArgs(body.text, candidateVarNames); + // we may have found some var names that were bound in previous primitive args binding step, + // filter them out... + for (Iterator iter = candidateVarNames.iterator(); iter.hasNext();) { + String varName = (String) iter.next(); + if (!alreadyBound(varName)) { + varNames.add(varName); + } + } + } + } + + + if (varNames.size() > 1) { + throw new AmbiguousBindingException("Found " + varNames.size() + + " candidate this(), target() or args() variables but only one unbound argument slot"); + } + else if (varNames.size() == 1) { + for (int j = 0; j < this.parameterNameBindings.length; j++) { + if (isUnbound(j)) { + bindParameterName(j, (String) varNames.get(0)); + break; + } + } + } + // else varNames.size must be 0 and we have nothing to bind. + } + + private void maybeBindReferencePointcutParameter() { + if (this.numberOfRemainingUnboundArguments > 1) { + throw new AmbiguousBindingException("Still " + this.numberOfRemainingUnboundArguments + + " unbound args at reference pointcut binding stage, with no way to determine between them"); + } + + List varNames = new ArrayList(); + String[] tokens = StringUtils.tokenizeToStringArray(this.pointcutExpression, " "); + for (int i = 0; i < tokens.length; i++) { + String toMatch = tokens[i]; + if (toMatch.startsWith("!")) { + toMatch = toMatch.substring(1); + } + int firstParenIndex = toMatch.indexOf("("); + if (firstParenIndex != -1) { + toMatch = toMatch.substring(0, firstParenIndex); + } + else { + if (tokens.length < i + 2) { + // no "(" and nothing following + continue; + } + else { + String nextToken = tokens[i + 1]; + if (nextToken.charAt(0) != '(') { + // next token is not "(" either, can't be a pc... + continue; + } + } + + } + + // eat the body + PointcutBody body = getPointcutBody(tokens, i); + i += body.numTokensConsumed; + + if (!nonReferencePointcutTokens.contains(toMatch)) { + // then it could be a reference pointcut + String varName = maybeExtractVariableName(body.text); + if (varName != null) { + varNames.add(varName); + } + } + } + + if (varNames.size() > 1) { + throw new AmbiguousBindingException("Found " + varNames.size() + + " candidate reference pointcut variables but only one unbound argument slot"); + } + else if (varNames.size() == 1) { + for (int j = 0; j < this.parameterNameBindings.length; j++) { + if (isUnbound(j)) { + bindParameterName(j, (String) varNames.get(0)); + break; + } + } + } + // else varNames.size must be 0 and we have nothing to bind. + } + + /* + * We've found the start of a binding pointcut at the given index into the + * token array. Now we need to extract the pointcut body and return it. + */ + private PointcutBody getPointcutBody(String[] tokens, int startIndex) { + int numTokensConsumed = 0; + String currentToken = tokens[startIndex]; + int bodyStart = currentToken.indexOf('('); + if (currentToken.charAt(currentToken.length() - 1) == ')') { + // It's an all in one... get the text between the first (and the last) + return new PointcutBody(0, currentToken.substring(bodyStart + 1, currentToken.length() - 1)); + } + else { + StringBuffer sb = new StringBuffer(); + if (bodyStart >= 0 && bodyStart != (currentToken.length() - 1)) { + sb.append(currentToken.substring(bodyStart + 1)); + sb.append(" "); + } + numTokensConsumed++; + int currentIndex = startIndex + numTokensConsumed; + while (currentIndex < tokens.length) { + if (tokens[currentIndex].equals("(")) { + currentIndex++; + continue; + } + + if (tokens[currentIndex].endsWith(")")) { + sb.append(tokens[currentIndex].substring(0, tokens[currentIndex].length() - 1)); + return new PointcutBody(numTokensConsumed, sb.toString().trim()); + } + + String toAppend = tokens[currentIndex]; + if (toAppend.startsWith("(")) { + toAppend = toAppend.substring(1); + } + sb.append(toAppend); + sb.append(" "); + currentIndex++; + numTokensConsumed++; + } + + } + + // We looked and failed... + return new PointcutBody(numTokensConsumed, null); + } + + /** + * Match up args against unbound arguments of primitive types + */ + private void maybeBindPrimitiveArgsFromPointcutExpression() { + int numUnboundPrimitives = countNumberOfUnboundPrimitiveArguments(); + if (numUnboundPrimitives > 1) { + throw new AmbiguousBindingException("Found '" + numUnboundPrimitives + + "' unbound primitive arguments with no way to distinguish between them."); + } + if (numUnboundPrimitives == 1) { + // Look for arg variable and bind it if we find exactly one... + List varNames = new ArrayList(); + String[] tokens = StringUtils.tokenizeToStringArray(this.pointcutExpression, " "); + for (int i = 0; i < tokens.length; i++) { + if (tokens[i].equals("args") || tokens[i].startsWith("args(")) { + PointcutBody body = getPointcutBody(tokens, i); + i += body.numTokensConsumed; + maybeExtractVariableNamesFromArgs(body.text, varNames); + } + } + if (varNames.size() > 1) { + throw new AmbiguousBindingException("Found " + varNames.size() + + " candidate variable names but only one candidate binding slot when matching primitive args"); + } + else if (varNames.size() == 1) { + // 1 primitive arg, and one candidate... + for (int i = 0; i < this.argumentTypes.length; i++) { + if (isUnbound(i) && this.argumentTypes[i].isPrimitive()) { + bindParameterName(i, (String) varNames.get(0)); + break; + } + } + } + } + } + + /* + * Return true if the parameter name binding for the given parameter + * index has not yet been assigned. + */ + private boolean isUnbound(int i) { + return this.parameterNameBindings[i] == null; + } + + private boolean alreadyBound(String varName) { + for (int i = 0; i < this.parameterNameBindings.length; i++) { + if (!isUnbound(i) && varName.equals(this.parameterNameBindings[i])) { + return true; + } + } + return false; + } + + /* + * Return true if the given argument type is a subclass + * of the given supertype. + */ + private boolean isSubtypeOf(Class supertype, int argumentNumber) { + return supertype.isAssignableFrom(this.argumentTypes[argumentNumber]); + } + + private int countNumberOfUnboundAnnotationArguments() { + if (annotationClass == null) { + // We're running on a JDK < 1.5 + return 0; + } + + int count = 0; + for (int i = 0; i < this.argumentTypes.length; i++) { + if (isUnbound(i) && isSubtypeOf(annotationClass, i)) { + count++; + } + } + return count; + } + + private int countNumberOfUnboundPrimitiveArguments() { + int count = 0; + for (int i = 0; i < this.argumentTypes.length; i++) { + if (isUnbound(i) && this.argumentTypes[i].isPrimitive()) { + count++; + } + } + return count; + } + + /* + * Find the argument index with the given type, and bind the given + * varName in that position. + */ + private void findAndBind(Class argumentType, String varName) { + for (int i = 0; i < this.argumentTypes.length; i++) { + if (isUnbound(i) && isSubtypeOf(argumentType, i)) { + bindParameterName(i, varName); + return; + } + } + throw new IllegalStateException("Expected to find an unbound argument of type '" + + argumentType.getName() + "'"); + } + + + /** + * Simple struct to hold the extracted text from a pointcut body, together + * with the number of tokens consumed in extracting it. + */ + private static class PointcutBody { + + private int numTokensConsumed; + + private String text; + + public PointcutBody(int tokens, String text) { + this.numTokensConsumed = tokens; + this.text = text; + } + } + + + /** + * Thrown in response to an ambiguous binding being detected when + * trying to resolve a method's parameter names. + */ + public static class AmbiguousBindingException extends RuntimeException { + + /** + * Construct a new AmbiguousBindingException with the specified message. + * @param msg the detail message + */ + public AmbiguousBindingException(String msg) { + super(msg); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAfterAdvice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAfterAdvice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAfterAdvice.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import java.lang.reflect.Method; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.aop.AfterAdvice; + +/** + * Spring AOP advice wrapping an AspectJ after advice method. + * + * @author Rod Johnson + * @since 2.0 + */ +public class AspectJAfterAdvice extends AbstractAspectJAdvice implements MethodInterceptor, AfterAdvice { + + public AspectJAfterAdvice( + Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) { + + super(aspectJBeforeAdviceMethod, pointcut, aif); + } + + public Object invoke(MethodInvocation mi) throws Throwable { + try { + return mi.proceed(); + } + finally { + invokeAdviceMethod(getJoinPointMatch(), null, null); + } + } + + public boolean isBeforeAdvice() { + return false; + } + + public boolean isAfterAdvice() { + return true; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAfterReturningAdvice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAfterReturningAdvice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAfterReturningAdvice.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,88 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; + +import org.springframework.aop.AfterAdvice; +import org.springframework.aop.AfterReturningAdvice; +import org.springframework.util.ClassUtils; +import org.springframework.util.TypeUtils; + +/** + * Spring AOP advice wrapping an AspectJ after-returning advice method. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Ramnivas Laddad + * @since 2.0 + */ +public class AspectJAfterReturningAdvice extends AbstractAspectJAdvice implements AfterReturningAdvice, AfterAdvice { + + public AspectJAfterReturningAdvice( + Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) { + + super(aspectJBeforeAdviceMethod, pointcut, aif); + } + + public boolean isBeforeAdvice() { + return false; + } + + public boolean isAfterAdvice() { + return true; + } + + public void setReturningName(String name) { + setReturningNameNoCheck(name); + } + + public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { + if (shouldInvokeOnReturnValueOf(method, returnValue)) { + invokeAdviceMethod(getJoinPointMatch(), returnValue, null); + } + } + + /** + * Following AspectJ semantics, if a returning clause was specified, then the + * advice is only invoked if the returned value is an instance of the given + * returning type and generic type parameters, if any, match the assignment + * rules. If the returning type is Object, the advice is *always* invoked. + * @param returnValue the return value of the target method + * @return whether to invoke the advice method for the given return value + */ + private boolean shouldInvokeOnReturnValueOf(Method method, Object returnValue) { + Class type = getDiscoveredReturningType(); + Object genericType = getDiscoveredReturningGenericType(); + // If we aren't dealing with a raw type, check if generic parameters are assignable. + return (ClassUtils.isAssignableValue(type, returnValue) && + (genericType == null || genericType == type || GenericTypeMatcher.isAssignable(genericType, method))); + } + + + /** + * Inner class to avoid a static JDK 1.5 dependency for generic type matching. + */ + private static class GenericTypeMatcher { + + public static boolean isAssignable(Object genericType, Method method) { + return TypeUtils.isAssignable((Type) genericType, method.getGenericReturnType()); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAfterThrowingAdvice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAfterThrowingAdvice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAfterThrowingAdvice.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import java.lang.reflect.Method; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.aop.AfterAdvice; + +/** + * Spring AOP advice wrapping an AspectJ after-throwing advice method. + * + * @author Rod Johnson + * @since 2.0 + */ +public class AspectJAfterThrowingAdvice extends AbstractAspectJAdvice implements MethodInterceptor, AfterAdvice { + + public AspectJAfterThrowingAdvice( + Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) { + + super(aspectJBeforeAdviceMethod, pointcut, aif); + } + + public boolean isBeforeAdvice() { + return false; + } + + public boolean isAfterAdvice() { + return true; + } + + public void setThrowingName(String name) { + setThrowingNameNoCheck(name); + } + + public Object invoke(MethodInvocation mi) throws Throwable { + try { + return mi.proceed(); + } + catch (Throwable t) { + if (shouldInvokeOnThrowing(t)) { + invokeAdviceMethod(getJoinPointMatch(), null, t); + } + throw t; + } + } + + /** + * In AspectJ semantics, after throwing advice that specifies a throwing clause + * is only invoked if the thrown exception is a subtype of the given throwing type. + */ + private boolean shouldInvokeOnThrowing(Throwable t) { + Class throwingType = getDiscoveredThrowingType(); + return throwingType.isAssignableFrom(t.getClass()); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAopUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAopUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAopUtils.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import org.aopalliance.aop.Advice; + +import org.springframework.aop.Advisor; +import org.springframework.aop.AfterAdvice; +import org.springframework.aop.BeforeAdvice; + +/** + * Utility methods for dealing with AspectJ advisors. + * + * @author Adrian Colyer + * @author Juergen Hoeller + * @since 2.0 + */ +public abstract class AspectJAopUtils { + + /** + * Return true if the advisor is a form of before advice. + */ + public static boolean isBeforeAdvice(Advisor anAdvisor) { + AspectJPrecedenceInformation precedenceInfo = getAspectJPrecedenceInformationFor(anAdvisor); + if (precedenceInfo != null) { + return precedenceInfo.isBeforeAdvice(); + } + return (anAdvisor.getAdvice() instanceof BeforeAdvice); + } + + /** + * Return true if the advisor is a form of after advice. + */ + public static boolean isAfterAdvice(Advisor anAdvisor) { + AspectJPrecedenceInformation precedenceInfo = getAspectJPrecedenceInformationFor(anAdvisor); + if (precedenceInfo != null) { + return precedenceInfo.isAfterAdvice(); + } + return (anAdvisor.getAdvice() instanceof AfterAdvice); + } + + /** + * Return the AspectJPrecedenceInformation provided by this advisor or its advice. + * If neither the advisor nor the advice have precedence information, this method + * will return null. + */ + public static AspectJPrecedenceInformation getAspectJPrecedenceInformationFor(Advisor anAdvisor) { + if (anAdvisor instanceof AspectJPrecedenceInformation) { + return (AspectJPrecedenceInformation) anAdvisor; + } + Advice advice = anAdvisor.getAdvice(); + if (advice instanceof AspectJPrecedenceInformation) { + return (AspectJPrecedenceInformation) advice; + } + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAroundAdvice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAroundAdvice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJAroundAdvice.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import java.lang.reflect.Method; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.weaver.tools.JoinPointMatch; + +import org.springframework.aop.ProxyMethodInvocation; + +/** + * Spring AOP around advice (MethodInterceptor) that wraps + * an AspectJ advice method. Exposes ProceedingJoinPoint. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + */ +public class AspectJAroundAdvice extends AbstractAspectJAdvice implements MethodInterceptor { + + public AspectJAroundAdvice( + Method aspectJAroundAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) { + + super(aspectJAroundAdviceMethod, pointcut, aif); + } + + public boolean isBeforeAdvice() { + return false; + } + + public boolean isAfterAdvice() { + return false; + } + + protected boolean supportsProceedingJoinPoint() { + return true; + } + + + public Object invoke(MethodInvocation mi) throws Throwable { + if (!(mi instanceof ProxyMethodInvocation)) { + throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi); + } + ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi; + ProceedingJoinPoint pjp = lazyGetProceedingJoinPoint(pmi); + JoinPointMatch jpm = getJoinPointMatch(pmi); + return invokeAdviceMethod(pjp, jpm, null, null); + } + + /** + * Return the ProceedingJoinPoint for the current invocation, + * instantiating it lazily if it hasn't been bound to the thread already. + * @param rmi the current Spring AOP ReflectiveMethodInvocation, + * which we'll use for attribute binding + * @return the ProceedingJoinPoint to make available to advice methods + */ + protected ProceedingJoinPoint lazyGetProceedingJoinPoint(ProxyMethodInvocation rmi) { + return new MethodInvocationProceedingJoinPoint(rmi); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJExpressionPointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJExpressionPointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJExpressionPointcut.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,530 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.aspectj.weaver.BCException; +import org.aspectj.weaver.patterns.NamePattern; +import org.aspectj.weaver.reflect.ReflectionWorld; +import org.aspectj.weaver.tools.ContextBasedMatcher; +import org.aspectj.weaver.tools.FuzzyBoolean; +import org.aspectj.weaver.tools.JoinPointMatch; +import org.aspectj.weaver.tools.MatchingContext; +import org.aspectj.weaver.tools.PointcutDesignatorHandler; +import org.aspectj.weaver.tools.PointcutExpression; +import org.aspectj.weaver.tools.PointcutParameter; +import org.aspectj.weaver.tools.PointcutParser; +import org.aspectj.weaver.tools.PointcutPrimitive; +import org.aspectj.weaver.tools.ShadowMatch; + +import org.springframework.aop.ClassFilter; +import org.springframework.aop.IntroductionAwareMethodMatcher; +import org.springframework.aop.MethodMatcher; +import org.springframework.aop.ProxyMethodInvocation; +import org.springframework.aop.framework.autoproxy.ProxyCreationContext; +import org.springframework.aop.interceptor.ExposeInvocationInterceptor; +import org.springframework.aop.support.AbstractExpressionPointcut; +import org.springframework.aop.support.AopUtils; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +/** + * Spring {@link org.springframework.aop.Pointcut} implementation + * that uses the AspectJ weaver to evaluate a pointcut expression. + * + *

The pointcut expression value is an AspectJ expression. This can + * reference other pointcuts and use composition and other operations. + * + *

Naturally, as this is to be processed by Spring AOP's proxy-based model, + * only method execution pointcuts are supported. + * + * @author Rob Harrop + * @author Adrian Colyer + * @author Rod Johnson + * @author Juergen Hoeller + * @author Ramnivas Laddad + * @since 2.0 + */ +public class AspectJExpressionPointcut extends AbstractExpressionPointcut + implements ClassFilter, IntroductionAwareMethodMatcher, BeanFactoryAware { + + private static final Set DEFAULT_SUPPORTED_PRIMITIVES = new HashSet(); + + static { + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.EXECUTION); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.ARGS); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.REFERENCE); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.THIS); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.TARGET); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.WITHIN); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_ANNOTATION); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_WITHIN); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_ARGS); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_TARGET); + } + + + private static final Log logger = LogFactory.getLog(AspectJExpressionPointcut.class); + + private final Map shadowMapCache = new HashMap(); + + private PointcutParser pointcutParser; + + private Class pointcutDeclarationScope; + + private String[] pointcutParameterNames = new String[0]; + + private Class[] pointcutParameterTypes = new Class[0]; + + private BeanFactory beanFactory; + + private PointcutExpression pointcutExpression; + + + /** + * Create a new default AspectJExpressionPointcut. + */ + public AspectJExpressionPointcut() { + this(DEFAULT_SUPPORTED_PRIMITIVES); + } + + /** + * Create a new AspectJExpressionPointcut with the given supported primitives. + * @param supportedPrimitives Set of {@link org.aspectj.weaver.tools.PointcutPrimitive} + * instances + */ + public AspectJExpressionPointcut(Set supportedPrimitives) { + this.pointcutParser = + PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution( + supportedPrimitives); + this.pointcutParser.registerPointcutDesignatorHandler(new BeanNamePointcutDesignatorHandler()); + } + + /** + * Create a new AspectJExpressionPointcut with the given settings. + * @param declarationScope the declaration scope for the pointcut + * @param paramNames the parameter names for the pointcut + * @param paramTypes the parameter types for the pointcut + */ + public AspectJExpressionPointcut(Class declarationScope, String[] paramNames, Class[] paramTypes) { + this(DEFAULT_SUPPORTED_PRIMITIVES); + this.pointcutDeclarationScope = declarationScope; + if (paramNames.length != paramTypes.length) { + throw new IllegalStateException( + "Number of pointcut parameter names must match number of pointcut parameter types"); + } + this.pointcutParameterNames = paramNames; + this.pointcutParameterTypes = paramTypes; + } + + + /** + * Set the declaration scope for the pointcut. + */ + public void setPointcutDeclarationScope(Class pointcutDeclarationScope) { + this.pointcutDeclarationScope = pointcutDeclarationScope; + } + + /** + * Set the parameter names for the pointcut. + */ + public void setParameterNames(String[] names) { + this.pointcutParameterNames = names; + } + + /** + * Set the parameter types for the pointcut. + */ + public void setParameterTypes(Class[] types) { + this.pointcutParameterTypes = types; + } + + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + + + public ClassFilter getClassFilter() { + checkReadyToMatch(); + return this; + } + + public MethodMatcher getMethodMatcher() { + checkReadyToMatch(); + return this; + } + + + /** + * Check whether this pointcut is ready to match, + * lazily building the underlying AspectJ pointcut expression. + */ + private void checkReadyToMatch() { + if (getExpression() == null) { + throw new IllegalStateException("Must set property 'expression' before attempting to match"); + } + if (this.pointcutExpression == null) { + this.pointcutExpression = buildPointcutExpression(); + } + } + + /** + * Build the underlying AspectJ pointcut expression. + */ + private PointcutExpression buildPointcutExpression() { + PointcutParameter[] pointcutParameters = new PointcutParameter[this.pointcutParameterNames.length]; + for (int i = 0; i < pointcutParameters.length; i++) { + pointcutParameters[i] = this.pointcutParser.createPointcutParameter( + this.pointcutParameterNames[i], this.pointcutParameterTypes[i]); + } + return this.pointcutParser.parsePointcutExpression( + replaceBooleanOperators(getExpression()), this.pointcutDeclarationScope, pointcutParameters); + } + + /** + * If a pointcut expression has been specified in XML, the user cannot + * write and as "&&" (though && will work). + * We also allow and between two pointcut sub-expressions. + *

This method converts back to && for the AspectJ pointcut parser. + */ + private String replaceBooleanOperators(String pcExpr) { + pcExpr = StringUtils.replace(pcExpr," and "," && "); + pcExpr = StringUtils.replace(pcExpr, " or ", " || "); + pcExpr = StringUtils.replace(pcExpr, " not ", " ! "); + return pcExpr; + } + + /** + * Return the underlying AspectJ pointcut expression. + */ + public PointcutExpression getPointcutExpression() { + checkReadyToMatch(); + return this.pointcutExpression; + } + + + public boolean matches(Class targetClass) { + checkReadyToMatch(); + try { + return this.pointcutExpression.couldMatchJoinPointsInType(targetClass); + } + catch (BCException ex) { + logger.debug("PointcutExpression matching rejected target class", ex); + return false; + } + } + + public boolean matches(Method method, Class targetClass, boolean beanHasIntroductions) { + checkReadyToMatch(); + Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass); + ShadowMatch shadowMatch = null; + try { + shadowMatch = getShadowMatch(targetMethod, method); + } + catch (ReflectionWorld.ReflectionWorldException ex) { + // Could neither introspect the target class nor the proxy class -> + // let's simply consider this method as non-matching. + return false; + } + + // Special handling for this, target, @this, @target, @annotation + // in Spring - we can optimize since we know we have exactly this class, + // and there will never be matching subclass at runtime. + if (shadowMatch.alwaysMatches()) { + return true; + } + else if (shadowMatch.neverMatches()) { + return false; + } + else { + // the maybe case + return (beanHasIntroductions || matchesIgnoringSubtypes(shadowMatch) || matchesTarget(shadowMatch, targetClass)); + } + } + + public boolean matches(Method method, Class targetClass) { + return matches(method, targetClass, false); + } + + public boolean isRuntime() { + checkReadyToMatch(); + return this.pointcutExpression.mayNeedDynamicTest(); + } + + public boolean matches(Method method, Class targetClass, Object[] args) { + checkReadyToMatch(); + ShadowMatch shadowMatch = null; + ShadowMatch originalShadowMatch = null; + try { + shadowMatch = getShadowMatch(AopUtils.getMostSpecificMethod(method, targetClass), method); + originalShadowMatch = getShadowMatch(method, method); + } + catch (ReflectionWorld.ReflectionWorldException ex) { + // Could neither introspect the target class nor the proxy class -> + // let's simply consider this method as non-matching. + return false; + } + + // Bind Spring AOP proxy to AspectJ "this" and Spring AOP target to AspectJ target, + // consistent with return of MethodInvocationProceedingJoinPoint + ProxyMethodInvocation pmi = null; + Object targetObject = null; + Object thisObject = null; + try { + MethodInvocation mi = ExposeInvocationInterceptor.currentInvocation(); + targetObject = mi.getThis(); + if (!(mi instanceof ProxyMethodInvocation)) { + throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi); + } + pmi = (ProxyMethodInvocation) mi; + thisObject = pmi.getProxy(); + } + catch (IllegalStateException ex) { + // No current invocation... + // TODO: Should we really proceed here? + logger.debug("Couldn't access current invocation - matching with limited context: " + ex); + } + + JoinPointMatch joinPointMatch = shadowMatch.matchesJoinPoint(thisObject, targetObject, args); + + /* + * Do a final check to see if any this(TYPE) kind of residue match. For + * this purpose, we use the original method's (proxy method's) shadow to + * ensure that 'this' is correctly checked against. Without this check, + * we get incorrect match on this(TYPE) where TYPE matches the target + * type but not 'this' (as would be the case of JDK dynamic proxies). + *

See SPR-2979 for the original bug. + */ + if (pmi != null) { // there is a current invocation + RuntimeTestWalker originalMethodResidueTest = new RuntimeTestWalker(originalShadowMatch); + if (!originalMethodResidueTest.testThisInstanceOfResidue(thisObject.getClass())) { + return false; + } + } + if (joinPointMatch.matches() && pmi != null) { + bindParameters(pmi, joinPointMatch); + } + return joinPointMatch.matches(); + } + + + protected String getCurrentProxiedBeanName() { + return ProxyCreationContext.getCurrentProxiedBeanName(); + } + + + /** + * A match test returned maybe - if there are any subtype sensitive variables + * involved in the test (this, target, at_this, at_target, at_annotation) then + * we say this is not a match as in Spring there will never be a different + * runtime subtype. + */ + private boolean matchesIgnoringSubtypes(ShadowMatch shadowMatch) { + return !(new RuntimeTestWalker(shadowMatch).testsSubtypeSensitiveVars()); + } + + private boolean matchesTarget(ShadowMatch shadowMatch, Class targetClass) { + return new RuntimeTestWalker(shadowMatch).testTargetInstanceOfResidue(targetClass); + } + + private void bindParameters(ProxyMethodInvocation invocation, JoinPointMatch jpm) { + // Note: Can't use JoinPointMatch.getClass().getName() as the key, since + // Spring AOP does all the matching at a join point, and then all the invocations + // under this scenario, if we just use JoinPointMatch as the key, then + // 'last man wins' which is not what we want at all. + // Using the expression is guaranteed to be safe, since 2 identical expressions + // are guaranteed to bind in exactly the same way. + invocation.setUserAttribute(getExpression(), jpm); + } + + private ShadowMatch getShadowMatch(Method targetMethod, Method originalMethod) { + synchronized (this.shadowMapCache) { + ShadowMatch shadowMatch = (ShadowMatch) this.shadowMapCache.get(targetMethod); + if (shadowMatch == null) { + try { + shadowMatch = this.pointcutExpression.matchesMethodExecution(targetMethod); + } + catch (ReflectionWorld.ReflectionWorldException ex) { + // Failed to introspect target method, probably because it has been loaded + // in a special ClassLoader. Let's try the original method instead... + if (targetMethod == originalMethod) { + throw ex; + } + shadowMatch = this.pointcutExpression.matchesMethodExecution(originalMethod); + } + this.shadowMapCache.put(targetMethod, shadowMatch); + } + return shadowMatch; + } + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AspectJExpressionPointcut)) { + return false; + } + AspectJExpressionPointcut otherPc = (AspectJExpressionPointcut) other; + return ObjectUtils.nullSafeEquals(this.getExpression(), otherPc.getExpression()) && + ObjectUtils.nullSafeEquals(this.pointcutDeclarationScope, otherPc.pointcutDeclarationScope) && + ObjectUtils.nullSafeEquals(this.pointcutParameterNames, otherPc.pointcutParameterNames) && + ObjectUtils.nullSafeEquals(this.pointcutParameterTypes, otherPc.pointcutParameterTypes); + } + + public int hashCode() { + int hashCode = ObjectUtils.nullSafeHashCode(this.getExpression()); + hashCode = 31 * hashCode + ObjectUtils.nullSafeHashCode(this.pointcutDeclarationScope); + hashCode = 31 * hashCode + ObjectUtils.nullSafeHashCode(this.pointcutParameterNames); + hashCode = 31 * hashCode + ObjectUtils.nullSafeHashCode(this.pointcutParameterTypes); + return hashCode; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("AspectJExpressionPointcut: "); + if (this.pointcutParameterNames != null && this.pointcutParameterTypes != null) { + sb.append("("); + for (int i = 0; i < this.pointcutParameterTypes.length; i++) { + sb.append(this.pointcutParameterTypes[i].getName()); + sb.append(" "); + sb.append(this.pointcutParameterNames[i]); + if ((i+1) < this.pointcutParameterTypes.length) { + sb.append(", "); + } + } + sb.append(")"); + } + sb.append(" "); + if (getExpression() != null) { + sb.append(getExpression()); + } + else { + sb.append(""); + } + return sb.toString(); + } + + + /** + * Handler for the Spring-specific bean() pointcut designator + * extension to AspectJ. + *

This handler must be added to each pointcut object that needs to + * handle the bean() PCD. Matching context is obtained + * automatically by examining a thread local variable and therefore a matching + * context need not be set on the pointcut. + */ + private class BeanNamePointcutDesignatorHandler implements PointcutDesignatorHandler { + + private static final String BEAN_DESIGNATOR_NAME = "bean"; + + public String getDesignatorName() { + return BEAN_DESIGNATOR_NAME; + } + + public ContextBasedMatcher parse(String expression) { + return new BeanNameContextMatcher(expression); + } + } + + + /** + * Matcher class for the BeanNamePointcutDesignatorHandler. + * + *

Dynamic match tests for this matcher always return true, + * since the matching decision is made at the proxy creation time. + * For static match tests, this matcher abstains to allow the overall + * pointcut to match even when negation is used with the bean() poitncut. + */ + private class BeanNameContextMatcher implements ContextBasedMatcher { + + private final NamePattern expressionPattern; + + public BeanNameContextMatcher(String expression) { + this.expressionPattern = new NamePattern(expression); + } + + public boolean couldMatchJoinPointsInType(Class someClass) { + return (contextMatch(someClass) == FuzzyBoolean.YES); + } + + public boolean couldMatchJoinPointsInType(Class someClass, MatchingContext context) { + return (contextMatch(someClass) == FuzzyBoolean.YES); + } + + public boolean matchesDynamically(MatchingContext context) { + return true; + } + + public FuzzyBoolean matchesStatically(MatchingContext context) { + return contextMatch(null); + } + + public boolean mayNeedDynamicTest() { + return false; + } + + private FuzzyBoolean contextMatch(Class targetType) { + String advisedBeanName = getCurrentProxiedBeanName(); + if (advisedBeanName == null) { // no proxy creation in progress + // abstain; can't return YES, since that will make pointcut with negation fail + return FuzzyBoolean.MAYBE; + } + if (BeanFactoryUtils.isGeneratedBeanName(advisedBeanName)) { + return FuzzyBoolean.NO; + } + if (targetType != null) { + boolean isFactory = FactoryBean.class.isAssignableFrom(targetType); + return FuzzyBoolean.fromBoolean( + matchesBeanName(isFactory ? BeanFactory.FACTORY_BEAN_PREFIX + advisedBeanName : advisedBeanName)); + } + else { + return FuzzyBoolean.fromBoolean(matchesBeanName(advisedBeanName) || + matchesBeanName(BeanFactory.FACTORY_BEAN_PREFIX + advisedBeanName)); + } + } + + private boolean matchesBeanName(String advisedBeanName) { + if (this.expressionPattern.matches(advisedBeanName)) { + return true; + } + if (beanFactory != null) { + String[] aliases = beanFactory.getAliases(advisedBeanName); + for (int i = 0; i < aliases.length; i++) { + if (this.expressionPattern.matches(aliases[i])) { + return true; + } + } + } + return false; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisor.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import org.springframework.aop.Pointcut; +import org.springframework.aop.support.AbstractGenericPointcutAdvisor; + +/** + * Spring AOP Advisor that can be used for any AspectJ pointcut expression. + * + * @author Rob Harrop + * @since 2.0 + */ +public class AspectJExpressionPointcutAdvisor extends AbstractGenericPointcutAdvisor { + + private final AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); + + + public Pointcut getPointcut() { + return this.pointcut; + } + + public void setExpression(String expression) { + this.pointcut.setExpression(expression); + } + + public void setLocation(String location) { + this.pointcut.setLocation(location); + } + + public void setParameterTypes(Class[] types) { + this.pointcut.setParameterTypes(types); + } + + public void setParameterNames(String[] names) { + this.pointcut.setParameterNames(names); + } + + public String getLocation() { + return this.pointcut.getLocation(); + } + + public String getExpression() { + return this.pointcut.getExpression(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJMethodBeforeAdvice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJMethodBeforeAdvice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJMethodBeforeAdvice.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import java.lang.reflect.Method; + +import org.springframework.aop.MethodBeforeAdvice; + +/** + * Spring AOP advice that wraps an AspectJ before method. + * + * @author Rod Johnson + * @author Adrian Colyer + * @since 2.0 + */ +public class AspectJMethodBeforeAdvice extends AbstractAspectJAdvice implements MethodBeforeAdvice { + + public AspectJMethodBeforeAdvice( + Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) { + + super(aspectJBeforeAdviceMethod, pointcut, aif); + } + + public void before(Method method, Object[] args, Object target) throws Throwable { + invokeAdviceMethod(getJoinPointMatch(), null, null); + } + + public boolean isBeforeAdvice() { + return true; + } + + public boolean isAfterAdvice() { + return false; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJPointcutAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJPointcutAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJPointcutAdvisor.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,96 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import org.aopalliance.aop.Advice; + +import org.springframework.aop.Pointcut; +import org.springframework.aop.PointcutAdvisor; +import org.springframework.core.Ordered; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + +/** + * AspectJPointcutAdvisor that adapts an {@link AbstractAspectJAdvice} + * to the {@link org.springframework.aop.PointcutAdvisor} interface. + * + * @author Adrian Colyer + * @author Juergen Hoeller + * @since 2.0 + */ +public class AspectJPointcutAdvisor implements PointcutAdvisor, Ordered { + + private final AbstractAspectJAdvice advice; + + private final Pointcut pointcut; + + private Integer order; + + + /** + * Create a new AspectJPointcutAdvisor for the given advice + * @param advice the AbstractAspectJAdvice to wrap + */ + public AspectJPointcutAdvisor(AbstractAspectJAdvice advice) { + Assert.notNull(advice, "Advice must not be null"); + this.advice = advice; + this.pointcut = advice.buildSafePointcut(); + } + + public void setOrder(int order) { + this.order = new Integer(order); + } + + + public boolean isPerInstance() { + return true; + } + + public Advice getAdvice() { + return this.advice; + } + + public Pointcut getPointcut() { + return this.pointcut; + } + + public int getOrder() { + if (this.order != null) { + return this.order.intValue(); + } + else { + return this.advice.getOrder(); + } + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AspectJPointcutAdvisor)) { + return false; + } + AspectJPointcutAdvisor otherAdvisor = (AspectJPointcutAdvisor) other; + return (ObjectUtils.nullSafeEquals(this.advice, otherAdvisor.advice)); + } + + public int hashCode() { + return AspectJPointcutAdvisor.class.hashCode(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJPrecedenceInformation.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJPrecedenceInformation.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJPrecedenceInformation.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import org.springframework.core.Ordered; + +/** + * Interface to be implemented by types that can supply the information + * needed to sort advice/advisors by AspectJ's precedence rules. + * + * @author Adrian Colyer + * @since 2.0 + * @see org.springframework.aop.aspectj.autoproxy.AspectJPrecedenceComparator + */ +public interface AspectJPrecedenceInformation extends Ordered { + + // Implementation note: + // We need the level of indirection this interface provides as otherwise the + // AspectJPrecedenceComparator must ask an Advisor for its Advice in all cases + // in order to sort advisors. This causes problems with the + // InstantiationModelAwarePointcutAdvisor which needs to delay creating + // its advice for aspects with non-singleton instantiation models. + + /** + * The name of the aspect (bean) in which the advice was declared. + */ + String getAspectName(); + + /** + * The declaration order of the advice member within the aspect. + */ + int getDeclarationOrder(); + + /** + * Return whether this is a before advice. + */ + boolean isBeforeAdvice(); + + /** + * Return whether this is an after advice. + */ + boolean isAfterAdvice(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJProxyUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJProxyUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJProxyUtils.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,74 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import java.util.Iterator; +import java.util.List; + +import org.springframework.aop.Advisor; +import org.springframework.aop.PointcutAdvisor; +import org.springframework.aop.interceptor.ExposeInvocationInterceptor; + +/** + * Utility methods for working with AspectJ proxies. + * + * @author Rod Johnson + * @author Ramnivas Laddad + * @since 2.0 + */ +public abstract class AspectJProxyUtils { + + /** + * Add special advisors if necessary to work with a proxy chain that contains AspectJ advisors. + * This will expose the current Spring AOP invocation (necessary for some AspectJ pointcut matching) + * and make available the current AspectJ JoinPoint. The call will have no effect if there are no + * AspectJ advisors in the advisor chain. + * @param advisors Advisors available + * @return true if any special {@link Advisor Advisors} were added, otherwise false. + */ + public static boolean makeAdvisorChainAspectJCapableIfNecessary(List advisors) { + // Don't add advisors to an empty list; may indicate that proxying is just not required + if (!advisors.isEmpty()) { + boolean foundAspectJAdvice = false; + for (Iterator it = advisors.iterator(); it.hasNext() && !foundAspectJAdvice; ) { + Advisor advisor = (Advisor) it.next(); + // Be careful not to get the Advice without a guard, as + // this might eagerly instantiate a non-singleton AspectJ aspect + if (isAspectJAdvice(advisor)) { + foundAspectJAdvice = true; + } + } + if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) { + advisors.add(0, ExposeInvocationInterceptor.ADVISOR); + return true; + } + } + return false; + } + + /** + * Determine whether the given Advisor contains an AspectJ advice. + * @param advisor the Advisor to check + */ + private static boolean isAspectJAdvice(Advisor advisor) { + return (advisor instanceof InstantiationModelAwarePointcutAdvisor || + advisor.getAdvice() instanceof AbstractAspectJAdvice || + (advisor instanceof PointcutAdvisor && + ((PointcutAdvisor) advisor).getPointcut() instanceof AspectJExpressionPointcut)); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJWeaverMessageHandler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJWeaverMessageHandler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/AspectJWeaverMessageHandler.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,109 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.aspectj.bridge.AbortException; +import org.aspectj.bridge.IMessage; +import org.aspectj.bridge.IMessage.Kind; +import org.aspectj.bridge.IMessageHandler; + +/** + * Implementation of AspectJ's {@link IMessageHandler} interface that + * routes AspectJ weaving messages through the same logging system as the + * regular Spring messages. + * + *

Pass the option... + * + *

-XmessageHandlerClass:org.springframework.aop.aspectj.AspectJWeaverMessageHandler + * + *

to the weaver; for example, specifying the following in a + * "META-INF/aop.xml file: + * + *

<weaver options="..."/> + * + * @author Adrian Colyer + * @author Juergen Hoeller + * @since 2.0 + */ +public class AspectJWeaverMessageHandler implements IMessageHandler { + + private static final String AJ_ID = "[AspectJ] "; + + private static final Log LOGGER = LogFactory.getLog("AspectJ Weaver"); + + + public boolean handleMessage(IMessage message) throws AbortException { + Kind messageKind = message.getKind(); + + if (LOGGER.isDebugEnabled() || LOGGER.isTraceEnabled()) { + if (messageKind == IMessage.DEBUG) { + LOGGER.debug(makeMessageFor(message)); + return true; + } + } + + if (LOGGER.isInfoEnabled()) { + if ((messageKind == IMessage.INFO) || (messageKind == IMessage.WEAVEINFO)) { + LOGGER.info(makeMessageFor(message)); + return true; + } + } + + if (LOGGER.isWarnEnabled()) { + if (messageKind == IMessage.WARNING) { + LOGGER.warn(makeMessageFor(message)); + return true; + } + } + + if (LOGGER.isErrorEnabled()) { + if (messageKind == IMessage.ERROR) { + LOGGER.error(makeMessageFor(message)); + return true; + } + } + + if (LOGGER.isFatalEnabled()) { + if (messageKind == IMessage.ABORT) { + LOGGER.fatal(makeMessageFor(message)); + return true; + } + } + + return false; + } + + private String makeMessageFor(IMessage aMessage) { + return AJ_ID + aMessage.getMessage(); + } + + public boolean isIgnoring(Kind messageKind) { + // We want to see everything, and allow configuration of log levels dynamically. + return false; + } + + public void dontIgnore(Kind messageKind) { + // We weren't ignoring anything anyway... + } + + public void ignore(Kind kind) { + // We weren't ignoring anything anyway... + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/DeclareParentsAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/DeclareParentsAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/DeclareParentsAdvisor.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,110 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import org.aopalliance.aop.Advice; + +import org.springframework.aop.ClassFilter; +import org.springframework.aop.IntroductionAdvisor; +import org.springframework.aop.support.ClassFilters; +import org.springframework.aop.support.DelegatePerTargetObjectIntroductionInterceptor; +import org.springframework.aop.support.DelegatingIntroductionInterceptor; + +/** + * Introduction advisor delegating to the given object. + * Implements AspectJ annotation-style behavior for the DeclareParents annotation. + * + * @author Rod Johnson + * @author Ramnivas Laddad + * @since 2.0 + */ +public class DeclareParentsAdvisor implements IntroductionAdvisor { + + private final Class introducedInterface; + + private final ClassFilter typePatternClassFilter; + + private final Advice advice; + + + /** + * Create a new advisor for this DeclareParents field. + * @param interfaceType static field defining the introduction + * @param typePattern type pattern the introduction is restricted to + * @param defaultImpl the default implementation class + */ + public DeclareParentsAdvisor(Class interfaceType, String typePattern, Class defaultImpl) { + this(interfaceType, typePattern, defaultImpl, + new DelegatePerTargetObjectIntroductionInterceptor(defaultImpl, interfaceType)); + } + + /** + * Create a new advisor for this DeclareParents field. + * @param interfaceType static field defining the introduction + * @param typePattern type pattern the introduction is restricted to + * @param delegateRef the delegate implementation object + */ + public DeclareParentsAdvisor(Class interfaceType, String typePattern, Object delegateRef) { + this(interfaceType, typePattern, delegateRef.getClass(), + new DelegatingIntroductionInterceptor(delegateRef)); + } + + /** + * Private constructor to share common code between impl-based delegate and reference-based delegate + * (cannot use method such as init() to share common code, due the the use of final fields) + * @param interfaceType static field defining the introduction + * @param typePattern type pattern the introduction is restricted to + * @param implementationClass implementation class + * @param advice delegation advice + */ + private DeclareParentsAdvisor(Class interfaceType, String typePattern, Class implementationClass, Advice advice) { + this.introducedInterface = interfaceType; + ClassFilter typePatternFilter = new TypePatternClassFilter(typePattern); + + // Excludes methods implemented. + ClassFilter exclusion = new ClassFilter() { + public boolean matches(Class clazz) { + return !(introducedInterface.isAssignableFrom(clazz)); + } + }; + + this.typePatternClassFilter = ClassFilters.intersection(typePatternFilter, exclusion); + this.advice = advice; + } + + + public ClassFilter getClassFilter() { + return this.typePatternClassFilter; + } + + public void validateInterfaces() throws IllegalArgumentException { + // Do nothing + } + + public boolean isPerInstance() { + return true; + } + + public Advice getAdvice() { + return this.advice; + } + + public Class[] getInterfaces() { + return new Class[] {this.introducedInterface}; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/InstantiationModelAwarePointcutAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/InstantiationModelAwarePointcutAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/InstantiationModelAwarePointcutAdvisor.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import org.springframework.aop.PointcutAdvisor; + +/** + * Interface to be implemented by Spring AOP Advisors wrapping AspectJ + * aspects that may have a lazy initialization strategy. For example, + * a perThis instantiation model would mean lazy initialization of the advice. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + */ +public interface InstantiationModelAwarePointcutAdvisor extends PointcutAdvisor { + + /** + * Return whether this advisor is lazily initializing its underlying advice. + */ + boolean isLazy(); + + /** + * Return whether this advisor has already instantiated its advice. + */ + boolean isAdviceInstantiated(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPoint.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPoint.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPoint.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,229 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import java.lang.reflect.Method; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.Signature; +import org.aspectj.lang.reflect.MethodSignature; +import org.aspectj.lang.reflect.SourceLocation; +import org.aspectj.runtime.internal.AroundClosure; + +import org.springframework.aop.ProxyMethodInvocation; +import org.springframework.util.Assert; + +/** + * Implementation of AspectJ ProceedingJoinPoint interface + * wrapping an AOP Alliance MethodInvocation. + * + *

Note: the getThis() method returns the current Spring AOP proxy. + * The getTarget() method returns the current Spring AOP target (which may be + * null if there is no target), and is a plain POJO without any advice. + * If you want to call the object and have the advice take effect, use + * getThis(). A common example is casting the object to an + * introduced interface in the implementation of an introduction. + * + *

Of course there is no such distinction between target and proxy in AspectJ. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Adrian Colyer + * @since 2.0 + */ +public class MethodInvocationProceedingJoinPoint implements ProceedingJoinPoint, JoinPoint.StaticPart { + + private final ProxyMethodInvocation methodInvocation; + + private Object[] defensiveCopyOfArgs; + + /** Lazily initialized signature object */ + private Signature signature; + + /** Lazily initialized source location object */ + private SourceLocation sourceLocation; + + + /** + * Create a new MethodInvocationProceedingJoinPoint, wrapping the given + * Spring ProxyMethodInvocation object. + * @param methodInvocation the Spring ProxyMethodInvocation object + */ + public MethodInvocationProceedingJoinPoint(ProxyMethodInvocation methodInvocation) { + Assert.notNull(methodInvocation, "MethodInvocation must not be null"); + this.methodInvocation = methodInvocation; + } + + public void set$AroundClosure(AroundClosure aroundClosure) { + throw new UnsupportedOperationException(); + } + + public Object proceed() throws Throwable { + return this.methodInvocation.invocableClone().proceed(); + } + + public Object proceed(Object[] arguments) throws Throwable { + Assert.notNull(arguments, "Argument array passed to proceed cannot be null"); + if (arguments.length != this.methodInvocation.getArguments().length) { + throw new IllegalArgumentException("Expecting " + + this.methodInvocation.getArguments().length + " arguments to proceed, " + + "but was passed " + arguments.length + " arguments"); + } + this.methodInvocation.setArguments(arguments); + return this.methodInvocation.invocableClone(arguments).proceed(); + } + + /** + * Returns the Spring AOP proxy. Cannot be null. + */ + public Object getThis() { + return this.methodInvocation.getProxy(); + } + + /** + * Returns the Spring AOP target. May be null if there is no target. + */ + public Object getTarget() { + return this.methodInvocation.getThis(); + } + + public Object[] getArgs() { + if (this.defensiveCopyOfArgs == null) { + Object[] argsSource = this.methodInvocation.getArguments(); + this.defensiveCopyOfArgs = new Object[argsSource.length]; + System.arraycopy(argsSource, 0, this.defensiveCopyOfArgs, 0, argsSource.length); + } + return this.defensiveCopyOfArgs; + } + + public Signature getSignature() { + if (this.signature == null) { + this.signature = new MethodSignatureImpl(); + } + return signature; + } + + public SourceLocation getSourceLocation() { + if (this.sourceLocation == null) { + this.sourceLocation = new SourceLocationImpl(); + } + return this.sourceLocation; + } + + public String getKind() { + return ProceedingJoinPoint.METHOD_EXECUTION; + } + + public JoinPoint.StaticPart getStaticPart() { + return this; + } + + + public String toShortString() { + return "execution(" + this.methodInvocation.getMethod().getName() + ")"; + } + + public String toLongString() { + return getClass().getName() + ": execution: [" + this.methodInvocation + "]"; + } + + public String toString() { + return getClass().getName() + ": " + toShortString(); + } + + + /** + * Lazily initialized MethodSignature. + */ + private class MethodSignatureImpl implements Signature, MethodSignature { + + public String toShortString() { + return methodInvocation.getMethod().getName(); + } + + public String toLongString() { + return methodInvocation.getMethod().toString(); + } + + public String getName() { + return methodInvocation.getMethod().getName(); + } + + public int getModifiers() { + return methodInvocation.getMethod().getModifiers(); + } + + public Class getDeclaringType() { + return methodInvocation.getMethod().getDeclaringClass(); + } + + public String getDeclaringTypeName() { + return methodInvocation.getMethod().getDeclaringClass().getName(); + } + + public Class getReturnType() { + return methodInvocation.getMethod().getReturnType(); + } + + public Method getMethod() { + return methodInvocation.getMethod(); + } + + public Class[] getParameterTypes() { + return methodInvocation.getMethod().getParameterTypes(); + } + + public String[] getParameterNames() { + // TODO consider allowing use of ParameterNameDiscoverer, or tying into + // parameter names exposed for argument binding... + throw new UnsupportedOperationException( + "Parameter names cannot be determined unless compiled by AspectJ compiler"); + } + + public Class[] getExceptionTypes() { + return methodInvocation.getMethod().getExceptionTypes(); + } + } + + + /** + * Lazily initialized SourceLocation. + */ + private class SourceLocationImpl implements SourceLocation { + + public Class getWithinType() { + if (methodInvocation.getThis() == null) { + throw new UnsupportedOperationException("No source location joinpoint available: target is null"); + } + return methodInvocation.getThis().getClass(); + } + + public String getFileName() { + throw new UnsupportedOperationException(); + } + + public int getLine() { + throw new UnsupportedOperationException(); + } + + public int getColumn() { + throw new UnsupportedOperationException(); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/RuntimeTestWalker.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/RuntimeTestWalker.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/RuntimeTestWalker.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,255 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import java.lang.reflect.Field; + +import org.aspectj.weaver.ResolvedType; +import org.aspectj.weaver.ast.And; +import org.aspectj.weaver.ast.Call; +import org.aspectj.weaver.ast.FieldGetCall; +import org.aspectj.weaver.ast.HasAnnotation; +import org.aspectj.weaver.ast.ITestVisitor; +import org.aspectj.weaver.ast.Instanceof; +import org.aspectj.weaver.ast.Literal; +import org.aspectj.weaver.ast.Not; +import org.aspectj.weaver.ast.Or; +import org.aspectj.weaver.ast.Test; +import org.aspectj.weaver.internal.tools.MatchingContextBasedTest; +import org.aspectj.weaver.reflect.ReflectionVar; +import org.aspectj.weaver.reflect.ShadowMatchImpl; +import org.aspectj.weaver.tools.ShadowMatch; + +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; + +/** + * This class encapsulates some AspectJ internal knowledge that should be + * pushed back into the AspectJ project in a future release. + * + *

It relies on implementation specific knowledge in AspectJ to break + * encapsulation and do something AspectJ was not designed to do: query + * the types of runtime tests that will be performed. The code here should + * migrate to ShadowMatch.getVariablesInvolvedInRuntimeTest() + * or some similar operation. + * + *

See . + * + * @author Adrian Colyer + * @author Ramnivas Laddad + * @since 2.0 + */ +class RuntimeTestWalker { + + private final Test runtimeTest; + + + public RuntimeTestWalker(ShadowMatch shadowMatch) { + ShadowMatchImpl shadowMatchImplementation = (ShadowMatchImpl) shadowMatch; + try { + Field testField = shadowMatchImplementation.getClass().getDeclaredField("residualTest"); + ReflectionUtils.makeAccessible(testField); + this.runtimeTest = (Test) testField.get(shadowMatch); + } + catch (NoSuchFieldException noSuchFieldEx) { + throw new IllegalStateException("The version of aspectjtools.jar / aspectjweaver.jar " + + "on the classpath is incompatible with this version of Spring: Expected field " + + "'runtimeTest' is not present on ShadowMatchImpl class."); + } + catch (IllegalAccessException illegalAccessEx) { + // Famous last words... but I don't see how this can happen given the + // makeAccessible call above + throw new IllegalStateException("Unable to access ShadowMatchImpl.runtimeTest field."); + } + } + + + /** + * If the test uses any of the this, target, at_this, at_target, and at_annotation vars, + * then it tests subtype sensitive vars. + */ + public boolean testsSubtypeSensitiveVars() { + return new SubtypeSensitiveVarTypeTestVisitor().testsSubtypeSensitiveVars(this.runtimeTest); + } + + public boolean testThisInstanceOfResidue(Class thisClass) { + return new ThisInstanceOfResidueTestVisitor(thisClass).thisInstanceOfMatches(this.runtimeTest); + } + + public boolean testTargetInstanceOfResidue(Class targetClass) { + return new TargetInstanceOfResidueTestVisitor(targetClass).targetInstanceOfMatches(this.runtimeTest); + } + + + private static class TestVisitorAdapter implements ITestVisitor { + + protected static final int THIS_VAR = 0; + protected static final int TARGET_VAR = 1; + protected static final int AT_THIS_VAR = 3; + protected static final int AT_TARGET_VAR = 4; + protected static final int AT_ANNOTATION_VAR = 8; + + public void visit(And e) { + e.getLeft().accept(this); + e.getRight().accept(this); + } + + public void visit(Or e) { + e.getLeft().accept(this); + e.getRight().accept(this); + } + + public void visit(Not e) { + e.getBody().accept(this); + } + + public void visit(Instanceof i) { + } + + public void visit(Literal literal) { + } + + public void visit(Call call) { + } + + public void visit(FieldGetCall fieldGetCall) { + } + + public void visit(HasAnnotation hasAnnotation) { + } + + public void visit(MatchingContextBasedTest matchingContextTest) { + } + + protected int getVarType(ReflectionVar v) { + try { + Field varTypeField = ReflectionVar.class.getDeclaredField("varType"); + ReflectionUtils.makeAccessible(varTypeField); + Integer varTypeValue = (Integer) varTypeField.get(v); + return varTypeValue.intValue(); + } + catch (NoSuchFieldException noSuchFieldEx) { + throw new IllegalStateException("the version of aspectjtools.jar / aspectjweaver.jar " + + "on the classpath is incompatible with this version of Spring:- expected field " + + "'varType' is not present on ReflectionVar class"); + } + catch (IllegalAccessException illegalAccessEx) { + // Famous last words... but I don't see how this can happen given the + // makeAccessible call above + throw new IllegalStateException("Unable to access ReflectionVar.varType field."); + } + } + } + + + private static abstract class InstanceOfResidueTestVisitor extends TestVisitorAdapter { + + private Class matchClass; + private boolean matches; + private int matchVarType; + + public InstanceOfResidueTestVisitor(Class matchClass, boolean defaultMatches, int matchVarType) { + this.matchClass = matchClass; + this.matches = defaultMatches; + this.matchVarType = matchVarType; + } + + public boolean instanceOfMatches(Test test) { + test.accept(this); + return matches; + } + + public void visit(Instanceof i) { + ResolvedType type = (ResolvedType) i.getType(); + int varType = getVarType((ReflectionVar) i.getVar()); + if (varType != this.matchVarType) { + return; + } + try { + Class typeClass = ClassUtils.forName(type.getName(), this.matchClass.getClassLoader()); + // Don't use ReflectionType.isAssignableFrom() as it won't be aware of (Spring) mixins + this.matches = typeClass.isAssignableFrom(this.matchClass); + } + catch (ClassNotFoundException ex) { + this.matches = false; + } + } + } + + + /** + * Check if residue of target(TYPE) kind. See SPR-3783 for more details. + */ + private static class TargetInstanceOfResidueTestVisitor extends InstanceOfResidueTestVisitor { + + public TargetInstanceOfResidueTestVisitor(Class targetClass) { + super(targetClass, false, TARGET_VAR); + } + + public boolean targetInstanceOfMatches(Test test) { + return instanceOfMatches(test); + } + } + + + /** + * Check if residue of this(TYPE) kind. See SPR-2979 for more details. + */ + private static class ThisInstanceOfResidueTestVisitor extends InstanceOfResidueTestVisitor { + + public ThisInstanceOfResidueTestVisitor(Class thisClass) { + super(thisClass, true, THIS_VAR); + } + + // TODO: Optimization: Process only if this() specifies a type and not an identifier. + public boolean thisInstanceOfMatches(Test test) { + return instanceOfMatches(test); + } + } + + + private static class SubtypeSensitiveVarTypeTestVisitor extends TestVisitorAdapter { + + private final Object thisObj = new Object(); + private final Object targetObj = new Object(); + private final Object[] argsObjs = new Object[0]; + private boolean testsSubtypeSensitiveVars = false; + + public boolean testsSubtypeSensitiveVars(Test aTest) { + aTest.accept(this); + return this.testsSubtypeSensitiveVars; + } + + public void visit(Instanceof i) { + ReflectionVar v = (ReflectionVar) i.getVar(); + Object varUnderTest = v.getBindingAtJoinPoint(thisObj,targetObj,argsObjs); + if ((varUnderTest == thisObj) || (varUnderTest == targetObj)) { + this.testsSubtypeSensitiveVars = true; + } + } + + public void visit(HasAnnotation hasAnn) { + // If you thought things were bad before, now we sink to new levels of horror... + ReflectionVar v = (ReflectionVar) hasAnn.getVar(); + int varType = getVarType(v); + if ((varType == AT_THIS_VAR) || (varType == AT_TARGET_VAR) || (varType == AT_ANNOTATION_VAR)) { + this.testsSubtypeSensitiveVars = true; + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/SimpleAspectInstanceFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/SimpleAspectInstanceFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/SimpleAspectInstanceFactory.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,91 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import org.springframework.aop.framework.AopConfigException; +import org.springframework.core.Ordered; +import org.springframework.util.Assert; + +/** + * Implementation of {@link AspectInstanceFactory} that creates a new instance + * of the specified aspect class for every {@link #getAspectInstance()} call. + * + * @author Juergen Hoeller + * @since 2.0.4 + */ +public class SimpleAspectInstanceFactory implements AspectInstanceFactory { + + private final Class aspectClass; + + + /** + * Create a new SimpleAspectInstanceFactory for the given aspect class. + * @param aspectClass the aspect class + */ + public SimpleAspectInstanceFactory(Class aspectClass) { + Assert.notNull(aspectClass, "Aspect class must not be null"); + this.aspectClass = aspectClass; + } + + /** + * Return the specified aspect class (never null). + */ + public final Class getAspectClass() { + return this.aspectClass; + } + + + public final Object getAspectInstance() { + try { + return this.aspectClass.newInstance(); + } + catch (InstantiationException ex) { + throw new AopConfigException("Unable to instantiate aspect class [" + this.aspectClass.getName() + "]", ex); + } + catch (IllegalAccessException ex) { + throw new AopConfigException("Cannot access element class [" + this.aspectClass.getName() + "]", ex); + } + } + + public ClassLoader getAspectClassLoader() { + return this.aspectClass.getClassLoader(); + } + + /** + * Determine the order for this factory's aspect instance, + * either an instance-specific order expressed through implementing + * the {@link org.springframework.core.Ordered} interface, + * or a fallback order. + * @see org.springframework.core.Ordered + * @see #getOrderForAspectClass + */ + public int getOrder() { + return getOrderForAspectClass(this.aspectClass); + } + + /** + * Determine a fallback order for the case that the aspect instance + * does not express an instance-specific order through implementing + * the {@link org.springframework.core.Ordered} interface. + *

The default implementation simply returns Ordered.LOWEST_PRECEDENCE. + * @param aspectClass the aspect class + */ + protected int getOrderForAspectClass(Class aspectClass) { + return Ordered.LOWEST_PRECEDENCE; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/SingletonAspectInstanceFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/SingletonAspectInstanceFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/SingletonAspectInstanceFactory.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import org.springframework.core.Ordered; +import org.springframework.util.Assert; + +/** + * Implementation of {@link AspectInstanceFactory} that is backed by a + * specified singleton object, returning the same instance for every + * {@link #getAspectInstance()} call. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see SimpleAspectInstanceFactory + */ +public class SingletonAspectInstanceFactory implements AspectInstanceFactory { + + private final Object aspectInstance; + + + /** + * Create a new SingletonAspectInstanceFactory for the given aspect instance. + * @param aspectInstance the singleton aspect instance + */ + public SingletonAspectInstanceFactory(Object aspectInstance) { + Assert.notNull(aspectInstance, "Aspect instance must not be null"); + this.aspectInstance = aspectInstance; + } + + + public final Object getAspectInstance() { + return this.aspectInstance; + } + + public ClassLoader getAspectClassLoader() { + return this.aspectInstance.getClass().getClassLoader(); + } + + /** + * Determine the order for this factory's aspect instance, + * either an instance-specific order expressed through implementing + * the {@link org.springframework.core.Ordered} interface, + * or a fallback order. + * @see org.springframework.core.Ordered + * @see #getOrderForAspectClass + */ + public int getOrder() { + if (this.aspectInstance instanceof Ordered) { + return ((Ordered) this.aspectInstance).getOrder(); + } + return getOrderForAspectClass(this.aspectInstance.getClass()); + } + + /** + * Determine a fallback order for the case that the aspect instance + * does not express an instance-specific order through implementing + * the {@link org.springframework.core.Ordered} interface. + *

The default implementation simply returns Ordered.LOWEST_PRECEDENCE. + * @param aspectClass the aspect class + */ + protected int getOrderForAspectClass(Class aspectClass) { + return Ordered.LOWEST_PRECEDENCE; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/TypePatternClassFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/TypePatternClassFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/TypePatternClassFilter.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,115 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj; + +import org.aspectj.weaver.tools.PointcutParser; +import org.aspectj.weaver.tools.TypePatternMatcher; + +import org.springframework.aop.ClassFilter; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +/** + * Spring AOP {@link ClassFilter} implementation using AspectJ type matching. + * + * @author Rod Johnson + * @since 2.0 + */ +public class TypePatternClassFilter implements ClassFilter { + + private String typePattern; + + private TypePatternMatcher aspectJTypePatternMatcher; + + + /** + * Creates a new instance of the {@link TypePatternClassFilter} class. + *

This is the JavaBean constructor; be sure to set the + * {@link #setTypePattern(String) typePattern} property, else a + * no doubt fatal {@link IllegalStateException} will be thrown + * when the {@link #matches(Class)} method is first invoked. + */ + public TypePatternClassFilter() { + } + + /** + * Create a fully configured {@link TypePatternClassFilter} using the + * given type pattern. + * @param typePattern the type pattern that AspectJ weaver should parse + * @throws IllegalArgumentException if the supplied typePattern is null + * or is recognized as invalid + */ + public TypePatternClassFilter(String typePattern) { + setTypePattern(typePattern); + } + + + /** + * Set the AspectJ type pattern to match. + *

Examples include: + * + * org.springframework.beans.* + * + * This will match any class or interface in the given package. + * + * org.springframework.beans.ITestBean+ + * + * This will match the ITestBean interface and any class + * that implements it. + *

These conventions are established by AspectJ, not Spring AOP. + * @param typePattern the type pattern that AspectJ weaver should parse + * @throws IllegalArgumentException if the supplied typePattern is null + * or is recognized as invalid + */ + public void setTypePattern(String typePattern) { + Assert.notNull(typePattern); + this.typePattern = typePattern; + this.aspectJTypePatternMatcher = + PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingContextClassloaderForResolution(). + parseTypePattern(replaceBooleanOperators(typePattern)); + } + + public String getTypePattern() { + return typePattern; + } + + /** + * Should the pointcut apply to the given interface or target class? + * @param clazz candidate target class + * @return whether the advice should apply to this candidate target class + * @throws IllegalStateException if no {@link #setTypePattern(String)} has been set + */ + public boolean matches(Class clazz) { + if (this.aspectJTypePatternMatcher == null) { + throw new IllegalStateException("No 'typePattern' has been set via ctor/setter."); + } + return this.aspectJTypePatternMatcher.matches(clazz); + } + + /** + * If a type pattern has been specified in XML, the user cannot + * write and as "&&" (though && will work). + * We also allow and between two sub-expressions. + *

This method converts back to && for the AspectJ pointcut parser. + */ + private String replaceBooleanOperators(String pcExpr) { + pcExpr = StringUtils.replace(pcExpr," and "," && "); + pcExpr = StringUtils.replace(pcExpr, " or ", " || "); + pcExpr = StringUtils.replace(pcExpr, " not ", " ! "); + return pcExpr; + } +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/package.html 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,14 @@ + + + +AspectJ integration package. Includes Spring AOP advice implementations for AspectJ 5 +annotation-style methods, and an AspectJExpressionPointcut: a Spring AOP Pointcut +implementation that allows use of the AspectJ pointcut expression language with the Spring AOP +runtime framework. + +

Note that use of this package does not require the use of the ajc compiler +or AspectJ load-time weaver. It is intended to enable the use of a valuable subset of AspectJ +functionality, with consistent semantics, with the proxy-based Spring AOP framework. + + + Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactory.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,341 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.Map; +import java.util.StringTokenizer; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.AjType; +import org.aspectj.lang.reflect.AjTypeSystem; +import org.aspectj.lang.reflect.PerClauseKind; + +import org.springframework.aop.aspectj.AspectJExpressionPointcut; +import org.springframework.aop.framework.AopConfigException; +import org.springframework.core.ParameterNameDiscoverer; +import org.springframework.core.PrioritizedParameterNameDiscoverer; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.util.StringUtils; + +/** + * Abstract base class for factories that can create Spring AOP Advisors + * given AspectJ classes from classes honoring the AspectJ 5 annotation syntax. + * + *

This class handles annotation parsing and validation functionality. + * It does not actually generate Spring AOP Advisors, which is deferred to subclasses. + * + * @author Rod Johnson + * @author Adrian Colyer + * @author Juergen Hoeller + * @since 2.0 + */ +public abstract class AbstractAspectJAdvisorFactory implements AspectJAdvisorFactory { + + protected static final ParameterNameDiscoverer ASPECTJ_ANNOTATION_PARAMETER_NAME_DISCOVERER = + new AspectJAnnotationParameterNameDiscoverer(); + + private static final String AJC_MAGIC = "ajc$"; + + + /** + * Find and return the first AspectJ annotation on the given method + * (there should only be one anyway...) + */ + protected static AspectJAnnotation findAspectJAnnotationOnMethod(Method aMethod) { + Class[] classesToLookFor = (Class[]) new Class[] { + Before.class, + Around.class, + After.class, + AfterReturning.class, + AfterThrowing.class, + Pointcut.class + }; + for (Class c : classesToLookFor) { + AspectJAnnotation foundAnnotation = findAnnotation(aMethod, c); + if (foundAnnotation != null) { + return foundAnnotation; + } + } + return null; + } + + private static AspectJAnnotation findAnnotation(Method method, Class toLookFor) { + A result = AnnotationUtils.findAnnotation(method, toLookFor); + if (result != null) { + return new AspectJAnnotation(result); + } + else { + return null; + } + } + + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + protected final ParameterNameDiscoverer parameterNameDiscoverer; + + + protected AbstractAspectJAdvisorFactory() { + PrioritizedParameterNameDiscoverer prioritizedParameterNameDiscoverer = new PrioritizedParameterNameDiscoverer(); + prioritizedParameterNameDiscoverer.addDiscoverer(ASPECTJ_ANNOTATION_PARAMETER_NAME_DISCOVERER); + this.parameterNameDiscoverer = prioritizedParameterNameDiscoverer; + } + + /** + * We consider something to be an AspectJ aspect suitable for use by the Spring AOP system + * if it has the @Aspect annotation, and was not compiled by ajc. The reason for this latter test + * is that aspects written in the code-style (AspectJ language) also have the annotation present + * when compiled by ajc with the -1.5 flag, yet they cannot be consumed by Spring AOP. + */ + public boolean isAspect(Class clazz) { + return (AjTypeSystem.getAjType(clazz).isAspect() && + hasAspectAnnotation(clazz) && !compiledByAjc(clazz)); + } + + private boolean hasAspectAnnotation(Class clazz) { + return clazz.isAnnotationPresent(Aspect.class); + } + + /** + * We need to detect this as "code-style" AspectJ aspects should not be + * interpreted by Spring AOP. + */ + private boolean compiledByAjc(Class clazz) { + // The AJTypeSystem goes to great lengths to provide a uniform appearance between code-style and + // annotation-style aspects. Therefore there is no 'clean' way to tell them apart. Here we rely on + // an implementation detail of the AspectJ compiler. + for (Field field : clazz.getDeclaredFields()) { + if (field.getName().startsWith(AJC_MAGIC)) { + return true; + } + } + return false; + } + + public void validate(Class aspectClass) throws AopConfigException { + // If the parent has the annotation and isn't abstract it's an error + if (aspectClass.getSuperclass().getAnnotation(Aspect.class) != null && + !Modifier.isAbstract(aspectClass.getSuperclass().getModifiers())) { + throw new AopConfigException("[" + aspectClass.getName() + "] cannot extend concrete aspect [" + + aspectClass.getSuperclass().getName() + "]"); + } + + AjType ajType = AjTypeSystem.getAjType(aspectClass); + if (!ajType.isAspect()) { + throw new NotAnAtAspectException(aspectClass); + } + if (ajType.getPerClause().getKind() == PerClauseKind.PERCFLOW) { + throw new AopConfigException(aspectClass.getName() + " uses percflow instantiation model: " + + "This is not supported in Spring AOP."); + } + if (ajType.getPerClause().getKind() == PerClauseKind.PERCFLOWBELOW) { + throw new AopConfigException(aspectClass.getName() + " uses percflowbelow instantiation model: " + + "This is not supported in Spring AOP."); + } + } + + /** + * The pointcut and advice annotations both have an "argNames" member which contains a + * comma-separated list of the argument names. We use this (if non-empty) to build the + * formal parameters for the pointcut. + */ + protected AspectJExpressionPointcut createPointcutExpression( + Method annotatedMethod, Class declarationScope, String[] pointcutParameterNames) { + + Class [] pointcutParameterTypes = new Class[0]; + if (pointcutParameterNames != null) { + pointcutParameterTypes = extractPointcutParameterTypes(pointcutParameterNames,annotatedMethod); + } + + AspectJExpressionPointcut ajexp = + new AspectJExpressionPointcut(declarationScope,pointcutParameterNames,pointcutParameterTypes); + ajexp.setLocation(annotatedMethod.toString()); + return ajexp; + } + + /** + * Create the pointcut parameters needed by aspectj based on the given argument names + * and the argument types that are available from the adviceMethod. Needs to take into + * account (ignore) any JoinPoint based arguments as these are not pointcut context but + * rather part of the advice execution context (thisJoinPoint, thisJoinPointStaticPart) + */ + private Class[] extractPointcutParameterTypes(String[] argNames, Method adviceMethod) { + Class[] ret = new Class[argNames.length]; + Class[] paramTypes = adviceMethod.getParameterTypes(); + if (argNames.length > paramTypes.length) { + throw new IllegalStateException("Expecting at least " + argNames.length + + " arguments in the advice declaration, but only found " + paramTypes.length); + } + // Make the simplifying assumption for now that all of the JoinPoint based arguments + // come first in the advice declaration. + int typeOffset = paramTypes.length - argNames.length; + for (int i = 0; i < ret.length; i++) { + ret[i] = paramTypes[i+typeOffset]; + } + return ret; + } + + + protected enum AspectJAnnotationType { + AtPointcut, + AtBefore, + AtAfter, + AtAfterReturning, + AtAfterThrowing, + AtAround + }; + + + /** + * Class modelling an AspectJ annotation, exposing its type enumeration and + * pointcut String. + */ + protected static class AspectJAnnotation { + + private static Map annotationTypes = new HashMap(); + + private static final String[] EXPRESSION_PROPERTIES = new String[]{"value", "pointcut"}; + + static { + annotationTypes.put(Pointcut.class,AspectJAnnotationType.AtPointcut); + annotationTypes.put(After.class,AspectJAnnotationType.AtAfter); + annotationTypes.put(AfterReturning.class,AspectJAnnotationType.AtAfterReturning); + annotationTypes.put(AfterThrowing.class,AspectJAnnotationType.AtAfterThrowing); + annotationTypes.put(Around.class,AspectJAnnotationType.AtAround); + annotationTypes.put(Before.class,AspectJAnnotationType.AtBefore); + } + + private final A annotation; + private AspectJAnnotationType annotationType; + private final String expression; + private final String argNames; + + public AspectJAnnotation(A aspectjAnnotation) { + this.annotation = aspectjAnnotation; + for (Class type : annotationTypes.keySet()) { + if (type.isInstance(this.annotation)) { + this.annotationType = annotationTypes.get(type); + break; + } + } + if (this.annotationType == null) { + throw new IllegalStateException("Unknown annotation type: " + this.annotation.toString()); + } + + // We know these methods exist with the same name on each object, + // but need to invoke them reflectively as there isn't a common interface. + try { + this.expression = resolveExpression(); + this.argNames = (String) + this.annotation.getClass().getMethod("argNames", (Class[]) null).invoke(this.annotation); + } + catch (Exception ex) { + throw new IllegalArgumentException(aspectjAnnotation + " cannot be an AspectJ annotation", ex); + } + } + + private String resolveExpression() throws Exception { + String expression = null; + for (int i = 0; i < EXPRESSION_PROPERTIES.length; i++) { + String methodName = EXPRESSION_PROPERTIES[i]; + Method method; + try { + method = this.annotation.getClass().getDeclaredMethod(methodName); + } + catch (NoSuchMethodException ex) { + method = null; + } + if (method != null) { + String candidate = (String) method.invoke(this.annotation); + if (StringUtils.hasText(candidate)) { + expression = candidate; + } + } + } + return expression; + } + + public AspectJAnnotationType getAnnotationType() { + return this.annotationType; + } + + public A getAnnotation() { + return this.annotation; + } + + public String getPointcutExpression() { + return this.expression; + } + + public String getArgNames() { + return this.argNames; + } + + public String toString() { + return this.annotation.toString(); + } + } + + + /** + * ParameterNameDiscoverer implementation that analyzes the arg names + * specified at the AspectJ annotation level. + */ + private static class AspectJAnnotationParameterNameDiscoverer implements ParameterNameDiscoverer { + + public String[] getParameterNames(Method method) { + if (method.getParameterTypes().length == 0) { + return new String[0]; + } + AspectJAnnotation annotation = findAspectJAnnotationOnMethod(method); + if (annotation == null) { + return null; + } + StringTokenizer strTok = new StringTokenizer(annotation.getArgNames(), ","); + if (strTok.countTokens() > 0) { + String[] names = new String[strTok.countTokens()]; + for (int i = 0; i < names.length; i++) { + names[i] = strTok.nextToken(); + } + return names; + } + else { + return null; + } + } + + public String[] getParameterNames(Constructor ctor) { + throw new UnsupportedOperationException("Spring AOP cannot handle constructor advice"); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AnnotationAwareAspectJAutoProxyCreator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AnnotationAwareAspectJAutoProxyCreator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AnnotationAwareAspectJAutoProxyCreator.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,138 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +import org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.util.Assert; + +/** + * {@link AspectJAwareAdvisorAutoProxyCreator} subclass that processes all AspectJ + * annotation aspects in the current application context, as well as Spring Advisors. + * + *

Any AspectJ annotated classes will automatically be recognized, and their + * advice applied if Spring AOP's proxy-based model is capable of applying it. + * This covers method execution joinpoints. + * + *

If the <aop:include> element is used, only @AspectJ beans with names matched by + * an include pattern will be considered as defining aspects to use for Spring auto-proxying. + * + *

Processing of Spring Advisors follows the rules established in + * {@link org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator}. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see org.springframework.aop.aspectj.annotation.AspectJAdvisorFactory + */ +public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator { + + private List includePatterns; + + private AspectJAdvisorFactory aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(); + + private BeanFactoryAspectJAdvisorsBuilder aspectJAdvisorsBuilder; + + + /** + * Set a list of regex patterns, matching eligible @AspectJ bean names. + *

Default is to consider all @AspectJ beans as eligible. + */ + public void setIncludePatterns(List patterns) { + this.includePatterns = new ArrayList(patterns.size()); + for (String patternText : patterns) { + this.includePatterns.add(Pattern.compile(patternText)); + } + } + + public void setAspectJAdvisorFactory(AspectJAdvisorFactory aspectJAdvisorFactory) { + Assert.notNull(this.aspectJAdvisorFactory, "AspectJAdvisorFactory must not be null"); + this.aspectJAdvisorFactory = aspectJAdvisorFactory; + } + + @Override + protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) { + super.initBeanFactory(beanFactory); + this.aspectJAdvisorsBuilder = + new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory); + } + + + @Override + protected List findCandidateAdvisors() { + // Add all the Spring advisors found according to superclass rules. + List advisors = super.findCandidateAdvisors(); + // Build Advisors for all AspectJ aspects in the bean factory. + advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors()); + return advisors; + } + + protected boolean isInfrastructureClass(Class beanClass) { + // Previously we setProxyTargetClass(true) in the constructor, but that has too + // broad an impact. Instead we now override isInfrastructureClass to avoid proxying + // aspects. I'm not entirely happy with that as there is no good reason not + // to advise aspects, except that it causes advice invocation to go through a + // proxy, and if the aspect implements e.g the Ordered interface it will be + // proxied by that interface and fail at runtime as the advice method is not + // defined on the interface. We could potentially relax the restriction about + // not advising aspects in the future. + return (super.isInfrastructureClass(beanClass) || this.aspectJAdvisorFactory.isAspect(beanClass)); + } + + /** + * Check whether the given aspect bean is eligible for auto-proxying. + *

If no <aop:include> elements were used then "includePatterns" will be + * null and all beans are included. If "includePatterns" is non-null, + * then one of the patterns must match. + */ + protected boolean isEligibleAspectBean(String beanName) { + if (this.includePatterns == null) { + return true; + } + else { + for (Pattern pattern : this.includePatterns) { + if (pattern.matcher(beanName).matches()) { + return true; + } + } + return false; + } + } + + + /** + * Subclass of BeanFactoryAspectJAdvisorsBuilderAdapter that delegates to + * surrounding AnnotationAwareAspectJAutoProxyCreator facilities. + */ + private class BeanFactoryAspectJAdvisorsBuilderAdapter extends BeanFactoryAspectJAdvisorsBuilder { + + public BeanFactoryAspectJAdvisorsBuilderAdapter( + ListableBeanFactory beanFactory, AspectJAdvisorFactory advisorFactory) { + super(beanFactory, advisorFactory); + } + + protected boolean isEligibleBean(String beanName) { + return AnnotationAwareAspectJAutoProxyCreator.this.isEligibleAspectBean(beanName); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AspectJAdvisorFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AspectJAdvisorFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AspectJAdvisorFactory.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,104 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import java.lang.reflect.Method; +import java.util.List; + +import org.aopalliance.aop.Advice; + +import org.springframework.aop.Advisor; +import org.springframework.aop.aspectj.AspectJExpressionPointcut; +import org.springframework.aop.framework.AopConfigException; + +/** + * Interface for factories that can create Spring AOP Advisors from classes + * annotated with AspectJ annotation syntax. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see AspectMetadata + * @see org.aspectj.lang.reflect.AjTypeSystem + */ +public interface AspectJAdvisorFactory { + + /** + * Determine whether or not the given class is an aspect, as reported + * by AspectJ's {@link org.aspectj.lang.reflect.AjTypeSystem}. + *

Will simply return false if the supposed aspect is + * invalid (such as an extension of a concrete aspect class). + * Will return true for some aspects that Spring AOP cannot process, + * such as those with unsupported instantiation models. + * Use the {@link #validate} method to handle these cases if necessary. + * @param clazz the supposed annotation-style AspectJ class + * @return whether or not this class is recognized by AspectJ as an aspect class + */ + boolean isAspect(Class clazz); + + /** + * Is the given class a valid AspectJ aspect class? + * @param aspectClass the supposed AspectJ annotation-style class to validate + * @throws AopConfigException if the class is an invalid aspect + * (which can never be legal) + * @throws NotAnAtAspectException if the class is not an aspect at all + * (which may or may not be legal, depending on the context) + */ + void validate(Class aspectClass) throws AopConfigException; + + /** + * Build Spring AOP Advisors for all annotated At-AspectJ methods + * on the specified aspect instance. + * @param aif the aspect instance factory (not the aspect instance itself + * in order to avoid eager instantiation) + * @return a list of advisors for this class + */ + List getAdvisors(MetadataAwareAspectInstanceFactory aif); + + /** + * Build a Spring AOP Advisor for the given AspectJ advice method. + * @param candidateAdviceMethod the candidate advice method + * @param aif the aspect instance factory + * @param declarationOrderInAspect the declaration order within the aspect + * @param aspectName the name of the aspect + * @return null if the method is not an AspectJ advice method + * or if it is a pointcut that will be used by other advice but will not + * create a Spring advice in its own right + */ + Advisor getAdvisor(Method candidateAdviceMethod, + MetadataAwareAspectInstanceFactory aif, int declarationOrderInAspect, String aspectName); + + /** + * Build a Spring AOP Advice for the given AspectJ advice method. + * @param candidateAdviceMethod the candidate advice method + * @param pointcut the corresponding AspectJ expression pointcut + * @param aif the aspect instance factory + * @param declarationOrderInAspect the declaration order within the aspect + * @param aspectName the name of the aspect + * @return null if the method is not an AspectJ advice method + * or if it is a pointcut that will be used by other advice but will not + * create a Spring advice in its own right + * @see org.springframework.aop.aspectj.AspectJAroundAdvice + * @see org.springframework.aop.aspectj.AspectJMethodBeforeAdvice + * @see org.springframework.aop.aspectj.AspectJAfterAdvice + * @see org.springframework.aop.aspectj.AspectJAfterReturningAdvice + * @see org.springframework.aop.aspectj.AspectJAfterThrowingAdvice + */ + Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut pointcut, + MetadataAwareAspectInstanceFactory aif, int declarationOrderInAspect, String aspectName); + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,218 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.aspectj.lang.reflect.PerClauseKind; + +import org.springframework.aop.Advisor; +import org.springframework.aop.aspectj.AspectJProxyUtils; +import org.springframework.aop.framework.AopConfigException; +import org.springframework.aop.framework.ProxyCreatorSupport; +import org.springframework.aop.support.AopUtils; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; + +/** + * AspectJ-based proxy factory, allowing for programmatic building + * of proxies which include AspectJ aspects (code style as well + * Java 5 annotation style). + * + * @author Rob Harrop + * @author Juergen Hoeller + * @author Ramnivas Laddad + * @since 2.0 + * @see #addAspect(Object) + * @see #addAspect(Class) + * @see #getProxy() + * @see #getProxy(ClassLoader) + * @see org.springframework.aop.framework.ProxyFactory + */ +public class AspectJProxyFactory extends ProxyCreatorSupport { + + /** Cache for singleton aspect instances */ + private static final Map aspectCache = new HashMap(); + + private final AspectJAdvisorFactory aspectFactory = new ReflectiveAspectJAdvisorFactory(); + + + /** + * Create a new AspectJProxyFactory. + */ + public AspectJProxyFactory() { + } + + /** + * Create a new AspectJProxyFactory. + *

Will proxy all interfaces that the given target implements. + * @param target the target object to be proxied + */ + public AspectJProxyFactory(Object target) { + Assert.notNull(target, "Target object must not be null"); + setInterfaces(ClassUtils.getAllInterfaces(target)); + setTarget(target); + } + + /** + * Create a new AspectJProxyFactory. + * No target, only interfaces. Must add interceptors. + */ + public AspectJProxyFactory(Class[] interfaces) { + setInterfaces(interfaces); + } + + + /** + * Add the supplied aspect instance to the chain. The type of the aspect instance + * supplied must be a singleton aspect. True singleton lifecycle is not honoured when + * using this method - the caller is responsible for managing the lifecycle of any + * aspects added in this way. + * @param aspectInstance the AspectJ aspect instance + */ + public void addAspect(Object aspectInstance) { + Class aspectClass = aspectInstance.getClass(); + String aspectName = aspectClass.getName(); + AspectMetadata am = createAspectMetadata(aspectClass, aspectName); + if (am.getAjType().getPerClause().getKind() != PerClauseKind.SINGLETON) { + throw new IllegalArgumentException( + "Aspect class [" + aspectClass.getName() + "] does not define a singleton aspect"); + } + addAdvisorsFromAspectInstanceFactory( + new SingletonMetadataAwareAspectInstanceFactory(aspectInstance, aspectName)); + } + + /** + * Add an aspect of the supplied type to the end of the advice chain. + * @param aspectClass the AspectJ aspect class + */ + public void addAspect(Class aspectClass) { + String aspectName = aspectClass.getName(); + AspectMetadata am = createAspectMetadata(aspectClass, aspectName); + MetadataAwareAspectInstanceFactory instanceFactory = createAspectInstanceFactory(am, aspectClass, aspectName); + addAdvisorsFromAspectInstanceFactory(instanceFactory); + } + + + /** + * Add all {@link Advisor Advisors} from the supplied {@link MetadataAwareAspectInstanceFactory} + * to the current chain. Exposes any special purpose {@link Advisor Advisors} if needed. + * @see #makeAdvisorChainAspectJCapableIfNecessary() + */ + private void addAdvisorsFromAspectInstanceFactory(MetadataAwareAspectInstanceFactory instanceFactory) { + List advisors = this.aspectFactory.getAdvisors(instanceFactory); + advisors = AopUtils.findAdvisorsThatCanApply(advisors, getTargetClass()); + addAllAdvisors((Advisor[]) advisors.toArray(new Advisor[advisors.size()])); + makeAdvisorChainAspectJCapableIfNecessary(); + } + + /** + * Create an {@link AspectMetadata} instance for the supplied aspect type. + */ + private AspectMetadata createAspectMetadata(Class aspectClass, String aspectName) { + AspectMetadata am = new AspectMetadata(aspectClass, aspectName); + if (!am.getAjType().isAspect()) { + throw new IllegalArgumentException("Class [" + aspectClass.getName() + "] is not a valid aspect type"); + } + return am; + } + + /** + * Create a {@link MetadataAwareAspectInstanceFactory} for the supplied aspect type. If the aspect type + * has no per clause, then a {@link SingletonMetadataAwareAspectInstanceFactory} is returned, otherwise + * a {@link PrototypeAspectInstanceFactory} is returned. + */ + private MetadataAwareAspectInstanceFactory createAspectInstanceFactory( + AspectMetadata am, Class aspectClass, String aspectName) { + + MetadataAwareAspectInstanceFactory instanceFactory = null; + if (am.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) { + // Create a shared aspect instance. + Object instance = getSingletonAspectInstance(aspectClass); + instanceFactory = new SingletonMetadataAwareAspectInstanceFactory(instance, aspectName); + } + else { + // Create a factory for independent aspect instances. + instanceFactory = new SimpleMetadataAwareAspectInstanceFactory(aspectClass, aspectName); + } + return instanceFactory; + } + + /** + * Add any special-purpose {@link Advisor Advisors} needed for AspectJ support + * to the chain. {@link #updateAdvisorArray() Updates} the {@link Advisor} array + * and fires {@link #adviceChanged events}. + */ + private void makeAdvisorChainAspectJCapableIfNecessary() { + if (AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(getAdvisorsInternal())) { + updateAdvisorArray(); + adviceChanged(); + } + } + + /** + * Get the singleton aspect instance for the supplied aspect type. An instance + * is created if one cannot be found in the instance cache. + */ + private Object getSingletonAspectInstance(Class aspectClass) { + synchronized (aspectCache) { + Object instance = aspectCache.get(aspectClass); + if (instance != null) { + return instance; + } + try { + instance = aspectClass.newInstance(); + aspectCache.put(aspectClass, instance); + return instance; + } + catch (InstantiationException ex) { + throw new AopConfigException("Unable to instantiate aspect class [" + aspectClass.getName() + "]", ex); + } + catch (IllegalAccessException ex) { + throw new AopConfigException("Cannot access aspect class [" + aspectClass.getName() + "]", ex); + } + } + } + + + /** + * Create a new proxy according to the settings in this factory. + *

Can be called repeatedly. Effect will vary if we've added + * or removed interfaces. Can add and remove interceptors. + *

Uses a default class loader: Usually, the thread context class loader + * (if necessary for proxy creation). + * @return the new proxy + */ + public T getProxy() { + return (T) createAopProxy().getProxy(); + } + + /** + * Create a new proxy according to the settings in this factory. + *

Can be called repeatedly. Effect will vary if we've added + * or removed interfaces. Can add and remove interceptors. + *

Uses the given class loader (if necessary for proxy creation). + * @param classLoader the class loader to create the proxy with + * @return the new proxy + */ + public T getProxy(ClassLoader classLoader) { + return (T) createAopProxy().getProxy(classLoader); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AspectMetadata.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AspectMetadata.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/AspectMetadata.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,166 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.reflect.AjType; +import org.aspectj.lang.reflect.AjTypeSystem; +import org.aspectj.lang.reflect.PerClauseKind; + +import org.springframework.aop.Pointcut; +import org.springframework.aop.aspectj.AspectJExpressionPointcut; +import org.springframework.aop.aspectj.TypePatternClassFilter; +import org.springframework.aop.framework.AopConfigException; +import org.springframework.aop.support.ComposablePointcut; + +/** + * Metadata for an AspectJ aspect class, with an additional Spring AOP pointcut + * for the per clause. + * + *

Uses AspectJ 5 AJType reflection API, so is only supported on Java 5. + * Enables us to work with different AspectJ instantiation models such as + * "singleton", "pertarget" and "perthis". + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see org.springframework.aop.aspectj.AspectJExpressionPointcut + */ +public class AspectMetadata { + + /** + * AspectJ reflection information (AspectJ 5 / Java 5 specific). + */ + private final AjType ajType; + + /** + * Spring AOP pointcut corresponding to the per clause of the + * aspect. Will be the Pointcut.TRUE canonical instance in the + * case of a singleton, otherwise an AspectJExpressionPointcut. + */ + private final Pointcut perClausePointcut; + + /** + * The name of this aspect as defined to Spring (the bean name) - + * allows us to determine if two pieces of advice come from the + * same aspect and hence their relative precedence. + */ + private String aspectName; + + + /** + * Create a new AspectMetadata instance for the given aspect class. + * @param aspectClass the aspect class + * @param aspectName the name of the aspect + */ + public AspectMetadata(Class aspectClass, String aspectName) { + this.aspectName = aspectName; + this.ajType = AjTypeSystem.getAjType(aspectClass); + + if (!this.ajType.isAspect()) { + throw new IllegalArgumentException("Class '" + aspectClass.getName() + "' is not an @AspectJ aspect"); + } + if (this.ajType.getDeclarePrecedence().length > 0) { + throw new IllegalArgumentException("DeclarePrecendence not presently supported in Spring AOP"); + } + + switch (this.ajType.getPerClause().getKind()) { + case SINGLETON : + this.perClausePointcut = Pointcut.TRUE; + return; + case PERTARGET : case PERTHIS : + AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut(); + ajexp.setLocation("@Aspect annotation on " + aspectClass.getName()); + ajexp.setExpression(findPerClause(aspectClass)); + this.perClausePointcut = ajexp; + return; + case PERTYPEWITHIN : + // Works with a type pattern + this.perClausePointcut = new ComposablePointcut(new TypePatternClassFilter(findPerClause(aspectClass))); + return; + default : + throw new AopConfigException( + "PerClause " + ajType.getPerClause().getKind() + " not supported by Spring AOP for " + aspectClass); + } + } + + /** + * Extract contents from String of form pertarget(contents). + */ + private String findPerClause(Class aspectClass) { + // TODO when AspectJ provides this, we can remove this hack. Hence we don't + // bother to make it elegant. Or efficient. Or robust :-) + String str = aspectClass.getAnnotation(Aspect.class).value(); + str = str.substring(str.indexOf("(") + 1); + str = str.substring(0, str.length() - 1); + return str; + } + + + /** + * Return AspectJ reflection information. + */ + public AjType getAjType() { + return this.ajType; + } + + /** + * Return the aspect class. + */ + public Class getAspectClass() { + return this.ajType.getJavaClass(); + } + + /** + * Return the aspect class. + */ + public String getAspectName() { + return this.aspectName; + } + + /** + * Return a Spring pointcut expression for a singleton aspect. + * (e.g. Pointcut.TRUE if it's a singleton). + */ + public Pointcut getPerClausePointcut() { + return this.perClausePointcut; + } + + /** + * Return whether the aspect is defined as "perthis" or "pertarget". + */ + public boolean isPerThisOrPerTarget() { + PerClauseKind kind = getAjType().getPerClause().getKind(); + return (kind == PerClauseKind.PERTARGET || kind == PerClauseKind.PERTHIS); + } + + /** + * Return whether the aspect is defined as "pertypewithin". + */ + public boolean isPerTypeWithin() { + PerClauseKind kind = getAjType().getPerClause().getKind(); + return (kind == PerClauseKind.PERTYPEWITHIN); + } + + /** + * Return whether the aspect needs to be lazily instantiated. + */ + public boolean isLazilyInstantiated() { + return (isPerThisOrPerTarget() || isPerTypeWithin()); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/BeanFactoryAspectInstanceFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/BeanFactoryAspectInstanceFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/BeanFactoryAspectInstanceFactory.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,122 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.util.ClassUtils; + +/** + * AspectInstanceFactory backed by a Spring + * {@link org.springframework.beans.factory.BeanFactory}. + * + *

Note that this may instantiate multiple times if using a prototype, + * which probably won't give the semantics you expect. + * Use a {@link LazySingletonAspectInstanceFactoryDecorator} + * to wrap this to ensure only one new aspect comes back. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see org.springframework.beans.factory.BeanFactory + * @see LazySingletonAspectInstanceFactoryDecorator + */ +public class BeanFactoryAspectInstanceFactory implements MetadataAwareAspectInstanceFactory { + + private final BeanFactory beanFactory; + + private final String name; + + private final AspectMetadata aspectMetadata; + + + /** + * Create a BeanFactoryAspectInstanceFactory. AspectJ will be called to + * introspect to create AJType metadata using the type returned for the + * given bean name from the BeanFactory. + * @param beanFactory BeanFactory to obtain instance(s) from + * @param name name of the bean + */ + public BeanFactoryAspectInstanceFactory(BeanFactory beanFactory, String name) { + this(beanFactory, name, beanFactory.getType(name)); + } + + /** + * Create a BeanFactoryAspectInstanceFactory, providing a type that AspectJ should + * introspect to create AJType metadata. Use if the BeanFactory may consider the type + * to be a subclass (as when using CGLIB), and the information should relate to a superclass. + * @param beanFactory BeanFactory to obtain instance(s) from + * @param name the name of the bean + * @param type the type that should be introspected by AspectJ + */ + public BeanFactoryAspectInstanceFactory(BeanFactory beanFactory, String name, Class type) { + this.beanFactory = beanFactory; + this.name = name; + this.aspectMetadata = new AspectMetadata(type, name); + } + + + public Object getAspectInstance() { + return this.beanFactory.getBean(this.name); + } + + public ClassLoader getAspectClassLoader() { + if (this.beanFactory instanceof ConfigurableBeanFactory) { + return ((ConfigurableBeanFactory) this.beanFactory).getBeanClassLoader(); + } + else { + return ClassUtils.getDefaultClassLoader(); + } + } + + public AspectMetadata getAspectMetadata() { + return this.aspectMetadata; + } + + /** + * Determine the order for this factory's target aspect, either + * an instance-specific order expressed through implementing the + * {@link org.springframework.core.Ordered} interface (only + * checked for singleton beans), or an order expressed through the + * {@link org.springframework.core.annotation.Order} annotation + * at the class level. + * @see org.springframework.core.Ordered + * @see org.springframework.core.annotation.Order + */ + public int getOrder() { + Class type = this.beanFactory.getType(this.name); + if (type != null) { + if (Ordered.class.isAssignableFrom(type) && this.beanFactory.isSingleton(this.name)) { + return ((Ordered) this.beanFactory.getBean(this.name)).getOrder(); + } + Order order = (Order) type.getAnnotation(Order.class); + if (order != null) { + return order.value(); + } + } + return Ordered.LOWEST_PRECEDENCE; + } + + + @Override + public String toString() { + return getClass().getSimpleName() + ": bean name '" + this.name + "'"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/BeanFactoryAspectJAdvisorsBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/BeanFactoryAspectJAdvisorsBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/BeanFactoryAspectJAdvisorsBuilder.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,164 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.aspectj.lang.reflect.PerClauseKind; + +import org.springframework.aop.Advisor; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.util.Assert; + +/** + * Helper for retrieving @AspectJ beans from a BeanFactory and building + * Spring Advisors based on them, for use with auto-proxying. + * + * @author Juergen Hoeller + * @since 2.0.2 + * @see AnnotationAwareAspectJAutoProxyCreator + */ +public class BeanFactoryAspectJAdvisorsBuilder { + + private final ListableBeanFactory beanFactory; + + private final AspectJAdvisorFactory advisorFactory; + + private List aspectBeanNames; + + private final Map> advisorsCache = new HashMap>(); + + private final Map aspectFactoryCache = + new HashMap(); + + + /** + * Create a new BeanFactoryAspectJAdvisorsBuilder for the given BeanFactory. + * @param beanFactory the ListableBeanFactory to scan + */ + public BeanFactoryAspectJAdvisorsBuilder(ListableBeanFactory beanFactory) { + this(beanFactory, new ReflectiveAspectJAdvisorFactory()); + } + + /** + * Create a new BeanFactoryAspectJAdvisorsBuilder for the given BeanFactory. + * @param beanFactory the ListableBeanFactory to scan + * @param advisorFactory the AspectJAdvisorFactory to build each Advisor with + */ + public BeanFactoryAspectJAdvisorsBuilder(ListableBeanFactory beanFactory, AspectJAdvisorFactory advisorFactory) { + Assert.notNull(beanFactory, "ListableBeanFactory must not be null"); + Assert.notNull(advisorFactory, "AspectJAdvisorFactory must not be null"); + this.beanFactory = beanFactory; + this.advisorFactory = advisorFactory; + } + + + /** + * Look for AspectJ-annotated aspect beans in the current bean factory, + * and return to a list of Spring AOP Advisors representing them. + *

Creates a Spring Advisor for each AspectJ advice method. + * @return the list of {@link org.springframework.aop.Advisor} beans + * @see #isEligibleBean + */ + public List buildAspectJAdvisors() { + List aspectNames = null; + + synchronized (this) { + aspectNames = this.aspectBeanNames; + if (aspectNames == null) { + List advisors = new LinkedList(); + aspectNames = new LinkedList(); + String[] beanNames = + BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Object.class, true, false); + for (String beanName : beanNames) { + if (!isEligibleBean(beanName)) { + continue; + } + // We must be careful not to instantiate beans eagerly as in this + // case they would be cached by the Spring container but would not + // have been weaved + Class beanType = this.beanFactory.getType(beanName); + if (beanType == null) { + continue; + } + if (this.advisorFactory.isAspect(beanType)) { + aspectNames.add(beanName); + AspectMetadata amd = new AspectMetadata(beanType, beanName); + if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) { + MetadataAwareAspectInstanceFactory factory = + new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName); + List classAdvisors = this.advisorFactory.getAdvisors(factory); + if (this.beanFactory.isSingleton(beanName)) { + this.advisorsCache.put(beanName, classAdvisors); + } + else { + this.aspectFactoryCache.put(beanName, factory); + } + advisors.addAll(classAdvisors); + } + else { + // Per target or per this. + if (this.beanFactory.isSingleton(beanName)) { + throw new IllegalArgumentException("Bean with name '" + beanName + + "' is a singleton, but aspect instantiation model is not singleton"); + } + MetadataAwareAspectInstanceFactory factory = + new PrototypeAspectInstanceFactory(this.beanFactory, beanName); + this.aspectFactoryCache.put(beanName, factory); + advisors.addAll(this.advisorFactory.getAdvisors(factory)); + } + } + } + this.aspectBeanNames = aspectNames; + return advisors; + } + } + + if (aspectNames.isEmpty()) { + return Collections.EMPTY_LIST; + } + List advisors = new LinkedList(); + for (Iterator it = aspectNames.iterator(); it.hasNext();) { + String aspectName = (String) it.next(); + List cachedAdvisors = this.advisorsCache.get(aspectName); + if (cachedAdvisors != null) { + advisors.addAll(cachedAdvisors); + } + else { + MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName); + advisors.addAll(this.advisorFactory.getAdvisors(factory)); + } + } + return advisors; + } + + /** + * Return whether the aspect bean with the given name is eligible. + * @param beanName the name of the aspect bean + * @return whether the bean is eligible + */ + protected boolean isEligibleBean(String beanName) { + return true; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/InstantiationModelAwarePointcutAdvisorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/InstantiationModelAwarePointcutAdvisorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/InstantiationModelAwarePointcutAdvisorImpl.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,263 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import java.lang.reflect.Method; + +import org.aopalliance.aop.Advice; +import org.aspectj.lang.reflect.PerClauseKind; + +import org.springframework.aop.Pointcut; +import org.springframework.aop.aspectj.AspectJExpressionPointcut; +import org.springframework.aop.aspectj.AspectJPrecedenceInformation; +import org.springframework.aop.aspectj.InstantiationModelAwarePointcutAdvisor; +import org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactory.AspectJAnnotation; +import org.springframework.aop.support.DynamicMethodMatcherPointcut; +import org.springframework.aop.support.Pointcuts; + +/** + * Internal implementation of AspectJPointcutAdvisor. + * Note that there will be one instance of this advisor for each target method. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + */ +class InstantiationModelAwarePointcutAdvisorImpl + implements InstantiationModelAwarePointcutAdvisor, AspectJPrecedenceInformation { + + private final AspectJExpressionPointcut declaredPointcut; + + private Pointcut pointcut; + + private final MetadataAwareAspectInstanceFactory aspectInstanceFactory; + + private final Method method; + + private final boolean lazy; + + private final AspectJAdvisorFactory atAspectJAdvisorFactory; + + private Advice instantiatedAdvice; + + private int declarationOrder; + + private String aspectName; + + private Boolean isBeforeAdvice = null; + + private Boolean isAfterAdvice = null; + + + public InstantiationModelAwarePointcutAdvisorImpl( + AspectJAdvisorFactory af, + AspectJExpressionPointcut ajexp, + MetadataAwareAspectInstanceFactory aif, + Method method, + int declarationOrderInAspect, + String aspectName) { + + this.declaredPointcut = ajexp; + this.method = method; + this.atAspectJAdvisorFactory = af; + this.aspectInstanceFactory = aif; + this.declarationOrder = declarationOrderInAspect; + this.aspectName = aspectName; + + if (aif.getAspectMetadata().isLazilyInstantiated()) { + // Static part of the pointcut is a lazy type. + Pointcut preInstantiationPointcut = + Pointcuts.union(aif.getAspectMetadata().getPerClausePointcut(), this.declaredPointcut); + + // Make it dynamic: must mutate from pre-instantiation to post-instantiation state. + // If it's not a dynamic pointcut, it may be optimized out + // by the Spring AOP infrastructure after the first evaluation. + this.pointcut = new PerTargetInstantiationModelPointcut(this.declaredPointcut, preInstantiationPointcut, aif); + this.lazy = true; + } + else { + // A singleton aspect. + this.instantiatedAdvice = instantiateAdvice(this.declaredPointcut); + this.pointcut = declaredPointcut; + this.lazy = false; + } + } + + + /** + * The pointcut for Spring AOP to use. Actual behaviour of the pointcut will change + * depending on the state of the advice. + */ + public Pointcut getPointcut() { + return this.pointcut; + } + + /** + * This is only of interest for Spring AOP: AspectJ instantiation semantics + * are much richer. In AspectJ terminology, all a return of true + * means here is that the aspect is not a SINGLETON. + */ + public boolean isPerInstance() { + return (getAspectMetadata().getAjType().getPerClause().getKind() != PerClauseKind.SINGLETON); + } + + /** + * Return the AspectJ AspectMetadata for this advisor. + */ + public AspectMetadata getAspectMetadata() { + return this.aspectInstanceFactory.getAspectMetadata(); + } + + /** + * Lazily instantiate advice if necessary. + */ + public synchronized Advice getAdvice() { + if (this.instantiatedAdvice == null) { + this.instantiatedAdvice = instantiateAdvice(this.declaredPointcut); + } + return this.instantiatedAdvice; + } + + public boolean isLazy() { + return this.lazy; + } + + public synchronized boolean isAdviceInstantiated() { + return (this.instantiatedAdvice != null); + } + + + private Advice instantiateAdvice(AspectJExpressionPointcut pcut) { + return this.atAspectJAdvisorFactory.getAdvice( + this.method, pcut, this.aspectInstanceFactory, this.declarationOrder, this.aspectName); + } + + public MetadataAwareAspectInstanceFactory getAspectInstanceFactory() { + return this.aspectInstanceFactory; + } + + public AspectJExpressionPointcut getDeclaredPointcut() { + return this.declaredPointcut; + } + + public int getOrder() { + return this.aspectInstanceFactory.getOrder(); + } + + public String getAspectName() { + return this.aspectName; + } + + public int getDeclarationOrder() { + return this.declarationOrder; + } + + public boolean isBeforeAdvice() { + if (this.isBeforeAdvice == null) { + determineAdviceType(); + } + return this.isBeforeAdvice; + } + + public boolean isAfterAdvice() { + if (this.isAfterAdvice == null) { + determineAdviceType(); + } + return this.isAfterAdvice; + } + + /** + * Duplicates some logic from getAdvice, but importantly does not force + * creation of the advice. + */ + private void determineAdviceType() { + AspectJAnnotation aspectJAnnotation = + AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(this.method); + if (aspectJAnnotation == null) { + this.isBeforeAdvice = false; + this.isAfterAdvice = false; + } + else { + switch (aspectJAnnotation.getAnnotationType()) { + case AtAfter: + case AtAfterReturning: + case AtAfterThrowing: + this.isAfterAdvice = true; + this.isBeforeAdvice = false; + break; + case AtAround: + case AtPointcut: + this.isAfterAdvice = false; + this.isBeforeAdvice = false; + break; + case AtBefore: + this.isAfterAdvice = false; + this.isBeforeAdvice = true; + } + } + } + + + @Override + public String toString() { + return "InstantiationModelAwarePointcutAdvisor: expression [" + getDeclaredPointcut().getExpression() + + "]; advice method [" + this.method + "]; perClauseKind=" + + this.aspectInstanceFactory.getAspectMetadata().getAjType().getPerClause().getKind(); + + } + + + /** + * Pointcut implementation that changes its behaviour when the advice is instantiated. + * Note that this is a dynamic pointcut. Otherwise it might + * be optimized out if it does not at first match statically. + */ + private class PerTargetInstantiationModelPointcut extends DynamicMethodMatcherPointcut { + + private final AspectJExpressionPointcut declaredPointcut; + + private final Pointcut preInstantiationPointcut; + + private LazySingletonAspectInstanceFactoryDecorator aspectInstanceFactory; + + private PerTargetInstantiationModelPointcut(AspectJExpressionPointcut declaredPointcut, + Pointcut preInstantiationPointcut, MetadataAwareAspectInstanceFactory aspectInstanceFactory) { + this.declaredPointcut = declaredPointcut; + this.preInstantiationPointcut = preInstantiationPointcut; + if (aspectInstanceFactory instanceof LazySingletonAspectInstanceFactoryDecorator) { + this.aspectInstanceFactory = (LazySingletonAspectInstanceFactoryDecorator) aspectInstanceFactory; + } + } + + @Override + public boolean matches(Method method, Class targetClass) { + // We're either instantiated and matching on declared pointcut, or uninstantiated matching on either pointcut + return (isAspectMaterialized() && this.declaredPointcut.matches(method, targetClass)) || + this.preInstantiationPointcut.getMethodMatcher().matches(method, targetClass); + } + + public boolean matches(Method method, Class targetClass, Object[] args) { + // This can match only on declared pointcut. + return (isAspectMaterialized() && this.declaredPointcut.matches(method, targetClass)); + } + + private boolean isAspectMaterialized() { + return (this.aspectInstanceFactory == null || this.aspectInstanceFactory.isMaterialized()); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/LazySingletonAspectInstanceFactoryDecorator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/LazySingletonAspectInstanceFactoryDecorator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/LazySingletonAspectInstanceFactoryDecorator.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import org.springframework.core.Ordered; +import org.springframework.util.Assert; + +/** + * Decorator to cause a MetadataAwareAspectInstanceFactory to instantiate only once. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + */ +public class LazySingletonAspectInstanceFactoryDecorator implements MetadataAwareAspectInstanceFactory { + + private final MetadataAwareAspectInstanceFactory maaif; + + private Object materialized; + + + /** + * Create a new lazily initializing decorator for the given AspectInstanceFactory. + * @param maaif the MetadataAwareAspectInstanceFactory to decorate + */ + public LazySingletonAspectInstanceFactoryDecorator(MetadataAwareAspectInstanceFactory maaif) { + Assert.notNull(maaif, "AspectInstanceFactory must not be null"); + this.maaif = maaif; + } + + public synchronized Object getAspectInstance() { + if (this.materialized == null) { + this.materialized = this.maaif.getAspectInstance(); + } + return this.materialized; + } + + public ClassLoader getAspectClassLoader() { + return this.maaif.getAspectClassLoader(); + } + + public boolean isMaterialized() { + return (this.materialized != null); + } + + public AspectMetadata getAspectMetadata() { + return this.maaif.getAspectMetadata(); + } + + public int getOrder() { + if (this.maaif instanceof Ordered) { + return ((Ordered) this.maaif).getOrder(); + } + return Ordered.LOWEST_PRECEDENCE; + } + + + @Override + public String toString() { + return "LazySingletonAspectInstanceFactoryDecorator: decorating " + this.maaif; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/MetadataAwareAspectInstanceFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/MetadataAwareAspectInstanceFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/MetadataAwareAspectInstanceFactory.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import org.springframework.aop.aspectj.AspectInstanceFactory; + +/** + * Subinterface of {@link org.springframework.aop.aspectj.AspectInstanceFactory} + * that returns {@link AspectMetadata} associated with AspectJ-annotated classes. + * + *

Ideally, AspectInstanceFactory would include this method itself, but because + * AspectMetadata uses Java-5-only {@link org.aspectj.lang.reflect.AjType}, + * we need to split out this subinterface. + * + * @author Rod Johnson + * @since 2.0 + * @see AspectMetadata + * @see org.aspectj.lang.reflect.AjType + */ +public interface MetadataAwareAspectInstanceFactory extends AspectInstanceFactory { + + /** + * Return the AspectJ AspectMetadata for this factory's aspect. + * @return the aspect metadata + */ + AspectMetadata getAspectMetadata(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/NotAnAtAspectException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/NotAnAtAspectException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/NotAnAtAspectException.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import org.springframework.aop.framework.AopConfigException; + +/** + * Extension of AopConfigException thrown when trying to perform + * an advisor generation operation on a class that is not an + * AspectJ annotation-style aspect. + * + * @author Rod Johnson + * @since 2.0 + */ +public class NotAnAtAspectException extends AopConfigException { + + private Class nonAspectClass; + + + /** + * Create a new NotAnAtAspectException for the given class. + * @param nonAspectClass the offending class + */ + public NotAnAtAspectException(Class nonAspectClass) { + super(nonAspectClass.getName() + " is not an @AspectJ aspect"); + this.nonAspectClass = nonAspectClass; + } + + /** + * Returns the offending class. + */ + public Class getNonAspectClass() { + return this.nonAspectClass; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/PrototypeAspectInstanceFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/PrototypeAspectInstanceFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/PrototypeAspectInstanceFactory.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import org.springframework.beans.factory.BeanFactory; + +/** + * AspectInstanceFactory backed by a BeanFactory-provided prototype, + * enforcing prototype semantics. + * + *

Note that this may instantiate multiple times, which probably won't give the + * semantics you expect. Use a {@link LazySingletonAspectInstanceFactoryDecorator} + * to wrap this to ensure only one new aspect comes back. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see org.springframework.beans.factory.BeanFactory + * @see LazySingletonAspectInstanceFactoryDecorator + */ +public class PrototypeAspectInstanceFactory extends BeanFactoryAspectInstanceFactory { + + /** + * Create a PrototypeAspectInstanceFactory. AspectJ will be called to + * introspect to create AJType metadata using the type returned for the + * given bean name from the BeanFactory. + * @param beanFactory the BeanFactory to obtain instance(s) from + * @param name the name of the bean + */ + public PrototypeAspectInstanceFactory(BeanFactory beanFactory, String name) { + super(beanFactory, name); + if (!beanFactory.isPrototype(name)) { + throw new IllegalArgumentException( + "Cannot use PrototypeAspectInstanceFactory with bean named '" + name + "': not a prototype"); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/ReflectiveAspectJAdvisorFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/ReflectiveAspectJAdvisorFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/ReflectiveAspectJAdvisorFactory.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,239 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.LinkedList; +import java.util.List; + +import org.aopalliance.aop.Advice; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.DeclareParents; +import org.aspectj.lang.annotation.Pointcut; + +import org.springframework.aop.Advisor; +import org.springframework.aop.MethodBeforeAdvice; +import org.springframework.aop.aspectj.AbstractAspectJAdvice; +import org.springframework.aop.aspectj.AspectJAfterAdvice; +import org.springframework.aop.aspectj.AspectJAfterReturningAdvice; +import org.springframework.aop.aspectj.AspectJAfterThrowingAdvice; +import org.springframework.aop.aspectj.AspectJAroundAdvice; +import org.springframework.aop.aspectj.AspectJExpressionPointcut; +import org.springframework.aop.aspectj.AspectJMethodBeforeAdvice; +import org.springframework.aop.aspectj.DeclareParentsAdvisor; +import org.springframework.aop.framework.AopConfigException; +import org.springframework.aop.support.DefaultPointcutAdvisor; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; + +/** + * Factory that can create Spring AOP Advisors given AspectJ classes from + * classes honoring the AspectJ 5 annotation syntax, using reflection to + * invoke the corresponding advice methods. + * + * @author Rod Johnson + * @author Adrian Colyer + * @author Juergen Hoeller + * @author Ramnivas Laddad + * @since 2.0 + */ +public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFactory { + + public List getAdvisors(MetadataAwareAspectInstanceFactory maaif) { + final Class aspectClass = maaif.getAspectMetadata().getAspectClass(); + final String aspectName = maaif.getAspectMetadata().getAspectName(); + validate(aspectClass); + + // We need to wrap the MetadataAwareAspectInstanceFactory with a decorator + // so that it will only instantiate once. + final MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory = + new LazySingletonAspectInstanceFactoryDecorator(maaif); + + final List advisors = new LinkedList(); + ReflectionUtils.doWithMethods(aspectClass, new ReflectionUtils.MethodCallback() { + public void doWith(Method method) throws IllegalArgumentException { + // Exclude pointcuts + if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) { + Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName); + if (advisor != null) { + advisors.add(advisor); + } + } + } + }); + + // If it's a per target aspect, emit the dummy instantiating aspect. + if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) { + Advisor instantiationAdvisor = new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory); + advisors.add(0, instantiationAdvisor); + } + + // Find introduction fields. + for (Field field : aspectClass.getDeclaredFields()) { + Advisor advisor = getDeclareParentsAdvisor(field); + if (advisor != null) { + advisors.add(advisor); + } + } + + return advisors; + } + + /** + * Build a {@link org.springframework.aop.aspectj.DeclareParentsAdvisor} + * for the given introduction field. + *

Resulting Advisors will need to be evaluated for targets. + * @param introductionField the field to introspect + * @return null if not an Advisor + */ + private Advisor getDeclareParentsAdvisor(Field introductionField) { + DeclareParents declareParents = (DeclareParents) introductionField.getAnnotation(DeclareParents.class); + if (declareParents == null) { + // Not an introduction field + return null; + } + + if (DeclareParents.class.equals(declareParents.defaultImpl())) { + // This is what comes back if it wasn't set. This seems bizarre... + // TODO this restriction possibly should be relaxed + throw new IllegalStateException("defaultImpl must be set on DeclareParents"); + } + + return new DeclareParentsAdvisor( + introductionField.getType(), declareParents.value(), declareParents.defaultImpl()); + } + + + public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aif, + int declarationOrderInAspect, String aspectName) { + + validate(aif.getAspectMetadata().getAspectClass()); + + AspectJExpressionPointcut ajexp = + getPointcut(candidateAdviceMethod, aif.getAspectMetadata().getAspectClass()); + if (ajexp == null) { + return null; + } + return new InstantiationModelAwarePointcutAdvisorImpl( + this, ajexp, aif, candidateAdviceMethod, declarationOrderInAspect, aspectName); + } + + private AspectJExpressionPointcut getPointcut(Method candidateAdviceMethod, Class candidateAspectClass) { + AspectJAnnotation aspectJAnnotation = + AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod); + if (aspectJAnnotation == null) { + return null; + } + AspectJExpressionPointcut ajexp = + new AspectJExpressionPointcut(candidateAspectClass, new String[0], new Class[0]); + ajexp.setExpression(aspectJAnnotation.getPointcutExpression()); + return ajexp; + } + + + public Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut ajexp, + MetadataAwareAspectInstanceFactory aif, int declarationOrderInAspect, String aspectName) { + + Class candidateAspectClass = aif.getAspectMetadata().getAspectClass(); + validate(candidateAspectClass); + + AspectJAnnotation aspectJAnnotation = + AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod); + if (aspectJAnnotation == null) { + return null; + } + + // If we get here, we know we have an AspectJ method. + // Check that it's an AspectJ-annotated class + if (!isAspect(candidateAspectClass)) { + throw new AopConfigException("Advice must be declared inside an aspect type: " + + "Offending method '" + candidateAdviceMethod + "' in class [" + + candidateAspectClass.getName() + "]"); + } + + if (logger.isDebugEnabled()) { + logger.debug("Found AspectJ method: " + candidateAdviceMethod); + } + + AbstractAspectJAdvice springAdvice; + + switch (aspectJAnnotation.getAnnotationType()) { + case AtBefore: + springAdvice = new AspectJMethodBeforeAdvice(candidateAdviceMethod, ajexp, aif); + break; + case AtAfter: + springAdvice = new AspectJAfterAdvice(candidateAdviceMethod, ajexp, aif); + break; + case AtAfterReturning: + springAdvice = new AspectJAfterReturningAdvice(candidateAdviceMethod, ajexp, aif); + AfterReturning afterReturningAnnotation = (AfterReturning) aspectJAnnotation.getAnnotation(); + if (StringUtils.hasText(afterReturningAnnotation.returning())) { + springAdvice.setReturningName(afterReturningAnnotation.returning()); + } + break; + case AtAfterThrowing: + springAdvice = new AspectJAfterThrowingAdvice(candidateAdviceMethod, ajexp, aif); + AfterThrowing afterThrowingAnnotation = (AfterThrowing) aspectJAnnotation.getAnnotation(); + if (StringUtils.hasText(afterThrowingAnnotation.throwing())) { + springAdvice.setThrowingName(afterThrowingAnnotation.throwing()); + } + break; + case AtAround: + springAdvice = new AspectJAroundAdvice(candidateAdviceMethod, ajexp, aif); + break; + case AtPointcut: + if (logger.isDebugEnabled()) { + logger.debug("Processing pointcut '" + candidateAdviceMethod.getName() + "'"); + } + return null; + default: + throw new UnsupportedOperationException( + "Unsupported advice type on method " + candidateAdviceMethod); + } + + // Now to configure the advice... + springAdvice.setAspectName(aspectName); + springAdvice.setDeclarationOrder(declarationOrderInAspect); + String[] argNames = this.parameterNameDiscoverer.getParameterNames(candidateAdviceMethod); + if (argNames != null) { + springAdvice.setArgumentNamesFromStringArray(argNames); + } + springAdvice.calculateArgumentBindings(); + return springAdvice; + } + + /** + * Synthetic advisor that instantiates the aspect. + * Triggered by per-clause pointcut on non-singleton aspect. + * The advice has no effect. + */ + protected static class SyntheticInstantiationAdvisor extends DefaultPointcutAdvisor { + + public SyntheticInstantiationAdvisor(final MetadataAwareAspectInstanceFactory aif) { + super(aif.getAspectMetadata().getPerClausePointcut(), new MethodBeforeAdvice() { + public void before(Method method, Object[] args, Object target) { + // Simply instantiate the aspect + aif.getAspectInstance(); + } + }); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/SimpleMetadataAwareAspectInstanceFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/SimpleMetadataAwareAspectInstanceFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/SimpleMetadataAwareAspectInstanceFactory.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import org.springframework.aop.aspectj.SimpleAspectInstanceFactory; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; + +/** + * Implementation of {@link MetadataAwareAspectInstanceFactory} that + * creates a new instance of the specified aspect class for every + * {@link #getAspectInstance()} call. + * + * @author Juergen Hoeller + * @since 2.0.4 + */ +public class SimpleMetadataAwareAspectInstanceFactory extends SimpleAspectInstanceFactory + implements MetadataAwareAspectInstanceFactory { + + private final AspectMetadata metadata; + + + /** + * Create a new SimpleMetadataAwareAspectInstanceFactory for the given aspect class. + * @param aspectClass the aspect class + * @param aspectName the aspect name + */ + public SimpleMetadataAwareAspectInstanceFactory(Class aspectClass, String aspectName) { + super(aspectClass); + this.metadata = new AspectMetadata(aspectClass, aspectName); + } + + + public final AspectMetadata getAspectMetadata() { + return this.metadata; + } + + /** + * Determine a fallback order for the case that the aspect instance + * does not express an instance-specific order through implementing + * the {@link org.springframework.core.Ordered} interface. + *

The default implementation simply returns Ordered.LOWEST_PRECEDENCE. + * @param aspectClass the aspect class + */ + protected int getOrderForAspectClass(Class aspectClass) { + Order order = (Order) aspectClass.getAnnotation(Order.class); + if (order != null) { + return order.value(); + } + return Ordered.LOWEST_PRECEDENCE; + } + +} + Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/SingletonMetadataAwareAspectInstanceFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/SingletonMetadataAwareAspectInstanceFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/SingletonMetadataAwareAspectInstanceFactory.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.annotation; + +import org.springframework.aop.aspectj.SingletonAspectInstanceFactory; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; + +/** + * Implementation of {@link MetadataAwareAspectInstanceFactory} that is backed + * by a specified singleton object, returning the same instance for every + * {@link #getAspectInstance()} call. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see SimpleMetadataAwareAspectInstanceFactory + */ +public class SingletonMetadataAwareAspectInstanceFactory extends SingletonAspectInstanceFactory + implements MetadataAwareAspectInstanceFactory { + + private final AspectMetadata metadata; + + + /** + * Create a new SingletonMetadataAwareAspectInstanceFactory for the given aspect. + * @param aspectInstance the singleton aspect instance + * @param aspectName the name of the aspect + */ + public SingletonMetadataAwareAspectInstanceFactory(Object aspectInstance, String aspectName) { + super(aspectInstance); + this.metadata = new AspectMetadata(aspectInstance.getClass(), aspectName); + } + + + public final AspectMetadata getAspectMetadata() { + return this.metadata; + } + + /** + * Check whether the aspect class carries an + * {@link org.springframework.core.annotation.Order} annotation, + * falling back to Ordered.LOWEST_PRECEDENCE. + * @see org.springframework.core.annotation.Order + */ + protected int getOrderForAspectClass(Class aspectClass) { + Order order = (Order) aspectClass.getAnnotation(Order.class); + if (order != null) { + return order.value(); + } + return Ordered.LOWEST_PRECEDENCE; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/annotation/package.html 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,9 @@ + + + +Classes enabling AspectJ 5 @Annotated classes to be used in Spring AOP. + +

Normally to be used through an AspectJAutoProxyCreator rather than directly. + + + Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,162 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.autoproxy; + +import java.util.Comparator; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import org.aopalliance.aop.Advice; +import org.aspectj.util.PartialOrder; +import org.aspectj.util.PartialOrder.PartialComparable; + +import org.springframework.aop.Advisor; +import org.springframework.aop.aspectj.AbstractAspectJAdvice; +import org.springframework.aop.aspectj.AspectJPointcutAdvisor; +import org.springframework.aop.aspectj.AspectJProxyUtils; +import org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator; +import org.springframework.aop.interceptor.ExposeInvocationInterceptor; +import org.springframework.core.Ordered; +import org.springframework.util.ClassUtils; + +/** + * {@link org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator} + * subclass that exposes AspectJ's invocation context and understands AspectJ's rules + * for advice precedence when multiple pieces of advice come from the same aspect. + * + * @author Adrian Colyer + * @author Juergen Hoeller + * @author Ramnivas Laddad + * @since 2.0 + */ +public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator { + + private static final Comparator DEFAULT_PRECEDENCE_COMPARATOR = new AspectJPrecedenceComparator(); + + + /** + * Sort the rest by AspectJ precedence. If two pieces of advice have + * come from the same aspect they will have the same order. + * Advice from the same aspect is then further ordered according to the + * following rules: + *

+ *

Important: Advisors are sorted in precedence order, from highest + * precedence to lowest. "On the way in" to a join point, the highest precedence + * advisor should run first. "On the way out" of a join point, the highest precedence + * advisor should run last. + */ + protected List sortAdvisors(List advisors) { + // build list for sorting + List partiallyComparableAdvisors = new LinkedList(); + for (Iterator it = advisors.iterator(); it.hasNext();) { + Advisor element = (Advisor) it.next(); + PartiallyComparableAdvisorHolder advisor = + new PartiallyComparableAdvisorHolder(element, DEFAULT_PRECEDENCE_COMPARATOR); + partiallyComparableAdvisors.add(advisor); + } + + // sort it + List sorted = PartialOrder.sort(partiallyComparableAdvisors); + if (sorted == null) { + // TODO: work much harder to give a better error message here. + throw new IllegalArgumentException("Advice precedence circularity error"); + } + + // extract results again + List result = new LinkedList(); + for (Iterator it = sorted.iterator(); it.hasNext();) { + PartiallyComparableAdvisorHolder pcAdvisor = (PartiallyComparableAdvisorHolder) it.next(); + result.add(pcAdvisor.getAdvisor()); + } + + return result; + } + + /** + * Adds an {@link ExposeInvocationInterceptor} to the beginning of the advice chain. + * These additional advices are needed when using AspectJ expression pointcuts + * and when using AspectJ-style advice. + */ + protected void extendAdvisors(List candidateAdvisors) { + AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors); + } + + protected boolean shouldSkip(Class beanClass, String beanName) { + // TODO: Consider optimization by caching the list of the aspect names + List candidtate = findCandidateAdvisors(); + for (Iterator it = candidtate.iterator(); it.hasNext();) { + Advisor advisor = (Advisor) it.next(); + if (advisor instanceof AspectJPointcutAdvisor) { + if(((AbstractAspectJAdvice) advisor.getAdvice()).getAspectName().equals(beanName)) { + return true; + } + } + } + return super.shouldSkip(beanClass, beanName); + } + + /** + * Implements AspectJ PartialComparable interface for defining partial orderings. + */ + private static class PartiallyComparableAdvisorHolder implements PartialComparable { + + private final Advisor advisor; + + private final Comparator comparator; + + public PartiallyComparableAdvisorHolder(Advisor advisor, Comparator comparator) { + this.advisor = advisor; + this.comparator = comparator; + } + + public int compareTo(Object obj) { + Advisor otherAdvisor = ((PartiallyComparableAdvisorHolder) obj).advisor; + return this.comparator.compare(this.advisor, otherAdvisor); + } + + public int fallbackCompareTo(Object obj) { + return 0; + } + + public Advisor getAdvisor() { + return this.advisor; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + Advice advice = this.advisor.getAdvice(); + sb.append(ClassUtils.getShortName(advice.getClass())); + sb.append(": "); + if (this.advisor instanceof Ordered) { + sb.append("order " + ((Ordered) this.advisor).getOrder() + ", "); + } + if (advice instanceof AbstractAspectJAdvice) { + AbstractAspectJAdvice ajAdvice = (AbstractAspectJAdvice) advice; + sb.append(ajAdvice.getAspectName()); + sb.append(", declaration order "); + sb.append(ajAdvice.getDeclarationOrder()); + } + return sb.toString(); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparator.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,170 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.aspectj.autoproxy; + +import java.util.Comparator; + +import org.springframework.aop.Advisor; +import org.springframework.aop.aspectj.AspectJAopUtils; +import org.springframework.aop.aspectj.AspectJPrecedenceInformation; +import org.springframework.core.OrderComparator; +import org.springframework.util.Assert; + +/** + * Orders AspectJ advice/advisors by precedence (not invocation order). + * + *

Given two pieces of advice, a and b: + *

    + *
  • if a and b are defined in different + * aspects, then the advice in the aspect with the lowest order + * value has the highest precedence
  • + *
  • if a and b are defined in the same + * aspect, then if one of a or b is a form of + * after advice, then the advice declared last in the aspect has the + * highest precedence. If neither a nor b is a + * form of after advice, then the advice declared first in the aspect has + * the highest precedence.
  • + *
+ * + *

Important: Note that unlike a normal comparator a return of 0 means + * we don't care about the ordering, not that the two elements must be sorted + * identically. Used with AspectJ PartialOrder class. + * + * @author Adrian Colyer + * @author Juergen Hoeller + * @since 2.0 + */ +class AspectJPrecedenceComparator implements Comparator { + + private static final int HIGHER_PRECEDENCE = -1; + private static final int SAME_PRECEDENCE = 0; + private static final int LOWER_PRECEDENCE = 1; + private static final int NOT_COMPARABLE = 0; + + private final Comparator advisorComparator; + + + /** + * Create a default AspectJPrecedenceComparator. + */ + public AspectJPrecedenceComparator() { + this.advisorComparator = new OrderComparator(); + } + + /** + * Create a AspectJPrecedenceComparator, using the given Comparator + * for comparing {@link org.springframework.aop.Advisor} instances. + * @param advisorComparator the Comparator to use for Advisors + */ + public AspectJPrecedenceComparator(Comparator advisorComparator) { + Assert.notNull(advisorComparator, "Advisor comparator must not be null"); + this.advisorComparator = advisorComparator; + } + + + public int compare(Object o1, Object o2) { + if (!(o1 instanceof Advisor && o2 instanceof Advisor)) { + throw new IllegalArgumentException( + "AspectJPrecedenceComparator can only compare the order of Advisors, " + + "but was passed [" + o1 + "] and [" + o2 + "]"); + } + + Advisor advisor1 = (Advisor) o1; + Advisor advisor2 = (Advisor) o2; + + boolean oneOrOtherIsAfterAdvice = + (AspectJAopUtils.isAfterAdvice(advisor1) || AspectJAopUtils.isAfterAdvice(advisor2)); + boolean oneOrOtherIsBeforeAdvice = + (AspectJAopUtils.isBeforeAdvice(advisor1) || AspectJAopUtils.isBeforeAdvice(advisor2)); + if (oneOrOtherIsAfterAdvice && oneOrOtherIsBeforeAdvice) { + return NOT_COMPARABLE; + } + else { + int advisorPrecedence = this.advisorComparator.compare(advisor1, advisor2); + if (advisorPrecedence == SAME_PRECEDENCE && declaredInSameAspect(advisor1, advisor2)) { + advisorPrecedence = comparePrecedenceWithinAspect(advisor1, advisor2); + } + return advisorPrecedence; + } + } + + private int comparePrecedenceWithinAspect(Advisor advisor1, Advisor advisor2) { + boolean oneOrOtherIsAfterAdvice = + (AspectJAopUtils.isAfterAdvice(advisor1) || AspectJAopUtils.isAfterAdvice(advisor2)); + int adviceDeclarationOrderDelta = getAspectDeclarationOrder(advisor1) - getAspectDeclarationOrder(advisor2); + + if (oneOrOtherIsAfterAdvice) { + // the advice declared last has higher precedence + if (adviceDeclarationOrderDelta < 0) { + // advice1 was declared before advice2 + // so advice1 has lower precedence + return LOWER_PRECEDENCE; + } + else if (adviceDeclarationOrderDelta == 0) { + return SAME_PRECEDENCE; + } + else { + return HIGHER_PRECEDENCE; + } + } + else { + // the advice declared first has higher precedence + if (adviceDeclarationOrderDelta < 0) { + // advice1 was declared before advice2 + // so advice1 has higher precedence + return HIGHER_PRECEDENCE; + } + else if (adviceDeclarationOrderDelta == 0) { + return SAME_PRECEDENCE; + } + else { + return LOWER_PRECEDENCE; + } + } + } + + private boolean declaredInSameAspect(Advisor advisor1, Advisor advisor2) { + if (!(hasAspectName(advisor1) && hasAspectName(advisor2))) { + return false; + } + else { + return getAspectName(advisor1).equals(getAspectName(advisor2)); + } + } + + private boolean hasAspectName(Advisor anAdvisor) { + return (anAdvisor instanceof AspectJPrecedenceInformation || + anAdvisor.getAdvice() instanceof AspectJPrecedenceInformation); + } + + // pre-condition is that hasAspectName returned true + private String getAspectName(Advisor anAdvisor) { + return AspectJAopUtils.getAspectJPrecedenceInformationFor(anAdvisor).getAspectName(); + } + + private int getAspectDeclarationOrder(Advisor anAdvisor) { + AspectJPrecedenceInformation precedenceInfo = + AspectJAopUtils.getAspectJPrecedenceInformationFor(anAdvisor); + if (precedenceInfo != null) { + return precedenceInfo.getDeclarationOrder(); + } + else { + return 0; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/aspectj/autoproxy/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/aspectj/autoproxy/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/aspectj/autoproxy/package.html 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,8 @@ + + + +Base classes enabling auto-proxying based on AspectJ. +Support for AspectJ annotation aspects resides in the "aspectj.annotation" package. + + + Index: 3rdParty_sources/spring/org/springframework/aop/config/AbstractInterceptorDrivenBeanDefinitionDecorator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/AbstractInterceptorDrivenBeanDefinitionDecorator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/AbstractInterceptorDrivenBeanDefinitionDecorator.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,120 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import java.util.List; + +import org.w3c.dom.Node; + +import org.springframework.aop.framework.ProxyFactoryBean; +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.ManagedList; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionDecorator; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +/** + * Base implementation for {@link org.springframework.beans.factory.xml.BeanDefinitionDecorator BeanDefinitionDecorators} wishing + * to add an {@link org.aopalliance.intercept.MethodInterceptor interceptor} to the resulting + * bean. + * + *

This base class controls the creation of the {@link ProxyFactoryBean} bean definition + * and wraps the original as an inner-bean definition for the target property of + * {@link ProxyFactoryBean}. + * + *

Chaining is correctly handled, ensuring that only one {@link ProxyFactoryBean} definition + * is created. If a previous {@link org.springframework.beans.factory.xml.BeanDefinitionDecorator} already created the {@link org.springframework.aop.framework.ProxyFactoryBean} + * then the interceptor is simply added to the existing definition. + * + *

Subclasses have only to create the BeanDefinition to the interceptor they + * wish to add. + * + * @author Rob Harrop + * @since 2.0 + * @see org.aopalliance.intercept.MethodInterceptor + */ +public abstract class AbstractInterceptorDrivenBeanDefinitionDecorator implements BeanDefinitionDecorator { + + public final BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definitionHolder, ParserContext parserContext) { + BeanDefinitionRegistry registry = parserContext.getRegistry(); + + // get the root bean name - will be the name of the generated proxy factory bean + String existingBeanName = definitionHolder.getBeanName(); + BeanDefinition existingDefinition = definitionHolder.getBeanDefinition(); + + // delegate to subclass for interceptor def + BeanDefinition interceptorDefinition = createInterceptorDefinition(node); + + // generate name and register the interceptor + String interceptorName = existingBeanName + "." + getInterceptorNameSuffix(interceptorDefinition); + BeanDefinitionReaderUtils.registerBeanDefinition(new BeanDefinitionHolder(interceptorDefinition, interceptorName), registry); + + BeanDefinitionHolder result = definitionHolder; + + if (!isProxyFactoryBeanDefinition(existingDefinition)) { + + // create the proxy definitionHolder + RootBeanDefinition proxyDefinition = new RootBeanDefinition(); + // create proxy factory bean definitionHolder + proxyDefinition.setBeanClass(ProxyFactoryBean.class); + + // set up property values + MutablePropertyValues mpvs = new MutablePropertyValues(); + proxyDefinition.setPropertyValues(mpvs); + + // set the target + mpvs.addPropertyValue("target", existingDefinition); + + // create the interceptor names list + ManagedList interceptorList = new ManagedList(); + mpvs.addPropertyValue("interceptorNames", interceptorList); + + result = new BeanDefinitionHolder(proxyDefinition, existingBeanName); + } + + addInterceptorNameToList(interceptorName, result.getBeanDefinition()); + + return result; + + } + + private void addInterceptorNameToList(String interceptorName, BeanDefinition beanDefinition) { + List list = (List) beanDefinition.getPropertyValues().getPropertyValue("interceptorNames").getValue(); + list.add(interceptorName); + } + + private boolean isProxyFactoryBeanDefinition(BeanDefinition existingDefinition) { + return existingDefinition.getBeanClassName().equals(ProxyFactoryBean.class.getName()); + } + + protected String getInterceptorNameSuffix(BeanDefinition interceptorDefinition) { + return StringUtils.uncapitalize(ClassUtils.getShortName(interceptorDefinition.getBeanClassName())); + } + + /** + * Subclasses should implement this method to return the BeanDefinition + * for the interceptor they wish to apply to the bean being decorated. + */ + protected abstract BeanDefinition createInterceptorDefinition(Node node); + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/AdviceEntry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/AdviceEntry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/AdviceEntry.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.springframework.beans.factory.parsing.ParseState; + +/** + * {@link ParseState} entry representing an advice element. + * + * @author Mark Fisher + * @since 2.0 + */ +public class AdviceEntry implements ParseState.Entry { + + private final String kind; + + + /** + * Creates a new instance of the {@link AdviceEntry} class. + * @param kind the kind of advice represented by this entry (before, after, around, etc.) + */ + public AdviceEntry(String kind) { + this.kind = kind; + } + + public String toString() { + return "Advice (" + this.kind + ")"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/AdvisorComponentDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/AdvisorComponentDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/AdvisorComponentDefinition.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,114 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanReference; +import org.springframework.beans.factory.parsing.AbstractComponentDefinition; +import org.springframework.util.Assert; + +/** + * {@link org.springframework.beans.factory.parsing.ComponentDefinition} + * that bridges the gap between the advisor bean definition configured + * by the <aop:advisor> tag and the component definition + * infrastructure. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public class AdvisorComponentDefinition extends AbstractComponentDefinition { + + private final String advisorBeanName; + + private final BeanDefinition advisorDefinition; + + private String description; + + private BeanReference[] beanReferences; + + private BeanDefinition[] beanDefinitions; + + + public AdvisorComponentDefinition(String advisorBeanName, BeanDefinition advisorDefinition) { + this(advisorBeanName, advisorDefinition, null); + } + + public AdvisorComponentDefinition( + String advisorBeanName, BeanDefinition advisorDefinition, BeanDefinition pointcutDefinition) { + + Assert.notNull(advisorBeanName, "'advisorBeanName' must not be null"); + Assert.notNull(advisorDefinition, "'advisorDefinition' must not be null"); + this.advisorBeanName = advisorBeanName; + this.advisorDefinition = advisorDefinition; + unwrapDefinitions(advisorDefinition, pointcutDefinition); + } + + + private void unwrapDefinitions(BeanDefinition advisorDefinition, BeanDefinition pointcutDefinition) { + MutablePropertyValues pvs = advisorDefinition.getPropertyValues(); + BeanReference adviceReference = (BeanReference) pvs.getPropertyValue("adviceBeanName").getValue(); + + if (pointcutDefinition != null) { + this.beanReferences = new BeanReference[] {adviceReference}; + this.beanDefinitions = new BeanDefinition[] {advisorDefinition, pointcutDefinition}; + this.description = buildDescription(adviceReference, pointcutDefinition); + } + else { + BeanReference pointcutReference = (BeanReference) pvs.getPropertyValue("pointcut").getValue(); + this.beanReferences = new BeanReference[] {adviceReference, pointcutReference}; + this.beanDefinitions = new BeanDefinition[] {advisorDefinition}; + this.description = buildDescription(adviceReference, pointcutReference); + } + } + + private String buildDescription(BeanReference adviceReference, BeanDefinition pointcutDefinition) { + return new StringBuffer("Advisor ").toString(); + } + + private String buildDescription(BeanReference adviceReference, BeanReference pointcutReference) { + return new StringBuffer("Advisor ").toString(); + } + + + public String getName() { + return this.advisorBeanName; + } + + public String getDescription() { + return this.description; + } + + public BeanDefinition[] getBeanDefinitions() { + return this.beanDefinitions; + } + + public BeanReference[] getBeanReferences() { + return this.beanReferences; + } + + public Object getSource() { + return this.advisorDefinition.getSource(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/AdvisorEntry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/AdvisorEntry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/AdvisorEntry.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.springframework.beans.factory.parsing.ParseState; + +/** + * {@link ParseState} entry representing an advisor. + * + * @author Mark Fisher + * @since 2.0 + */ +public class AdvisorEntry implements ParseState.Entry { + + private final String name; + + + /** + * Creates a new instance of the {@link AdvisorEntry} class. + * @param name the bean name of the advisor + */ + public AdvisorEntry(String name) { + this.name = name; + } + + public String toString() { + return "Advisor '" + this.name + "'"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/AopConfigUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/AopConfigUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/AopConfigUtils.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,159 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator; +import org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.core.JdkVersion; +import org.springframework.core.Ordered; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; + +/** + * Utility class for handling registration of AOP auto-proxy creators. + * + *

Only a single auto-proxy creator can be registered yet multiple concrete + * implementations are available. Therefore this class wraps a simple escalation + * protocol, allowing classes to request a particular auto-proxy creator and know + * that class, or a subclass thereof, will eventually be resident + * in the application context. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @author Mark Fisher + * @since 2.5 + * @see AopNamespaceUtils + */ +public abstract class AopConfigUtils { + + /** + * The bean name of the internally managed auto-proxy creator. + */ + public static final String AUTO_PROXY_CREATOR_BEAN_NAME = + "org.springframework.aop.config.internalAutoProxyCreator"; + + /** + * The class name of the AnnotationAwareAspectJAutoProxyCreator class. + * Only available with AspectJ and Java 5. + */ + private static final String ASPECTJ_ANNOTATION_AUTO_PROXY_CREATOR_CLASS_NAME = + "org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"; + + + /** + * Stores the auto proxy creator classes in escalation order. + */ + private static final List APC_PRIORITY_LIST = new ArrayList(); + + /** + * Setup the escalation list. + */ + static { + APC_PRIORITY_LIST.add(InfrastructureAdvisorAutoProxyCreator.class.getName()); + APC_PRIORITY_LIST.add(AspectJAwareAdvisorAutoProxyCreator.class.getName()); + APC_PRIORITY_LIST.add(ASPECTJ_ANNOTATION_AUTO_PROXY_CREATOR_CLASS_NAME); + } + + + public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) { + return registerAutoProxyCreatorIfNecessary(registry, null); + } + + public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, Object source) { + return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source); + } + + public static BeanDefinition registerAspectJAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) { + return registerAspectJAutoProxyCreatorIfNecessary(registry, null); + } + + public static BeanDefinition registerAspectJAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, Object source) { + return registerOrEscalateApcAsRequired(AspectJAwareAdvisorAutoProxyCreator.class, registry, source); + } + + public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) { + return registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry, null); + } + + public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, Object source) { + Class cls = getAspectJAnnotationAutoProxyCreatorClassIfPossible(); + return registerOrEscalateApcAsRequired(cls, registry, source); + } + + public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry registry) { + if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) { + BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME); + definition.getPropertyValues().addPropertyValue("proxyTargetClass", Boolean.TRUE); + } + } + + + private static BeanDefinition registerOrEscalateApcAsRequired(Class cls, BeanDefinitionRegistry registry, Object source) { + Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); + if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) { + BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME); + if (!cls.getName().equals(apcDefinition.getBeanClassName())) { + int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName()); + int requiredPriority = findPriorityForClass(cls.getName()); + if (currentPriority < requiredPriority) { + apcDefinition.setBeanClassName(cls.getName()); + } + } + return null; + } + RootBeanDefinition beanDefinition = new RootBeanDefinition(cls); + beanDefinition.setSource(source); + beanDefinition.getPropertyValues().addPropertyValue("order", new Integer(Ordered.HIGHEST_PRECEDENCE)); + beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition); + return beanDefinition; + } + + private static Class getAspectJAnnotationAutoProxyCreatorClassIfPossible() { + if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) { + throw new IllegalStateException( + "AnnotationAwareAspectJAutoProxyCreator is only available on Java 1.5 and higher"); + } + try { + return ClassUtils.forName( + ASPECTJ_ANNOTATION_AUTO_PROXY_CREATOR_CLASS_NAME, AopConfigUtils.class.getClassLoader()); + } + catch (Throwable ex) { + throw new IllegalStateException("Unable to load Java 1.5 dependent class [" + + ASPECTJ_ANNOTATION_AUTO_PROXY_CREATOR_CLASS_NAME + "]", ex); + } + } + + private static int findPriorityForClass(String className) { + Assert.notNull(className, "Class name must not be null"); + for (int i = 0; i < APC_PRIORITY_LIST.size(); i++) { + String str = (String) APC_PRIORITY_LIST.get(i); + if (className.equals(str)) { + return i; + } + } + throw new IllegalArgumentException( + "Class name [" + className + "] is not a known auto-proxy creator class"); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/AopNamespaceHandler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/AopNamespaceHandler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/AopNamespaceHandler.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.springframework.aop.aspectj.AspectJExpressionPointcut; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.NamespaceHandlerSupport; + +/** + * NamespaceHandler for the aop namespace. + * + *

Provides a {@link org.springframework.beans.factory.xml.BeanDefinitionParser} for the + * <aop:config> tag. A config tag can include nested + * pointcut, advisor and aspect tags. + * + *

The pointcut tag allows for creation of named + * {@link AspectJExpressionPointcut} beans using a simple syntax: + *

+ * <aop:pointcut id="getNameCalls" expression="execution(* *..ITestBean.getName(..))"/>
+ * 
+ * + *

Using the advisor tag you can configure an {@link org.springframework.aop.Advisor} + * and have it applied to all relevant beans in you {@link org.springframework.beans.factory.BeanFactory} + * automatically. The advisor tag supports both in-line and referenced + * {@link org.springframework.aop.Pointcut Pointcuts}: + * + *

+ * <aop:advisor id="getAgeAdvisor"
+ *     pointcut="execution(* *..ITestBean.getAge(..))"
+ *     advice-ref="getAgeCounter"/>
+ *
+ * <aop:advisor id="getNameAdvisor"
+ *     pointcut-ref="getNameCalls"
+ *     advice-ref="getNameCounter"/>
+ * + * @author Rob Harrop + * @author Adrian Colyer + * @author Juergen Hoeller + * @since 2.0 + */ +public class AopNamespaceHandler extends NamespaceHandlerSupport { + + /** + * Register the {@link BeanDefinitionParser BeanDefinitionParsers} for the + * 'config', 'spring-configured', 'aspectj-autoproxy' + * and 'scoped-proxy' tags. + */ + public void init() { + // In 2.0 XSD as well as in 2.1 XSD. + registerBeanDefinitionParser("config", new ConfigBeanDefinitionParser()); + registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser()); + registerBeanDefinitionDecorator("scoped-proxy", new ScopedProxyBeanDefinitionDecorator()); + + // Only in 2.0 XSD: moved to context namespace as of 2.1 + registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser()); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/AopNamespaceUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/AopNamespaceUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/AopNamespaceUtils.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,115 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.xml.ParserContext; + +/** + * Utility class for handling registration of auto-proxy creators used internally + * by the 'aop' namespace tags. + * + *

Only a single auto-proxy creator can be registered and multiple tags may wish + * to register different concrete implementations. As such this class delegates to + * {@link AopConfigUtils} which wraps a simple escalation protocol. Therefore classes + * may request a particular auto-proxy creator and know that class, or a subclass + * thereof, will eventually be resident in the application context. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @author Mark Fisher + * @since 2.0 + * @see AopConfigUtils + */ +public abstract class AopNamespaceUtils { + + /** + * The proxy-target-class attribute as found on AOP-related XML tags. + */ + public static final String PROXY_TARGET_CLASS_ATTRIBUTE = "proxy-target-class"; + + + public static void registerAutoProxyCreatorIfNecessary( + ParserContext parserContext, Element sourceElement) { + + BeanDefinition beanDefinition = AopConfigUtils.registerAutoProxyCreatorIfNecessary( + parserContext.getRegistry(), parserContext.extractSource(sourceElement)); + useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement); + registerComponentIfNecessary(beanDefinition, parserContext); + } + + public static void registerAspectJAutoProxyCreatorIfNecessary( + ParserContext parserContext, Element sourceElement) { + + BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAutoProxyCreatorIfNecessary( + parserContext.getRegistry(), parserContext.extractSource(sourceElement)); + useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement); + registerComponentIfNecessary(beanDefinition, parserContext); + } + + public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary( + ParserContext parserContext, Element sourceElement) { + + BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary( + parserContext.getRegistry(), parserContext.extractSource(sourceElement)); + useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement); + registerComponentIfNecessary(beanDefinition, parserContext); + } + + /** + * @deprecated since Spring 2.5, in favor of + * {@link #registerAutoProxyCreatorIfNecessary(ParserContext, Element)} and + * {@link AopConfigUtils#registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry, Object)} + */ + public static void registerAutoProxyCreatorIfNecessary(ParserContext parserContext, Object source) { + BeanDefinition beanDefinition = AopConfigUtils.registerAutoProxyCreatorIfNecessary( + parserContext.getRegistry(), source); + registerComponentIfNecessary(beanDefinition, parserContext); + } + + /** + * @deprecated since Spring 2.5, in favor of + * {@link AopConfigUtils#forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry)} + */ + public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry registry) { + AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry); + } + + + private static void useClassProxyingIfNecessary(BeanDefinitionRegistry registry, Element sourceElement) { + if (sourceElement != null) { + boolean proxyTargetClass = Boolean.valueOf( + sourceElement.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE)).booleanValue(); + if (proxyTargetClass) { + AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry); + } + } + } + + private static void registerComponentIfNecessary(BeanDefinition beanDefinition, ParserContext parserContext) { + if (beanDefinition != null) { + BeanComponentDefinition componentDefinition = + new BeanComponentDefinition(beanDefinition, AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME); + parserContext.registerComponent(componentDefinition); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/AspectComponentDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/AspectComponentDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/AspectComponentDefinition.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanReference; +import org.springframework.beans.factory.parsing.CompositeComponentDefinition; + +/** + * {@link org.springframework.beans.factory.parsing.ComponentDefinition} + * that holds an aspect definition, including its nested pointcuts. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + * @see #getNestedComponents() + * @see PointcutComponentDefinition + */ +public class AspectComponentDefinition extends CompositeComponentDefinition { + + private final BeanDefinition[] beanDefinitions; + + private final BeanReference[] beanReferences; + + + public AspectComponentDefinition( + String aspectName, BeanDefinition[] beanDefinitions, BeanReference[] beanReferences, Object source) { + + super(aspectName, source); + this.beanDefinitions = (beanDefinitions != null ? beanDefinitions : new BeanDefinition[0]); + this.beanReferences = (beanReferences != null ? beanReferences : new BeanReference[0]); + } + + + public BeanDefinition[] getBeanDefinitions() { + return this.beanDefinitions; + } + + public BeanReference[] getBeanReferences() { + return this.beanReferences; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/AspectEntry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/AspectEntry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/AspectEntry.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.springframework.beans.factory.parsing.ParseState; +import org.springframework.util.StringUtils; + +/** + * {@link ParseState} entry representing an aspect. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.0 + */ +public class AspectEntry implements ParseState.Entry { + + private final String id; + + private final String ref; + + + /** + * Create a new AspectEntry. + * @param id the id of the aspect element + * @param ref the bean name referenced by this aspect element + */ + public AspectEntry(String id, String ref) { + this.id = id; + this.ref = ref; + } + + public String toString() { + return "Aspect: " + (StringUtils.hasLength(this.id) ? "id='" + this.id + "'" : "ref='" + this.ref + "'"); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/AspectJAutoProxyBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/AspectJAutoProxyBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/AspectJAutoProxyBeanDefinitionParser.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.TypedStringValue; +import org.springframework.beans.factory.support.ManagedList; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; + +/** + * {@link BeanDefinitionParser} for the aspectj-autoproxy tag, + * enabling the automatic application of @AspectJ-style aspects found in + * the {@link org.springframework.beans.factory.BeanFactory}. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +class AspectJAutoProxyBeanDefinitionParser implements BeanDefinitionParser { + + public BeanDefinition parse(Element element, ParserContext parserContext) { + AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element); + extendBeanDefinition(element, parserContext); + return null; + } + + private void extendBeanDefinition(Element element, ParserContext parserContext) { + BeanDefinition beanDef = + parserContext.getRegistry().getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME); + if (element.hasChildNodes()) { + addIncludePatterns(element, parserContext, beanDef); + } + } + + private void addIncludePatterns(Element element, ParserContext parserContext, BeanDefinition beanDef) { + ManagedList includePatterns = new ManagedList(); + NodeList childNodes = element.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + Node node = childNodes.item(i); + if (node instanceof Element) { + Element includeElement = (Element) node; + TypedStringValue valueHolder = new TypedStringValue(includeElement.getAttribute("name")); + valueHolder.setSource(parserContext.extractSource(includeElement)); + includePatterns.add(valueHolder); + } + } + if (!includePatterns.isEmpty()) { + includePatterns.setSource(parserContext.extractSource(element)); + beanDef.getPropertyValues().addPropertyValue("includePatterns", includePatterns); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/ConfigBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/ConfigBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/ConfigBeanDefinitionParser.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,546 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import java.util.ArrayList; +import java.util.List; + +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import org.springframework.aop.aspectj.AspectJAfterAdvice; +import org.springframework.aop.aspectj.AspectJAfterReturningAdvice; +import org.springframework.aop.aspectj.AspectJAfterThrowingAdvice; +import org.springframework.aop.aspectj.AspectJAroundAdvice; +import org.springframework.aop.aspectj.AspectJExpressionPointcut; +import org.springframework.aop.aspectj.AspectJMethodBeforeAdvice; +import org.springframework.aop.aspectj.AspectJPointcutAdvisor; +import org.springframework.aop.aspectj.DeclareParentsAdvisor; +import org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanReference; +import org.springframework.beans.factory.config.ConstructorArgumentValues; +import org.springframework.beans.factory.config.RuntimeBeanNameReference; +import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.beans.factory.parsing.CompositeComponentDefinition; +import org.springframework.beans.factory.parsing.ParseState; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.util.StringUtils; +import org.springframework.util.xml.DomUtils; + +/** + * {@link BeanDefinitionParser} for the <aop:config> tag. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @author Adrian Colyer + * @author Mark Fisher + * @author Ramnivas Laddad + * @since 2.0 + */ +class ConfigBeanDefinitionParser implements BeanDefinitionParser { + + private static final String ASPECT = "aspect"; + + private static final String EXPRESSION = "expression"; + + private static final String ID = "id"; + + private static final String POINTCUT = "pointcut"; + + private static final String ADVICE_BEAN_NAME = "adviceBeanName"; + + private static final String ADVISOR = "advisor"; + + private static final String ADVICE_REF = "advice-ref"; + + private static final String POINTCUT_REF = "pointcut-ref"; + + private static final String REF = "ref"; + + private static final String BEFORE = "before"; + + private static final String DECLARE_PARENTS = "declare-parents"; + + private static final String TYPE_PATTERN = "types-matching"; + + private static final String DEFAULT_IMPL = "default-impl"; + + private static final String DELEGATE_REF = "delegate-ref"; + + private static final String IMPLEMENT_INTERFACE = "implement-interface"; + + private static final String AFTER = "after"; + + private static final String AFTER_RETURNING_ELEMENT = "after-returning"; + + private static final String AFTER_THROWING_ELEMENT = "after-throwing"; + + private static final String AROUND = "around"; + + private static final String RETURNING = "returning"; + + private static final String RETURNING_PROPERTY = "returningName"; + + private static final String THROWING = "throwing"; + + private static final String THROWING_PROPERTY = "throwingName"; + + private static final String ARG_NAMES = "arg-names"; + + private static final String ARG_NAMES_PROPERTY = "argumentNames"; + + private static final String ASPECT_NAME_PROPERTY = "aspectName"; + + private static final String DECLARATION_ORDER_PROPERTY = "declarationOrder"; + + private static final String ORDER_PROPERTY = "order"; + + private static final int METHOD_INDEX = 0; + + private static final int POINTCUT_INDEX = 1; + + private static final int ASPECT_INSTANCE_FACTORY_INDEX = 2; + + + private ParseState parseState = new ParseState(); + + + public BeanDefinition parse(Element element, ParserContext parserContext) { + CompositeComponentDefinition compositeDef = + new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element)); + parserContext.pushContainingComponent(compositeDef); + + configureAutoProxyCreator(parserContext, element); + + NodeList childNodes = element.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + Node node = childNodes.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + String localName = node.getLocalName(); + if (POINTCUT.equals(localName)) { + parsePointcut((Element) node, parserContext); + } + else if (ADVISOR.equals(localName)) { + parseAdvisor((Element) node, parserContext); + } + else if (ASPECT.equals(localName)) { + parseAspect((Element) node, parserContext); + } + } + } + + parserContext.popAndRegisterContainingComponent(); + return null; + } + + /** + * Configures the auto proxy creator needed to support the {@link BeanDefinition BeanDefinitions} + * created by the '<aop:config/>' tag. Will force class proxying if the + * 'proxy-target-class' attribute is set to 'true'. + * @see AopNamespaceUtils + */ + private void configureAutoProxyCreator(ParserContext parserContext, Element element) { + AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(parserContext, element); + } + + /** + * Parses the supplied <advisor> element and registers the resulting + * {@link org.springframework.aop.Advisor} and any resulting {@link org.springframework.aop.Pointcut} + * with the supplied {@link BeanDefinitionRegistry}. + */ + private void parseAdvisor(Element advisorElement, ParserContext parserContext) { + AbstractBeanDefinition advisorDef = createAdvisorBeanDefinition(advisorElement, parserContext); + String id = advisorElement.getAttribute(ID); + + try { + this.parseState.push(new AdvisorEntry(id)); + String advisorBeanName = id; + if (StringUtils.hasText(advisorBeanName)) { + parserContext.getRegistry().registerBeanDefinition(advisorBeanName, advisorDef); + } + else { + advisorBeanName = parserContext.getReaderContext().registerWithGeneratedName(advisorDef); + } + + Object pointcut = parsePointcutProperty(advisorElement, parserContext); + if (pointcut instanceof BeanDefinition) { + advisorDef.getPropertyValues().addPropertyValue(POINTCUT, pointcut); + parserContext.registerComponent( + new AdvisorComponentDefinition(advisorBeanName, advisorDef, (BeanDefinition) pointcut)); + } + else if (pointcut instanceof String) { + advisorDef.getPropertyValues().addPropertyValue(POINTCUT, new RuntimeBeanReference((String) pointcut)); + parserContext.registerComponent( + new AdvisorComponentDefinition(advisorBeanName, advisorDef)); + } + } + finally { + this.parseState.pop(); + } + } + + /** + * Create a {@link RootBeanDefinition} for the advisor described in the supplied. Does not + * parse any associated 'pointcut' or 'pointcut-ref' attributes. + */ + private AbstractBeanDefinition createAdvisorBeanDefinition(Element advisorElement, ParserContext parserContext) { + RootBeanDefinition advisorDefinition = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class); + advisorDefinition.setSource(parserContext.extractSource(advisorElement)); + + String adviceRef = advisorElement.getAttribute(ADVICE_REF); + if (!StringUtils.hasText(adviceRef)) { + parserContext.getReaderContext().error( + "'advice-ref' attribute contains empty value.", advisorElement, this.parseState.snapshot()); + } + else { + advisorDefinition.getPropertyValues().addPropertyValue( + ADVICE_BEAN_NAME, new RuntimeBeanNameReference(adviceRef)); + } + + if (advisorElement.hasAttribute(ORDER_PROPERTY)) { + advisorDefinition.getPropertyValues().addPropertyValue( + ORDER_PROPERTY, advisorElement.getAttribute(ORDER_PROPERTY)); + } + + return advisorDefinition; + } + + private void parseAspect(Element aspectElement, ParserContext parserContext) { + String aspectId = aspectElement.getAttribute(ID); + String aspectName = aspectElement.getAttribute(REF); + + try { + this.parseState.push(new AspectEntry(aspectId, aspectName)); + List beanDefinitions = new ArrayList(); + List beanReferences = new ArrayList(); + + List declareParents = DomUtils.getChildElementsByTagName(aspectElement, DECLARE_PARENTS); + for (int i = METHOD_INDEX; i < declareParents.size(); i++) { + Element declareParentsElement = (Element) declareParents.get(i); + beanDefinitions.add(parseDeclareParents(declareParentsElement, parserContext)); + } + + // We have to parse "advice" and all the advice kinds in one loop, to get the + // ordering semantics right. + NodeList nodeList = aspectElement.getChildNodes(); + boolean adviceFoundAlready = false; + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (isAdviceNode(node)) { + if (!adviceFoundAlready) { + adviceFoundAlready = true; + if (!StringUtils.hasText(aspectName)) { + parserContext.getReaderContext().error( + " tag needs aspect bean reference via 'ref' attribute when declaring advices.", + aspectElement, this.parseState.snapshot()); + return; + } + beanReferences.add(new RuntimeBeanReference(aspectName)); + } + AbstractBeanDefinition advisorDefinition = parseAdvice( + aspectName, i, aspectElement, (Element) node, parserContext, beanDefinitions, beanReferences); + beanDefinitions.add(advisorDefinition); + } + } + + AspectComponentDefinition aspectComponentDefinition = createAspectComponentDefinition( + aspectElement, aspectId, beanDefinitions, beanReferences, parserContext); + parserContext.pushContainingComponent(aspectComponentDefinition); + + List pointcuts = DomUtils.getChildElementsByTagName(aspectElement, POINTCUT); + for (int i = 0; i < pointcuts.size(); i++) { + Element pointcutElement = (Element) pointcuts.get(i); + parsePointcut(pointcutElement, parserContext); + } + + parserContext.popAndRegisterContainingComponent(); + } + finally { + this.parseState.pop(); + } + } + + private AspectComponentDefinition createAspectComponentDefinition( + Element aspectElement, String aspectId, List beanDefs, List beanRefs, ParserContext parserContext) { + + BeanDefinition[] beanDefArray = (BeanDefinition[]) beanDefs.toArray(new BeanDefinition[beanDefs.size()]); + BeanReference[] beanRefArray = (BeanReference[]) beanRefs.toArray(new BeanReference[beanRefs.size()]); + Object source = parserContext.extractSource(aspectElement); + return new AspectComponentDefinition(aspectId, beanDefArray, beanRefArray, source); + } + + /** + * Return true if the supplied node describes an advice type. May be one of: + * 'before', 'after', 'after-returning', + * 'after-throwing' or 'around'. + */ + private boolean isAdviceNode(Node aNode) { + if (!(aNode instanceof Element)) { + return false; + } + else { + String name = aNode.getLocalName(); + return (BEFORE.equals(name) || AFTER.equals(name) || AFTER_RETURNING_ELEMENT.equals(name) || + AFTER_THROWING_ELEMENT.equals(name) || AROUND.equals(name)); + } + } + + /** + * Parse a 'declare-parents' element and register the appropriate + * DeclareParentsAdvisor with the BeanDefinitionRegistry encapsulated in the + * supplied ParserContext. + */ + private AbstractBeanDefinition parseDeclareParents(Element declareParentsElement, ParserContext parserContext) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(DeclareParentsAdvisor.class); + builder.addConstructorArgValue(declareParentsElement.getAttribute(IMPLEMENT_INTERFACE)); + builder.addConstructorArgValue(declareParentsElement.getAttribute(TYPE_PATTERN)); + + String defaultImpl = declareParentsElement.getAttribute(DEFAULT_IMPL); + String delegateRef = declareParentsElement.getAttribute(DELEGATE_REF); + + if (StringUtils.hasText(defaultImpl) && !StringUtils.hasText(delegateRef)) { + builder.addConstructorArgValue(defaultImpl); + } + else if (StringUtils.hasText(delegateRef) && !StringUtils.hasText(defaultImpl)) { + builder.addConstructorArgReference(delegateRef); + } + else { + parserContext.getReaderContext().error( + "Exactly one of the " + DEFAULT_IMPL + " or " + DELEGATE_REF + " attributes must be specified", + declareParentsElement, this.parseState.snapshot()); + } + + AbstractBeanDefinition definition = builder.getBeanDefinition(); + definition.setSource(parserContext.extractSource(declareParentsElement)); + parserContext.getReaderContext().registerWithGeneratedName(definition); + return definition; + } + + /** + * Parses one of 'before', 'after', 'after-returning', + * 'after-throwing' or 'around' and registers the resulting + * BeanDefinition with the supplied BeanDefinitionRegistry. + * @return the generated advice RootBeanDefinition + */ + private AbstractBeanDefinition parseAdvice( + String aspectName, int order, Element aspectElement, Element adviceElement, ParserContext parserContext, + List beanDefinitions, List beanReferences) { + + try { + this.parseState.push(new AdviceEntry(adviceElement.getLocalName())); + + // create the method factory bean + RootBeanDefinition methodDefinition = new RootBeanDefinition(MethodLocatingFactoryBean.class); + methodDefinition.getPropertyValues().addPropertyValue("targetBeanName", aspectName); + methodDefinition.getPropertyValues().addPropertyValue("methodName", adviceElement.getAttribute("method")); + methodDefinition.setSynthetic(true); + + // create instance factory definition + RootBeanDefinition aspectFactoryDef = + new RootBeanDefinition(SimpleBeanFactoryAwareAspectInstanceFactory.class); + aspectFactoryDef.getPropertyValues().addPropertyValue("aspectBeanName", aspectName); + aspectFactoryDef.setSynthetic(true); + + // register the pointcut + AbstractBeanDefinition adviceDef = createAdviceDefinition( + adviceElement, parserContext, aspectName, order, methodDefinition, aspectFactoryDef, + beanDefinitions, beanReferences); + + // configure the advisor + RootBeanDefinition advisorDefinition = new RootBeanDefinition(AspectJPointcutAdvisor.class); + advisorDefinition.setSource(parserContext.extractSource(adviceElement)); + advisorDefinition.getConstructorArgumentValues().addGenericArgumentValue(adviceDef); + if (aspectElement.hasAttribute(ORDER_PROPERTY)) { + advisorDefinition.getPropertyValues().addPropertyValue( + ORDER_PROPERTY, aspectElement.getAttribute(ORDER_PROPERTY)); + } + + // register the final advisor + parserContext.getReaderContext().registerWithGeneratedName(advisorDefinition); + + return advisorDefinition; + } + finally { + this.parseState.pop(); + } + } + + /** + * Creates the RootBeanDefinition for a POJO advice bean. Also causes pointcut + * parsing to occur so that the pointcut may be associate with the advice bean. + * This same pointcut is also configured as the pointcut for the enclosing + * Advisor definition using the supplied MutablePropertyValues. + */ + private AbstractBeanDefinition createAdviceDefinition( + Element adviceElement, ParserContext parserContext, String aspectName, int order, + RootBeanDefinition methodDef, RootBeanDefinition aspectFactoryDef, List beanDefinitions, List beanReferences) { + + RootBeanDefinition adviceDefinition = new RootBeanDefinition(getAdviceClass(adviceElement)); + adviceDefinition.setSource(parserContext.extractSource(adviceElement)); + + adviceDefinition.getPropertyValues().addPropertyValue( + ASPECT_NAME_PROPERTY, aspectName); + adviceDefinition.getPropertyValues().addPropertyValue( + DECLARATION_ORDER_PROPERTY, new Integer(order)); + + if (adviceElement.hasAttribute(RETURNING)) { + adviceDefinition.getPropertyValues().addPropertyValue( + RETURNING_PROPERTY, adviceElement.getAttribute(RETURNING)); + } + if (adviceElement.hasAttribute(THROWING)) { + adviceDefinition.getPropertyValues().addPropertyValue( + THROWING_PROPERTY, adviceElement.getAttribute(THROWING)); + } + if (adviceElement.hasAttribute(ARG_NAMES)) { + adviceDefinition.getPropertyValues().addPropertyValue( + ARG_NAMES_PROPERTY, adviceElement.getAttribute(ARG_NAMES)); + } + + ConstructorArgumentValues cav = adviceDefinition.getConstructorArgumentValues(); + cav.addIndexedArgumentValue(METHOD_INDEX, methodDef); + + Object pointcut = parsePointcutProperty(adviceElement, parserContext); + if (pointcut instanceof BeanDefinition) { + cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcut); + beanDefinitions.add(pointcut); + } + else if (pointcut instanceof String) { + RuntimeBeanReference pointcutRef = new RuntimeBeanReference((String) pointcut); + cav.addIndexedArgumentValue(POINTCUT_INDEX, pointcutRef); + beanReferences.add(pointcutRef); + } + + cav.addIndexedArgumentValue(ASPECT_INSTANCE_FACTORY_INDEX, aspectFactoryDef); + + return adviceDefinition; + } + + /** + * Gets the advice implementation class corresponding to the supplied {@link Element}. + */ + private Class getAdviceClass(Element adviceElement) { + String elementName = adviceElement.getLocalName(); + if (BEFORE.equals(elementName)) { + return AspectJMethodBeforeAdvice.class; + } + else if (AFTER.equals(elementName)) { + return AspectJAfterAdvice.class; + } + else if (AFTER_RETURNING_ELEMENT.equals(elementName)) { + return AspectJAfterReturningAdvice.class; + } + else if (AFTER_THROWING_ELEMENT.equals(elementName)) { + return AspectJAfterThrowingAdvice.class; + } + else if (AROUND.equals(elementName)) { + return AspectJAroundAdvice.class; + } + else { + throw new IllegalArgumentException("Unknown advice kind [" + elementName + "]."); + } + } + + /** + * Parses the supplied <pointcut> and registers the resulting + * Pointcut with the BeanDefinitionRegistry. + */ + private AbstractBeanDefinition parsePointcut(Element pointcutElement, ParserContext parserContext) { + String id = pointcutElement.getAttribute(ID); + String expression = pointcutElement.getAttribute(EXPRESSION); + + AbstractBeanDefinition pointcutDefinition = null; + + try { + this.parseState.push(new PointcutEntry(id)); + pointcutDefinition = createPointcutDefinition(expression); + pointcutDefinition.setSource(parserContext.extractSource(pointcutElement)); + + String pointcutBeanName = id; + if (StringUtils.hasText(pointcutBeanName)) { + parserContext.getRegistry().registerBeanDefinition(pointcutBeanName, pointcutDefinition); + } + else { + pointcutBeanName = parserContext.getReaderContext().registerWithGeneratedName(pointcutDefinition); + } + + parserContext.registerComponent( + new PointcutComponentDefinition(pointcutBeanName, pointcutDefinition, expression)); + } + finally { + this.parseState.pop(); + } + + return pointcutDefinition; + } + + /** + * Parses the pointcut or pointcut-ref attributes of the supplied + * {@link Element} and add a pointcut property as appropriate. Generates a + * {@link org.springframework.beans.factory.config.BeanDefinition} for the pointcut if necessary + * and returns its bean name, otherwise returns the bean name of the referred pointcut. + */ + private Object parsePointcutProperty(Element element, ParserContext parserContext) { + if (element.hasAttribute(POINTCUT) && element.hasAttribute(POINTCUT_REF)) { + parserContext.getReaderContext().error( + "Cannot define both 'pointcut' and 'pointcut-ref' on tag.", + element, this.parseState.snapshot()); + return null; + } + else if (element.hasAttribute(POINTCUT)) { + // Create a pointcut for the anonymous pc and register it. + String expression = element.getAttribute(POINTCUT); + AbstractBeanDefinition pointcutDefinition = createPointcutDefinition(expression); + pointcutDefinition.setSource(parserContext.extractSource(element)); + return pointcutDefinition; + } + else if (element.hasAttribute(POINTCUT_REF)) { + String pointcutRef = element.getAttribute(POINTCUT_REF); + if (!StringUtils.hasText(pointcutRef)) { + parserContext.getReaderContext().error( + "'pointcut-ref' attribute contains empty value.", element, this.parseState.snapshot()); + return null; + } + return pointcutRef; + } + else { + parserContext.getReaderContext().error( + "Must define one of 'pointcut' or 'pointcut-ref' on tag.", + element, this.parseState.snapshot()); + return null; + } + } + + /** + * Creates a {@link BeanDefinition} for the {@link AspectJExpressionPointcut} class using + * the supplied pointcut expression. + */ + protected AbstractBeanDefinition createPointcutDefinition(String expression) { + RootBeanDefinition beanDefinition = new RootBeanDefinition(AspectJExpressionPointcut.class); + beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE); + beanDefinition.setSynthetic(true); + beanDefinition.getPropertyValues().addPropertyValue(EXPRESSION, expression); + return beanDefinition; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/MethodLocatingFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/MethodLocatingFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/MethodLocatingFactoryBean.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,93 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import java.lang.reflect.Method; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.util.StringUtils; + +/** + * {@link FactoryBean} implementation that locates a {@link Method} on a specified bean. + * + * @author Rob Harrop + * @since 2.0 + */ +public class MethodLocatingFactoryBean implements FactoryBean, BeanFactoryAware { + + private String targetBeanName; + + private String methodName; + + private Method method; + + + /** + * Set the name of the bean to locate the {@link Method} on. + *

This property is required. + * @param targetBeanName the name of the bean to locate the {@link Method} on + */ + public void setTargetBeanName(String targetBeanName) { + this.targetBeanName = targetBeanName; + } + + /** + * Set the name of the {@link Method} to locate. + *

This property is required. + * @param methodName the name of the {@link Method} to locate + */ + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + public void setBeanFactory(BeanFactory beanFactory) { + if (!StringUtils.hasText(this.targetBeanName)) { + throw new IllegalArgumentException("Property 'targetBeanName' is required"); + } + if (!StringUtils.hasText(this.methodName)) { + throw new IllegalArgumentException("Property 'methodName' is required"); + } + + Class beanClass = beanFactory.getType(this.targetBeanName); + if (beanClass == null) { + throw new IllegalArgumentException("Can't determine type of bean with name '" + this.targetBeanName + "'"); + } + this.method = BeanUtils.resolveSignature(this.methodName, beanClass); + + if (this.method == null) { + throw new IllegalArgumentException("Unable to locate method [" + this.methodName + + "] on bean [" + this.targetBeanName + "]"); + } + } + + + public Object getObject() throws Exception { + return this.method; + } + + public Class getObjectType() { + return Method.class; + } + + public boolean isSingleton() { + return true; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/PointcutComponentDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/PointcutComponentDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/PointcutComponentDefinition.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.parsing.AbstractComponentDefinition; +import org.springframework.util.Assert; + +/** + * {@link org.springframework.beans.factory.parsing.ComponentDefinition} + * implementation that holds a pointcut definition. + * + * @author Rob Harrop + * @since 2.0 + */ +public class PointcutComponentDefinition extends AbstractComponentDefinition { + + private final String pointcutBeanName; + + private final BeanDefinition pointcutDefinition; + + private final String description; + + + public PointcutComponentDefinition(String pointcutBeanName, BeanDefinition pointcutDefinition, String expression) { + Assert.notNull(pointcutBeanName, "Bean name must not be null"); + Assert.notNull(pointcutDefinition, "Pointcut definition must not be null"); + Assert.notNull(expression, "Expression must not be null"); + this.pointcutBeanName = pointcutBeanName; + this.pointcutDefinition = pointcutDefinition; + this.description = "Pointcut "; + } + + + public String getName() { + return this.pointcutBeanName; + } + + public String getDescription() { + return this.description; + } + + public BeanDefinition[] getBeanDefinitions() { + return new BeanDefinition[] {this.pointcutDefinition}; + } + + public Object getSource() { + return this.pointcutDefinition.getSource(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/PointcutEntry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/PointcutEntry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/PointcutEntry.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.springframework.beans.factory.parsing.ParseState; + +/** + * {@link ParseState} entry representing a pointcut. + * + * @author Mark Fisher + * @since 2.0 + */ +public class PointcutEntry implements ParseState.Entry { + + private final String name; + + /** + * Creates a new instance of the {@link PointcutEntry} class. + * @param name the bean name of the pointcut + */ + public PointcutEntry(String name) { + this.name = name; + } + + public String toString() { + return "Pointcut '" + this.name + "'"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/ScopedProxyBeanDefinitionDecorator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/ScopedProxyBeanDefinitionDecorator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/ScopedProxyBeanDefinitionDecorator.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import org.springframework.aop.scope.ScopedProxyUtils; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionDecorator; +import org.springframework.beans.factory.xml.ParserContext; + +/** + * {@link BeanDefinitionDecorator} responsible for parsing the + * <aop:scoped-proxy/> tag. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @author Mark Fisher + * @since 2.0 + */ +class ScopedProxyBeanDefinitionDecorator implements BeanDefinitionDecorator { + + private static final String PROXY_TARGET_CLASS = "proxy-target-class"; + + + public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) { + boolean proxyTargetClass = true; + if (node instanceof Element) { + Element ele = (Element) node; + if (ele.hasAttribute(PROXY_TARGET_CLASS)) { + proxyTargetClass = Boolean.valueOf(ele.getAttribute(PROXY_TARGET_CLASS)).booleanValue(); + } + } + + // Register the original bean definition as it will be referenced by the scoped proxy and is relevant for tooling (validation, navigation). + String targetBeanName = ScopedProxyUtils.getTargetBeanName(definition.getBeanName()); + parserContext.getReaderContext().fireComponentRegistered(new BeanComponentDefinition(definition.getBeanDefinition(), targetBeanName)); + + return ScopedProxyUtils.createScopedProxy(definition, parserContext.getRegistry(), proxyTargetClass); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/SimpleBeanFactoryAwareAspectInstanceFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/SimpleBeanFactoryAwareAspectInstanceFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/SimpleBeanFactoryAwareAspectInstanceFactory.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.springframework.aop.aspectj.AspectInstanceFactory; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.core.Ordered; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +/** + * Implementation of {@link AspectInstanceFactory} that locates the aspect from the + * {@link org.springframework.beans.factory.BeanFactory} using a configured bean name. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public class SimpleBeanFactoryAwareAspectInstanceFactory implements AspectInstanceFactory, BeanFactoryAware { + + private String aspectBeanName; + + private BeanFactory beanFactory; + + + /** + * Set the name of the aspect bean. This is the bean that is returned when calling + * {@link #getAspectInstance()}. + */ + public void setAspectBeanName(String aspectBeanName) { + this.aspectBeanName = aspectBeanName; + } + + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + if (!StringUtils.hasText(this.aspectBeanName)) { + throw new IllegalArgumentException("'aspectBeanName' is required"); + } + } + + + /** + * Look up the aspect bean from the {@link BeanFactory} and returns it. + * @see #setAspectBeanName + */ + public Object getAspectInstance() { + return this.beanFactory.getBean(this.aspectBeanName); + } + + public ClassLoader getAspectClassLoader() { + if (this.beanFactory instanceof ConfigurableBeanFactory) { + return ((ConfigurableBeanFactory) this.beanFactory).getBeanClassLoader(); + } + else { + return ClassUtils.getDefaultClassLoader(); + } + } + + public int getOrder() { + if (this.beanFactory.isSingleton(this.aspectBeanName) && + this.beanFactory.isTypeMatch(this.aspectBeanName, Ordered.class)) { + return ((Ordered) this.beanFactory.getBean(this.aspectBeanName)).getOrder(); + } + return Ordered.LOWEST_PRECEDENCE; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/SpringConfiguredBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/SpringConfiguredBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/SpringConfiguredBeanDefinitionParser.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; + +/** + * {@link BeanDefinitionParser} responsible for parsing the + * <aop:spring-configured/> tag. + * + *

NOTE: This is essentially a duplicate of Spring 2.5's + * {@link org.springframework.context.config.SpringConfiguredBeanDefinitionParser} + * for the <context:spring-configured/> tag, mirrored here + * for compatibility with Spring 2.0's <aop:spring-configured/> + * tag (avoiding a direct dependency on the context package). + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +class SpringConfiguredBeanDefinitionParser implements BeanDefinitionParser { + + /** + * The bean name of the internally managed bean configurer aspect. + */ + public static final String BEAN_CONFIGURER_ASPECT_BEAN_NAME = + "org.springframework.context.config.internalBeanConfigurerAspect"; + + private static final String BEAN_CONFIGURER_ASPECT_CLASS_NAME = + "org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect"; + + + public BeanDefinition parse(Element element, ParserContext parserContext) { + if (!parserContext.getRegistry().containsBeanDefinition(BEAN_CONFIGURER_ASPECT_BEAN_NAME)) { + RootBeanDefinition def = new RootBeanDefinition(); + def.setBeanClassName(BEAN_CONFIGURER_ASPECT_CLASS_NAME); + def.setFactoryMethodName("aspectOf"); + def.setSource(parserContext.extractSource(element)); + parserContext.registerBeanComponent(new BeanComponentDefinition(def, BEAN_CONFIGURER_ASPECT_BEAN_NAME)); + } + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/config/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/package.html 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,8 @@ + + + +Support package for declarative AOP configuration, +with XML schema being the primary configuration format. + + + Index: 3rdParty_sources/spring/org/springframework/aop/config/spring-aop-2.0.xsd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/spring-aop-2.0.xsd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/spring-aop-2.0.xsd 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: 3rdParty_sources/spring/org/springframework/aop/config/spring-aop-2.5.xsd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/config/spring-aop-2.5.xsd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/config/spring-aop-2.5.xsd 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,390 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: 3rdParty_sources/spring/org/springframework/aop/framework/AbstractSingletonProxyFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/AbstractSingletonProxyFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/AbstractSingletonProxyFactoryBean.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,241 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import org.springframework.aop.TargetSource; +import org.springframework.aop.framework.adapter.AdvisorAdapterRegistry; +import org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry; +import org.springframework.aop.target.SingletonTargetSource; +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.FactoryBeanNotInitializedException; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.util.ClassUtils; + +/** + * Convenient proxy factory bean superclass for proxy factory + * beans that create only singletons. + * + *

Manages pre- and post-interceptors (references, rather than + * interceptor names, as in {@link ProxyFactoryBean}) and provides + * consistent interface management. + * + * @author Juergen Hoeller + * @since 2.0 + */ +public abstract class AbstractSingletonProxyFactoryBean extends ProxyConfig + implements FactoryBean, BeanClassLoaderAware, InitializingBean { + + private Object target; + + private Class[] proxyInterfaces; + + private Object[] preInterceptors; + + private Object[] postInterceptors; + + /** Default is global AdvisorAdapterRegistry */ + private AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance(); + + private transient ClassLoader proxyClassLoader; + + private Object proxy; + + + /** + * Set the target object, that is, the bean to be wrapped with a transactional proxy. + *

The target may be any object, in which case a SingletonTargetSource will + * be created. If it is a TargetSource, no wrapper TargetSource is created: + * This enables the use of a pooling or prototype TargetSource etc. + * @see org.springframework.aop.TargetSource + * @see org.springframework.aop.target.SingletonTargetSource + * @see org.springframework.aop.target.LazyInitTargetSource + * @see org.springframework.aop.target.PrototypeTargetSource + * @see org.springframework.aop.target.CommonsPoolTargetSource + */ + public void setTarget(Object target) { + this.target = target; + } + + /** + * Specify the set of interfaces being proxied. + *

If not specified (the default), the AOP infrastructure works + * out which interfaces need proxying by analyzing the target, + * proxying all the interfaces that the target object implements. + */ + public void setProxyInterfaces(Class[] proxyInterfaces) { + this.proxyInterfaces = proxyInterfaces; + } + + /** + * Set additional interceptors (or advisors) to be applied before the + * implicit transaction interceptor, e.g. a PerformanceMonitorInterceptor. + *

You may specify any AOP Alliance MethodInterceptors or other + * Spring AOP Advices, as well as Spring AOP Advisors. + * @see org.springframework.aop.interceptor.PerformanceMonitorInterceptor + */ + public void setPreInterceptors(Object[] preInterceptors) { + this.preInterceptors = preInterceptors; + } + + /** + * Set additional interceptors (or advisors) to be applied after the + * implicit transaction interceptor. + *

You may specify any AOP Alliance MethodInterceptors or other + * Spring AOP Advices, as well as Spring AOP Advisors. + */ + public void setPostInterceptors(Object[] postInterceptors) { + this.postInterceptors = postInterceptors; + } + + /** + * Specify the AdvisorAdapterRegistry to use. + * Default is the global AdvisorAdapterRegistry. + * @see org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry + */ + public void setAdvisorAdapterRegistry(AdvisorAdapterRegistry advisorAdapterRegistry) { + this.advisorAdapterRegistry = advisorAdapterRegistry; + } + + /** + * Set the ClassLoader to generate the proxy class in. + *

Default is the bean ClassLoader, i.e. the ClassLoader used by the + * containing BeanFactory for loading all bean classes. This can be + * overridden here for specific proxies. + */ + public void setProxyClassLoader(ClassLoader classLoader) { + this.proxyClassLoader = classLoader; + } + + public void setBeanClassLoader(ClassLoader classLoader) { + if (this.proxyClassLoader == null) { + this.proxyClassLoader = classLoader; + } + } + + + public void afterPropertiesSet() { + if (this.target == null) { + throw new IllegalArgumentException("Property 'target' is required"); + } + if (this.target instanceof String) { + throw new IllegalArgumentException("'target' needs to be a bean reference, not a bean name as value"); + } + if (this.proxyClassLoader == null) { + this.proxyClassLoader = ClassUtils.getDefaultClassLoader(); + } + + ProxyFactory proxyFactory = new ProxyFactory(); + + if (this.preInterceptors != null) { + for (int i = 0; i < this.preInterceptors.length; i++) { + proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(this.preInterceptors[i])); + } + } + + // Add the main interceptor (typically an Advisor). + proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(createMainInterceptor())); + + if (this.postInterceptors != null) { + for (int i = 0; i < this.postInterceptors.length; i++) { + proxyFactory.addAdvisor(this.advisorAdapterRegistry.wrap(this.postInterceptors[i])); + } + } + + proxyFactory.copyFrom(this); + + TargetSource targetSource = createTargetSource(this.target); + proxyFactory.setTargetSource(targetSource); + + if (this.proxyInterfaces != null) { + proxyFactory.setInterfaces(this.proxyInterfaces); + } + else if (!isProxyTargetClass()) { + // Rely on AOP infrastructure to tell us what interfaces to proxy. + proxyFactory.setInterfaces( + ClassUtils.getAllInterfacesForClass(targetSource.getTargetClass(), this.proxyClassLoader)); + } + + this.proxy = getProxy(proxyFactory); + } + + /** + * Determine a TargetSource for the given target (or TargetSource). + * @param target target. If this is an implementation of TargetSource it is + * used as our TargetSource; otherwise it is wrapped in a SingletonTargetSource. + * @return a TargetSource for this object + */ + protected TargetSource createTargetSource(Object target) { + if (target instanceof TargetSource) { + return (TargetSource) target; + } + else { + return new SingletonTargetSource(target); + } + } + + /** + * Return the proxy object to expose. + *

The default implementation uses a getProxy call with + * the factory's bean class loader. Can be overridden to specify a + * custom class loader. + * @param aopProxy the prepared AopProxy instance to get the proxy from + * @return the proxy object to expose + * @see AopProxy#getProxy(ClassLoader) + */ + protected Object getProxy(AopProxy aopProxy) { + return aopProxy.getProxy(this.proxyClassLoader); + } + + + public Object getObject() { + if (this.proxy == null) { + throw new FactoryBeanNotInitializedException(); + } + return this.proxy; + } + + public Class getObjectType() { + if (this.proxy != null) { + return this.proxy.getClass(); + } + if (this.proxyInterfaces != null && this.proxyInterfaces.length == 1) { + return this.proxyInterfaces[0]; + } + if (this.target instanceof TargetSource) { + return ((TargetSource) this.target).getTargetClass(); + } + if (this.target != null) { + return this.target.getClass(); + } + return null; + } + + public final boolean isSingleton() { + return true; + } + + + /** + * Create the "main" interceptor for this proxy factory bean. + * Typically an Advisor, but can also be any type of Advice. + *

Pre-interceptors will be applied before, post-interceptors + * will be applied after this interceptor. + */ + protected abstract Object createMainInterceptor(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/Advised.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/Advised.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/Advised.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,228 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import org.aopalliance.aop.Advice; + +import org.springframework.aop.Advisor; +import org.springframework.aop.TargetClassAware; +import org.springframework.aop.TargetSource; + +/** + * Interface to be implemented by classes that hold the configuration + * of a factory of AOP proxies. This configuration includes the + * Interceptors and other advice, and Advisors, and the proxied interfaces. + * + *

Any AOP proxy obtained from Spring can be cast to this interface to + * allow manipulation of its AOP advice. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 13.03.2003 + * @see org.springframework.aop.framework.AdvisedSupport + */ +public interface Advised extends TargetClassAware { + + /** + * Return whether the Advised configuration is frozen, + * in which case no advice changes can be made. + */ + boolean isFrozen(); + + /** + * Are we proxying the full target class instead of specified interfaces? + */ + boolean isProxyTargetClass(); + + /** + * Return the interfaces proxied by the AOP proxy. Will not + * include the target class, which may also be proxied. + */ + Class[] getProxiedInterfaces(); + + /** + * Determine whether the given interface is proxied. + * @param intf the interface to check + */ + boolean isInterfaceProxied(Class intf); + + + /** + * Change the TargetSource used by this Advised object. + * Only works if the configuration isn't frozen. + * @param targetSource new TargetSource to use + */ + void setTargetSource(TargetSource targetSource); + + /** + * Return the TargetSource used by this Advised object. + */ + TargetSource getTargetSource(); + + /** + * Set whether the proxy should be exposed by the AOP framework as a + * ThreadLocal for retrieval via the AopContext class. This is useful + * if an advised object needs to call another advised method on itself. + * (If it uses this, the invocation will not be advised). + *

Default is "false", for optimal performance. + */ + void setExposeProxy(boolean exposeProxy); + + /** + * Return whether the factory should expose the proxy as a ThreadLocal. + * This can be necessary if a target object needs to invoke a method on itself + * benefitting from advice. (If it invokes a method on this no advice + * will apply.) Getting the proxy is analogous to an EJB calling getEJBObject(). + * @see AopContext + */ + boolean isExposeProxy(); + + /** + * Set whether this proxy configuration is pre-filtered so that it only + * contains applicable advisors (matching this proxy's target class). + *

Default is "false". Set this to "true" if the advisors have been + * pre-filtered already, meaning that the ClassFilter check can be skipped + * when building the actual advisor chain for proxy invocations. + * @see org.springframework.aop.ClassFilter + */ + void setPreFiltered(boolean preFiltered); + + /** + * Return whether this proxy configuration is pre-filtered so that it only + * contains applicable advisors (matching this proxy's target class). + */ + boolean isPreFiltered(); + + + /** + * Return the advisors applying to this proxy. + * @return a list of Advisors applying to this proxy (never null) + */ + Advisor[] getAdvisors(); + + /** + * Add an advisor at the end of the advisor chain. + *

The Advisor may be an {@link org.springframework.aop.IntroductionAdvisor}, + * in which new interfaces will be available when a proxy is next obtained + * from the relevant factory. + * @param advisor the advisor to add to the end of the chain + * @throws AopConfigException in case of invalid advice + */ + void addAdvisor(Advisor advisor) throws AopConfigException; + + /** + * Add an Advisor at the specified position in the chain. + * @param advisor the advisor to add at the specified position in the chain + * @param pos position in chain (0 is head). Must be valid. + * @throws AopConfigException in case of invalid advice + */ + void addAdvisor(int pos, Advisor advisor) throws AopConfigException; + + /** + * Remove the given advisor. + * @param advisor the advisor to remove + * @return true if the advisor was removed; false + * if the advisor was not found and hence could not be removed + */ + boolean removeAdvisor(Advisor advisor); + + /** + * Remove the advisor at the given index. + * @param index index of advisor to remove + * @throws AopConfigException if the index is invalid + */ + void removeAdvisor(int index) throws AopConfigException; + + /** + * Return the index (from 0) of the given advisor, + * or -1 if no such advisor applies to this proxy. + *

The return value of this method can be used to index into the advisors array. + * @param advisor the advisor to search for + * @return index from 0 of this advisor, or -1 if there's no such advisor + */ + int indexOf(Advisor advisor); + + /** + * Replace the given advisor. + *

Note: If the advisor is an {@link org.springframework.aop.IntroductionAdvisor} + * and the replacement is not or implements different interfaces, the proxy will need + * to be re-obtained or the old interfaces won't be supported and the new interface + * won't be implemented. + * @param a the advisor to replace + * @param b the advisor to replace it with + * @return whether it was replaced. If the advisor wasn't found in the + * list of advisors, this method returns false and does nothing. + * @throws AopConfigException in case of invalid advice + */ + boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException; + + + /** + * Add the given AOP Alliance advice to the tail of the advice (interceptor) chain. + *

This will be wrapped in a DefaultPointcutAdvisor with a pointcut that always + * applies, and returned from the getAdvisors() method in this wrapped form. + *

Note that the given advice will apply to all invocations on the proxy, + * even to the toString() method! Use appropriate advice implementations + * or specify appropriate pointcuts to apply to a narrower set of methods. + * @param advice advice to add to the tail of the chain + * @throws AopConfigException in case of invalid advice + * @see #addAdvice(int, Advice) + * @see org.springframework.aop.support.DefaultPointcutAdvisor + */ + void addAdvice(Advice advice) throws AopConfigException; + + /** + * Add the given AOP Alliance Advice at the specified position in the advice chain. + *

This will be wrapped in a {@link org.springframework.aop.support.DefaultPointcutAdvisor} + * with a pointcut that always applies, and returned from the {@link #getAdvisors()} + * method in this wrapped form. + *

Note: The given advice will apply to all invocations on the proxy, + * even to the toString() method! Use appropriate advice implementations + * or specify appropriate pointcuts to apply to a narrower set of methods. + * @param pos index from 0 (head) + * @param advice advice to add at the specified position in the advice chain + * @throws AopConfigException in case of invalid advice + */ + void addAdvice(int pos, Advice advice) throws AopConfigException; + + /** + * Remove the Advisor containing the given advice. + * @param advice the advice to remove + * @return true of the advice was found and removed; + * false if there was no such advice + */ + boolean removeAdvice(Advice advice); + + /** + * Return the index (from 0) of the given AOP Alliance Advice, + * or -1 if no such advice is an advice for this proxy. + *

The return value of this method can be used to index into + * the advisors array. + * @param advice AOP Alliance advice to search for + * @return index from 0 of this advice, or -1 if there's no such advice + */ + int indexOf(Advice advice); + + + /** + * As toString() will normally be delegated to the target, + * this returns the equivalent for the AOP proxy. + * @return a string description of the proxy configuration + */ + String toProxyConfigString(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/AdvisedSupport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/AdvisedSupport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/AdvisedSupport.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,590 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.aopalliance.aop.Advice; + +import org.springframework.aop.Advisor; +import org.springframework.aop.DynamicIntroductionAdvice; +import org.springframework.aop.IntroductionAdvisor; +import org.springframework.aop.IntroductionInfo; +import org.springframework.aop.TargetSource; +import org.springframework.aop.support.DefaultIntroductionAdvisor; +import org.springframework.aop.support.DefaultPointcutAdvisor; +import org.springframework.aop.target.EmptyTargetSource; +import org.springframework.aop.target.SingletonTargetSource; +import org.springframework.core.CollectionFactory; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; + +/** + * Base class for AOP proxy configuration managers. + * These are not themselves AOP proxies, but subclasses of this class are + * normally factories from which AOP proxy instances are obtained directly. + * + *

This class frees subclasses of the housekeeping of Advices + * and Advisors, but doesn't actually implement proxy creation + * methods, which are provided by subclasses. + * + *

This class is serializable; subclasses need not be. + * This class is used to hold snapshots of proxies. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see org.springframework.aop.framework.AopProxy + */ +public class AdvisedSupport extends ProxyConfig implements Advised { + + /** use serialVersionUID from Spring 2.0 for interoperability */ + private static final long serialVersionUID = 2651364800145442165L; + + + /** + * Canonical TargetSource when there's no target, and behavior is + * supplied by the advisors. + */ + public static final TargetSource EMPTY_TARGET_SOURCE = EmptyTargetSource.INSTANCE; + + + /** Package-protected to allow direct access for efficiency */ + TargetSource targetSource = EMPTY_TARGET_SOURCE; + + /** Whether the Advisors are already filtered for the specific target class */ + private boolean preFiltered = false; + + /** The AdvisorChainFactory to use */ + AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory(); + + /** Cache with Method as key and advisor chain List as value */ + private transient Map methodCache; + + /** + * Interfaces to be implemented by the proxy. Held in List to keep the order + * of registration, to create JDK proxy with specified order of interfaces. + */ + private List interfaces = new ArrayList(); + + /** + * List of Advisors. If an Advice is added, it will be wrapped + * in an Advisor before being added to this List. + */ + private List advisors = new LinkedList(); + + /** + * Array updated on changes to the advisors list, which is easier + * to manipulate internally. + */ + private Advisor[] advisorArray = new Advisor[0]; + + + /** + * No-arg constructor for use as a JavaBean. + */ + public AdvisedSupport() { + initMethodCache(); + } + + /** + * Create a AdvisedSupport instance with the given parameters. + * @param interfaces the proxied interfaces + */ + public AdvisedSupport(Class[] interfaces) { + this(); + setInterfaces(interfaces); + } + + /** + * Initialize the method cache. + */ + private void initMethodCache() { + this.methodCache = CollectionFactory.createConcurrentMapIfPossible(32); + } + + + /** + * Set the given object as target. + * Will create a SingletonTargetSource for the object. + * @see #setTargetSource + * @see org.springframework.aop.target.SingletonTargetSource + */ + public void setTarget(Object target) { + setTargetSource(new SingletonTargetSource(target)); + } + + public void setTargetSource(TargetSource targetSource) { + this.targetSource = (targetSource != null ? targetSource : EMPTY_TARGET_SOURCE); + } + + public TargetSource getTargetSource() { + return this.targetSource; + } + + /** + * Set a target class to be proxied, indicating that the proxy + * should be castable to the given class. + *

Internally, an {@link org.springframework.aop.target.EmptyTargetSource} + * for the given target class will be used. The kind of proxy needed + * will be determined on actual creation of the proxy. + *

This is a replacement for setting a "targetSource" or "target", + * for the case where we want a proxy based on a target class + * (which can be an interface or a concrete class) without having + * a fully capable TargetSource available. + * @see #setTargetSource + * @see #setTarget + */ + public void setTargetClass(Class targetClass) { + this.targetSource = EmptyTargetSource.forClass(targetClass); + } + + public Class getTargetClass() { + return this.targetSource.getTargetClass(); + } + + public void setPreFiltered(boolean preFiltered) { + this.preFiltered = preFiltered; + } + + public boolean isPreFiltered() { + return this.preFiltered; + } + + /** + * Set the advisor chain factory to use. + *

Default is a {@link DefaultAdvisorChainFactory}. + */ + public void setAdvisorChainFactory(AdvisorChainFactory advisorChainFactory) { + Assert.notNull(advisorChainFactory, "AdvisorChainFactory must not be null"); + this.advisorChainFactory = advisorChainFactory; + } + + /** + * Return the advisor chain factory to use (never null). + */ + public AdvisorChainFactory getAdvisorChainFactory() { + return this.advisorChainFactory; + } + + + /** + * Set the interfaces to be proxied. + */ + public void setInterfaces(Class[] interfaces) { + Assert.notNull(interfaces, "Interfaces must not be null"); + this.interfaces.clear(); + for (int i = 0; i < interfaces.length; i++) { + addInterface(interfaces[i]); + } + } + + /** + * Add a new proxied interface. + * @param intf the additional interface to proxy + */ + public void addInterface(Class intf) { + Assert.notNull(intf, "Interface must not be null"); + if (!intf.isInterface()) { + throw new IllegalArgumentException("[" + intf.getName() + "] is not an interface"); + } + if (!this.interfaces.contains(intf)) { + this.interfaces.add(intf); + adviceChanged(); + } + } + + /** + * Remove a proxied interface. + *

Does nothing if the given interface isn't proxied. + * @param intf the interface to remove from the proxy + * @return true if the interface was removed; false + * if the interface was not found and hence could not be removed + */ + public boolean removeInterface(Class intf) { + return this.interfaces.remove(intf); + } + + public Class[] getProxiedInterfaces() { + return (Class[]) this.interfaces.toArray(new Class[this.interfaces.size()]); + } + + public boolean isInterfaceProxied(Class intf) { + for (Iterator it = this.interfaces.iterator(); it.hasNext();) { + Class proxyIntf = (Class) it.next(); + if (intf.isAssignableFrom(proxyIntf)) { + return true; + } + } + return false; + } + + + public final Advisor[] getAdvisors() { + return this.advisorArray; + } + + public void addAdvisor(Advisor advisor) { + int pos = this.advisors.size(); + addAdvisor(pos, advisor); + } + + public void addAdvisor(int pos, Advisor advisor) throws AopConfigException { + if (advisor instanceof IntroductionAdvisor) { + validateIntroductionAdvisor((IntroductionAdvisor) advisor); + } + addAdvisorInternal(pos, advisor); + } + + public boolean removeAdvisor(Advisor advisor) { + int index = indexOf(advisor); + if (index == -1) { + return false; + } + else { + removeAdvisor(index); + return true; + } + } + + public void removeAdvisor(int index) throws AopConfigException { + if (isFrozen()) { + throw new AopConfigException("Cannot remove Advisor: Configuration is frozen."); + } + if (index < 0 || index > this.advisors.size() - 1) { + throw new AopConfigException("Advisor index " + index + " is out of bounds: " + + "This configuration only has " + this.advisors.size() + " advisors."); + } + + Advisor advisor = (Advisor) this.advisors.get(index); + if (advisor instanceof IntroductionAdvisor) { + IntroductionAdvisor ia = (IntroductionAdvisor) advisor; + // We need to remove introduction interfaces. + for (int j = 0; j < ia.getInterfaces().length; j++) { + removeInterface(ia.getInterfaces()[j]); + } + } + + this.advisors.remove(index); + updateAdvisorArray(); + adviceChanged(); + } + + public int indexOf(Advisor advisor) { + Assert.notNull(advisor, "Advisor must not be null"); + return this.advisors.indexOf(advisor); + } + + public boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException { + Assert.notNull(a, "Advisor a must not be null"); + Assert.notNull(b, "Advisor b must not be null"); + int index = indexOf(a); + if (index == -1) { + return false; + } + removeAdvisor(index); + addAdvisor(index, b); + return true; + } + + /** + * Add all of the given advisors to this proxy configuration. + * @param advisors the advisors to register + */ + public void addAllAdvisors(Advisor[] advisors) { + if (isFrozen()) { + throw new AopConfigException("Cannot add advisor: Configuration is frozen."); + } + if (!ObjectUtils.isEmpty(advisors)) { + for (int i = 0; i < advisors.length; i++) { + Advisor advisor = advisors[i]; + if (advisor instanceof IntroductionAdvisor) { + validateIntroductionAdvisor((IntroductionAdvisor) advisor); + } + Assert.notNull(advisor, "Advisor must not be null"); + this.advisors.add(advisor); + } + updateAdvisorArray(); + adviceChanged(); + } + } + + private void validateIntroductionAdvisor(IntroductionAdvisor advisor) { + advisor.validateInterfaces(); + // If the advisor passed validation, we can make the change. + Class[] ifcs = advisor.getInterfaces(); + for (int i = 0; i < ifcs.length; i++) { + addInterface(ifcs[i]); + } + } + + private void addAdvisorInternal(int pos, Advisor advisor) throws AopConfigException { + Assert.notNull(advisor, "Advisor must not be null"); + if (isFrozen()) { + throw new AopConfigException("Cannot add advisor: Configuration is frozen."); + } + if (pos > this.advisors.size()) { + throw new IllegalArgumentException( + "Illegal position " + pos + " in advisor list with size " + this.advisors.size()); + } + this.advisors.add(pos, advisor); + updateAdvisorArray(); + adviceChanged(); + } + + /** + * Bring the array up to date with the list. + */ + protected final void updateAdvisorArray() { + this.advisorArray = (Advisor[]) this.advisors.toArray(new Advisor[this.advisors.size()]); + } + + /** + * Allows uncontrolled access to the {@link List} of {@link Advisor Advisors}. + *

Use with care, and remember to {@link #updateAdvisorArray() refresh the advisor array} + * and {@link #adviceChanged() fire advice changed events} when making any modifications. + */ + protected final List getAdvisorsInternal() { + return this.advisors; + } + + + public void addAdvice(Advice advice) throws AopConfigException { + int pos = this.advisors.size(); + addAdvice(pos, advice); + } + + /** + * Cannot add introductions this way unless the advice implements IntroductionInfo. + */ + public void addAdvice(int pos, Advice advice) throws AopConfigException { + Assert.notNull(advice, "Advice must not be null"); + if (advice instanceof IntroductionInfo) { + // We don't need an IntroductionAdvisor for this kind of introduction: + // It's fully self-describing. + addAdvisor(pos, new DefaultIntroductionAdvisor(advice, (IntroductionInfo) advice)); + } + else if (advice instanceof DynamicIntroductionAdvice) { + // We need an IntroductionAdvisor for this kind of introduction. + throw new AopConfigException("DynamicIntroductionAdvice may only be added as part of IntroductionAdvisor"); + } + else { + addAdvisor(pos, new DefaultPointcutAdvisor(advice)); + } + } + + public boolean removeAdvice(Advice advice) throws AopConfigException { + int index = indexOf(advice); + if (index == -1) { + return false; + } + else { + removeAdvisor(index); + return true; + } + } + + public int indexOf(Advice advice) { + Assert.notNull(advice, "Advice must not be null"); + for (int i = 0; i < this.advisors.size(); i++) { + Advisor advisor = (Advisor) this.advisors.get(i); + if (advisor.getAdvice() == advice) { + return i; + } + } + return -1; + } + + /** + * Is the given advice included in any advisor within this proxy configuration? + * @param advice the advice to check inclusion of + * @return whether this advice instance is included + */ + public boolean adviceIncluded(Advice advice) { + Assert.notNull(advice, "Advice must not be null"); + for (int i = 0; i < this.advisors.size(); i++) { + Advisor advisor = (Advisor) this.advisors.get(i); + if (advisor.getAdvice() == advice) { + return true; + } + } + return false; + } + + /** + * Count advices of the given class. + * @param adviceClass the advice class to check + * @return the count of the interceptors of this class or subclasses + */ + public int countAdvicesOfType(Class adviceClass) { + Assert.notNull(adviceClass, "Advice class must not be null"); + int count = 0; + for (int i = 0; i < this.advisors.size(); i++) { + Advisor advisor = (Advisor) this.advisors.get(i); + if (advisor.getAdvice() != null && + adviceClass.isAssignableFrom(advisor.getAdvice().getClass())) { + count++; + } + } + return count; + } + + + /** + * Determine a list of {@link org.aopalliance.intercept.MethodInterceptor} objects + * for the given method, based on this configuration. + * @param method the proxied method + * @param targetClass the target class + * @return List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers) + */ + public List getInterceptorsAndDynamicInterceptionAdvice(Method method, Class targetClass) { + MethodCacheKey cacheKey = new MethodCacheKey(method); + List cached = (List) this.methodCache.get(cacheKey); + if (cached == null) { + cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice( + this, method, targetClass); + this.methodCache.put(cacheKey, cached); + } + return cached; + } + + /** + * Invoked when advice has changed. + */ + protected void adviceChanged() { + synchronized (this.methodCache) { + this.methodCache.clear(); + } + } + + /** + * Call this method on a new instance created by the no-arg constructor + * to create an independent copy of the configuration from the given object. + * @param other the AdvisedSupport object to copy configuration from + */ + protected void copyConfigurationFrom(AdvisedSupport other) { + copyConfigurationFrom(other, other.targetSource, new ArrayList(other.advisors)); + } + + /** + * Copy the AOP configuration from the given AdvisedSupport object, + * but allow substitution of a fresh TargetSource and a given interceptor chain. + * @param other the AdvisedSupport object to take proxy configuration from + * @param targetSource the new TargetSource + * @param advisors the Advisors for the chain + */ + protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSource, List advisors) { + copyFrom(other); + this.targetSource = targetSource; + this.advisorChainFactory = other.advisorChainFactory; + this.interfaces = new ArrayList(other.interfaces); + for (Iterator it = advisors.iterator(); it.hasNext();) { + Advisor advisor = (Advisor) it.next(); + if (advisor instanceof IntroductionAdvisor) { + validateIntroductionAdvisor((IntroductionAdvisor) advisor); + } + Assert.notNull(advisor, "Advisor must not be null"); + this.advisors.add(advisor); + } + updateAdvisorArray(); + adviceChanged(); + } + + /** + * Build a configuration-only copy of this AdvisedSupport, + * replacing the TargetSource + */ + AdvisedSupport getConfigurationOnlyCopy() { + AdvisedSupport copy = new AdvisedSupport(); + copy.copyFrom(this); + copy.targetSource = EmptyTargetSource.forClass(getTargetClass(), getTargetSource().isStatic()); + copy.advisorChainFactory = this.advisorChainFactory; + copy.interfaces = this.interfaces; + copy.advisors = this.advisors; + copy.updateAdvisorArray(); + return copy; + } + + + //--------------------------------------------------------------------- + // Serialization support + //--------------------------------------------------------------------- + + private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { + // Rely on default serialization; just initialize state after deserialization. + ois.defaultReadObject(); + + // Initialize transient fields. + initMethodCache(); + } + + + public String toProxyConfigString() { + return toString(); + } + + /** + * For debugging/diagnostic use. + */ + public String toString() { + StringBuffer sb = new StringBuffer(getClass().getName() + ": "); + sb.append(this.interfaces.size()).append(" interfaces "); + sb.append(ClassUtils.classNamesToString(this.interfaces)).append("; "); + sb.append(this.advisors.size()).append(" advisors "); + sb.append(this.advisors).append("; "); + sb.append("targetSource [").append(this.targetSource).append("]; "); + sb.append(super.toString()); + return sb.toString(); + } + + + /** + * Simple wrapper class around a Method. Used as the key when + * caching methods, for efficient equals and hashCode comparisons. + */ + private static class MethodCacheKey { + + private final Method method; + + private final int hashCode; + + public MethodCacheKey(Method method) { + this.method = method; + this.hashCode = method.hashCode(); + } + + public boolean equals(Object other) { + if (other == this) { + return true; + } + MethodCacheKey otherKey = (MethodCacheKey) other; + return (this.method == otherKey.method); + } + + public int hashCode() { + return this.hashCode; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/AdvisedSupportListener.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/AdvisedSupportListener.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/AdvisedSupportListener.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +/** + * Listener to be registered on {@link ProxyCreatorSupport} objects + * Allows for receiving callbacks on activation and change of advice. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see ProxyCreatorSupport#addListener + */ +public interface AdvisedSupportListener { + + /** + * Invoked when the first proxy is created. + * @param advised the AdvisedSupport object + */ + void activated(AdvisedSupport advised); + + /** + * Invoked when advice is changed after a proxy is created. + * @param advised the AdvisedSupport object + */ + void adviceChanged(AdvisedSupport advised); + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/AdvisorChainFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/AdvisorChainFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/AdvisorChainFactory.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import java.lang.reflect.Method; +import java.util.List; + +/** + * Factory interface for advisor chains. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public interface AdvisorChainFactory { + + /** + * Determine a list of {@link org.aopalliance.intercept.MethodInterceptor} objects + * for the given advisor chain configuration. + * @param config the AOP configuration in the form of an Advised object + * @param method the proxied method + * @param targetClass the target class + * @return List of MethodInterceptors (may also include InterceptorAndDynamicMethodMatchers) + */ + List getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class targetClass); + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/AopConfigException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/AopConfigException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/AopConfigException.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import org.springframework.core.NestedRuntimeException; + +/** + * Exception that gets thrown on illegal AOP configuration arguments. + * + * @author Rod Johnson + * @since 13.03.2003 + */ +public class AopConfigException extends NestedRuntimeException { + + /** + * Constructor for AopConfigException. + * @param msg the detail message + */ + public AopConfigException(String msg) { + super(msg); + } + + /** + * Constructor for AopConfigException. + * @param msg the detail message + * @param cause the root cause + */ + public AopConfigException(String msg, Throwable cause) { + super(msg, cause); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/AopContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/AopContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/AopContext.java 17 Aug 2012 15:11:24 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import org.springframework.core.NamedThreadLocal; + +/** + * Class containing static methods used to obtain information about the current AOP invocation. + * + *

The currentProxy() method is usable if the AOP framework is configured to + * expose the current proxy (not the default). It returns the AOP proxy in use. Target objects + * or advice can use this to make advised calls, in the same way as getEJBObject() + * can be used in EJBs. They can also use it to find advice configuration. + * + *

Spring's AOP framework does not expose proxies by default, as there is a performance cost + * in doing so. + * + *

The functionality in this class might be used by a target object that needed access + * to resources on the invocation. However, this approach should not be used when there is + * a reasonable alternative, as it makes application code dependent on usage under AOP and + * the Spring AOP framework in particular. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 13.03.2003 + */ +public abstract class AopContext { + + /** + * ThreadLocal holder for AOP proxy associated with this thread. + * Will contain null unless the "exposeProxy" property on + * the controlling proxy configuration has been set to "true". + * @see ProxyConfig#setExposeProxy + */ + private static final ThreadLocal currentProxy = new NamedThreadLocal("Current AOP proxy"); + + + /** + * Try to return the current AOP proxy. This method is usable only if the + * calling method has been invoked via AOP, and the AOP framework has been set + * to expose proxies. Otherwise, this method will throw an IllegalStateException. + * @return Object the current AOP proxy (never returns null) + * @throws IllegalStateException if the proxy cannot be found, because the + * method was invoked outside an AOP invocation context, or because the + * AOP framework has not been configured to expose the proxy + */ + public static Object currentProxy() throws IllegalStateException { + Object proxy = currentProxy.get(); + if (proxy == null) { + throw new IllegalStateException( + "Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available."); + } + return proxy; + } + + /** + * Make the given proxy available via the currentProxy() method. + *

Note that the caller should be careful to keep the old value as appropriate. + * @param proxy the proxy to expose (or null to reset it) + * @return the old proxy, which may be null if none was bound + * @see #currentProxy() + */ + static Object setCurrentProxy(Object proxy) { + Object old = currentProxy.get(); + currentProxy.set(proxy); + return old; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/AopInfrastructureBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/AopInfrastructureBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/AopInfrastructureBean.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +/** + * Marker interface that indicates a bean that is part of Spring's + * AOP infrastructure. In particular, this implies that any such bean + * is not subject to auto-proxying, even if a pointcut would match. + * + * @author Juergen Hoeller + * @since 2.0.3 + * @see org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator + * @see org.springframework.aop.scope.ScopedProxyFactoryBean + */ +public interface AopInfrastructureBean { + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/AopProxy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/AopProxy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/AopProxy.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +/** + * Delegate interface for a configured AOP proxy, allowing for the creation + * of actual proxy objects. + * + *

Out-of-the-box implementations are available for JDK dynamic proxies + * and for CGLIB proxies, as applied by {@link DefaultAopProxyFactory}. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see DefaultAopProxyFactory + */ +public interface AopProxy { + + /** + * Create a new proxy object. + *

Uses the AopProxy's default class loader (if necessary for proxy creation): + * usually, the thread context class loader. + * @return the new proxy object (never null) + * @see java.lang.Thread#getContextClassLoader() + */ + Object getProxy(); + + /** + * Create a new proxy object. + *

Uses the given class loader (if necessary for proxy creation). + * null will simply be passed down and thus lead to the low-level + * proxy facility's default, which is usually different from the default chosen + * by the AopProxy implementation's {@link #getProxy()} method. + * @param classLoader the class loader to create the proxy with + * (or null for the low-level proxy facility's default) + * @return the new proxy object (never null) + */ + Object getProxy(ClassLoader classLoader); + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/AopProxyFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/AopProxyFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/AopProxyFactory.java 17 Aug 2012 15:11:24 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +/** + * Interface to be implemented by factories that are able to create + * AOP proxies based on {@link AdvisedSupport} configuration objects. + * + *

Proxies should observe the following contract: + *

    + *
  • They should implement all interfaces that the configuration + * indicates should be proxied. + *
  • They should implement the {@link Advised} interface. + *
  • They should implement the equals method to compare proxied + * interfaces, advice, and target. + *
  • They should be serializable if all advisors and target + * are serializable. + *
  • They should be thread-safe if advisors and target + * are thread-safe. + *
+ * + *

Proxies may or may not allow advice changes to be made. + * If they do not permit advice changes (for example, because + * the configuration was frozen) a proxy should throw an + * {@link AopConfigException} on an attempted advice change. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public interface AopProxyFactory { + + /** + * Create an {@link AopProxy} for the given AOP configuration. + * @param config the AOP configuration in the form of an + * AdvisedSupport object + * @return the corresponding AOP proxy + * @throws AopConfigException if the configuration is invalid + */ + AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException; + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/AopProxyUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/AopProxyUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/AopProxyUtils.java 17 Aug 2012 15:11:24 -0000 1.1 @@ -0,0 +1,143 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import java.util.Arrays; + +import org.springframework.aop.SpringProxy; +import org.springframework.aop.support.AopUtils; +import org.springframework.util.Assert; + +/** + * Utility methods for AOP proxy factories. + * Mainly for internal use within the AOP framework. + * + *

See {@link org.springframework.aop.support.AopUtils} for a collection of + * generic AOP utility methods which do not depend on AOP framework internals. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see org.springframework.aop.support.AopUtils + */ +public abstract class AopProxyUtils { + + /** + * Determine the target class of the given bean instance, + * which might be an AOP proxy. + *

Returns the target class for an AOP proxy and the plain class else. + * @param candidate the instance to check (might be an AOP proxy) + * @return the target class (or the plain class of the given object as fallback) + * @deprecated as of Spring 2.0.3, in favor of AopUtils.getTargetClass + * @see org.springframework.aop.support.AopUtils#getTargetClass(Object) + */ + public static Class getTargetClass(Object candidate) { + Assert.notNull(candidate, "Candidate object must not be null"); + if (AopUtils.isCglibProxy(candidate)) { + return candidate.getClass().getSuperclass(); + } + if (candidate instanceof Advised) { + return ((Advised) candidate).getTargetSource().getTargetClass(); + } + return candidate.getClass(); + } + + /** + * Determine the complete set of interfaces to proxy for the given AOP configuration. + *

This will always add the {@link Advised} interface unless the AdvisedSupport's + * {@link AdvisedSupport#setOpaque "opaque"} flag is on. Always adds the + * {@link org.springframework.aop.SpringProxy} marker interface. + * @return the complete set of interfaces to proxy + * @see Advised + * @see org.springframework.aop.SpringProxy + */ + public static Class[] completeProxiedInterfaces(AdvisedSupport advised) { + Class[] specifiedInterfaces = advised.getProxiedInterfaces(); + if (specifiedInterfaces.length == 0) { + // No user-specified interfaces: check whether target class is an interface. + Class targetClass = advised.getTargetClass(); + if (targetClass != null && targetClass.isInterface()) { + specifiedInterfaces = new Class[] {targetClass}; + } + } + boolean addSpringProxy = !advised.isInterfaceProxied(SpringProxy.class); + boolean addAdvised = !advised.isOpaque() && !advised.isInterfaceProxied(Advised.class); + int nonUserIfcCount = 0; + if (addSpringProxy) { + nonUserIfcCount++; + } + if (addAdvised) { + nonUserIfcCount++; + } + Class[] proxiedInterfaces = new Class[specifiedInterfaces.length + nonUserIfcCount]; + System.arraycopy(specifiedInterfaces, 0, proxiedInterfaces, 0, specifiedInterfaces.length); + if (addSpringProxy) { + proxiedInterfaces[specifiedInterfaces.length] = SpringProxy.class; + } + if (addAdvised) { + proxiedInterfaces[proxiedInterfaces.length - 1] = Advised.class; + } + return proxiedInterfaces; + } + + /** + * Extract the user-specified interfaces that the given proxy implements, + * i.e. all non-Advised interfaces that the proxy implements. + * @param proxy the proxy to analyze (usually a JDK dynamic proxy) + * @return all user-specified interfaces that the proxy implements, + * in the original order (never null or empty) + * @see Advised + */ + public static Class[] proxiedUserInterfaces(Object proxy) { + Class[] proxyInterfaces = proxy.getClass().getInterfaces(); + int nonUserIfcCount = 0; + if (proxy instanceof SpringProxy) { + nonUserIfcCount++; + } + if (proxy instanceof Advised) { + nonUserIfcCount++; + } + Class[] userInterfaces = new Class[proxyInterfaces.length - nonUserIfcCount]; + System.arraycopy(proxyInterfaces, 0, userInterfaces, 0, userInterfaces.length); + Assert.notEmpty(userInterfaces, "JDK proxy must implement one or more interfaces"); + return userInterfaces; + } + + /** + * Check equality of the proxies behind the given AdvisedSupport objects. + * Not the same as equality of the AdvisedSupport objects: + * rather, equality of interfaces, advisors and target sources. + */ + public static boolean equalsInProxy(AdvisedSupport a, AdvisedSupport b) { + return (a == b || + (equalsProxiedInterfaces(a, b) && equalsAdvisors(a, b) && a.getTargetSource().equals(b.getTargetSource()))); + } + + /** + * Check equality of the proxied interfaces behind the given AdvisedSupport objects. + */ + public static boolean equalsProxiedInterfaces(AdvisedSupport a, AdvisedSupport b) { + return Arrays.equals(a.getProxiedInterfaces(), b.getProxiedInterfaces()); + } + + /** + * Check equality of the advisors behind the given AdvisedSupport objects. + */ + public static boolean equalsAdvisors(AdvisedSupport a, AdvisedSupport b) { + return Arrays.equals(a.getAdvisors(), b.getAdvisors()); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/Cglib2AopProxy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/Cglib2AopProxy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/Cglib2AopProxy.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,935 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.UndeclaredThrowableException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; + +import net.sf.cglib.core.CodeGenerationException; +import net.sf.cglib.proxy.Callback; +import net.sf.cglib.proxy.CallbackFilter; +import net.sf.cglib.proxy.Dispatcher; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.Factory; +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.MethodProxy; +import net.sf.cglib.proxy.NoOp; +import net.sf.cglib.transform.impl.UndeclaredThrowableStrategy; +import org.aopalliance.aop.Advice; +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.aop.Advisor; +import org.springframework.aop.PointcutAdvisor; +import org.springframework.aop.RawTargetAccess; +import org.springframework.aop.TargetSource; +import org.springframework.aop.support.AopUtils; +import org.springframework.core.SmartClassLoader; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + +/** + * CGLIB2-based {@link AopProxy} implementation for the Spring AOP framework. + * + *

Requires CGLIB 2.1+ on the classpath.. + * As of Spring 2.0, earlier CGLIB versions are not supported anymore. + * + *

Objects of this type should be obtained through proxy factories, + * configured by an {@link AdvisedSupport} object. This class is internal + * to Spring's AOP framework and need not be used directly by client code. + * + *

{@link DefaultAopProxyFactory} will automatically create CGLIB2-based + * proxies if necessary, for example in case of proxying a target class + * (see the {@link DefaultAopProxyFactory attendant javadoc} for details). + * + *

Proxies created using this class are thread-safe if the underlying + * (target) class is thread-safe. + * + * @author Rod Johnson + * @author Rob Harrop + * @author Juergen Hoeller + * @author Ramnivas Laddad + * @see net.sf.cglib.proxy.Enhancer + * @see AdvisedSupport#setProxyTargetClass + * @see DefaultAopProxyFactory + */ +final class Cglib2AopProxy implements AopProxy, Serializable { + + // Constants for CGLIB callback array indices + private static final int AOP_PROXY = 0; + private static final int INVOKE_TARGET = 1; + private static final int NO_OVERRIDE = 2; + private static final int DISPATCH_TARGET = 3; + private static final int DISPATCH_ADVISED = 4; + private static final int INVOKE_EQUALS = 5; + private static final int INVOKE_HASHCODE = 6; + + + /** Logger available to subclasses; static to optimize serialization */ + protected final static Log logger = LogFactory.getLog(Cglib2AopProxy.class); + + /** Keeps track of the Classes that we have validated for final methods */ + private static final Map validatedClasses = new WeakHashMap(); + + + /** The configuration used to configure this proxy */ + protected final AdvisedSupport advised; + + private Object[] constructorArgs; + + private Class[] constructorArgTypes; + + /** Dispatcher used for methods on Advised */ + private final transient AdvisedDispatcher advisedDispatcher; + + private transient Map fixedInterceptorMap; + + private transient int fixedInterceptorOffset; + + + /** + * Create a new Cglib2AopProxy for the given AOP configuration. + * @param config the AOP configuration as AdvisedSupport object + * @throws AopConfigException if the config is invalid. We try to throw an informative + * exception in this case, rather than let a mysterious failure happen later. + */ + public Cglib2AopProxy(AdvisedSupport config) throws AopConfigException { + Assert.notNull(config, "AdvisedSupport must not be null"); + if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) { + throw new AopConfigException("No advisors and no TargetSource specified"); + } + this.advised = config; + this.advisedDispatcher = new AdvisedDispatcher(this.advised); + } + + /** + * Set constructor arguments to use for creating the proxy. + * @param constructorArgs the constructor argument values + * @param constructorArgTypes the constructor argument types + */ + public void setConstructorArguments(Object[] constructorArgs, Class[] constructorArgTypes) { + if (constructorArgs == null || constructorArgTypes == null) { + throw new IllegalArgumentException("Both 'constructorArgs' and 'constructorArgTypes' need to be specified"); + } + if (constructorArgs.length != constructorArgTypes.length) { + throw new IllegalArgumentException("Number of 'constructorArgs' (" + constructorArgs.length + + ") must match number of 'constructorArgTypes' (" + constructorArgTypes.length + ")"); + } + this.constructorArgs = constructorArgs; + this.constructorArgTypes = constructorArgTypes; + } + + + public Object getProxy() { + return getProxy(null); + } + + public Object getProxy(ClassLoader classLoader) { + if (logger.isDebugEnabled()) { + logger.debug("Creating CGLIB2 proxy: target source is " + this.advised.getTargetSource()); + } + + try { + Class rootClass = this.advised.getTargetClass(); + Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy"); + + Class proxySuperClass = rootClass; + if (AopUtils.isCglibProxyClass(rootClass)) { + proxySuperClass = rootClass.getSuperclass(); + Class[] additionalInterfaces = rootClass.getInterfaces(); + for (int i = 0; i < additionalInterfaces.length; i++) { + Class additionalInterface = additionalInterfaces[i]; + this.advised.addInterface(additionalInterface); + } + } + + // Validate the class, writing log messages as necessary. + validateClassIfNecessary(proxySuperClass); + + // Configure CGLIB Enhancer... + Enhancer enhancer = createEnhancer(); + if (classLoader != null) { + enhancer.setClassLoader(classLoader); + if (classLoader instanceof SmartClassLoader && + ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) { + enhancer.setUseCache(false); + } + } + enhancer.setSuperclass(proxySuperClass); + enhancer.setStrategy(new UndeclaredThrowableStrategy(UndeclaredThrowableException.class)); + enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised)); + enhancer.setInterceptDuringConstruction(false); + + Callback[] callbacks = getCallbacks(rootClass); + enhancer.setCallbacks(callbacks); + enhancer.setCallbackFilter(new ProxyCallbackFilter( + this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset)); + + Class[] types = new Class[callbacks.length]; + for (int x = 0; x < types.length; x++) { + types[x] = callbacks[x].getClass(); + } + enhancer.setCallbackTypes(types); + + // Generate the proxy class and create a proxy instance. + Object proxy; + if (this.constructorArgs != null) { + proxy = enhancer.create(this.constructorArgTypes, this.constructorArgs); + } + else { + proxy = enhancer.create(); + } + + return proxy; + } + catch (CodeGenerationException ex) { + throw new AopConfigException("Could not generate CGLIB subclass of class [" + + this.advised.getTargetClass() + "]: " + + "Common causes of this problem include using a final class or a non-visible class", + ex); + } + catch (IllegalArgumentException ex) { + throw new AopConfigException("Could not generate CGLIB subclass of class [" + + this.advised.getTargetClass() + "]: " + + "Common causes of this problem include using a final class or a non-visible class", + ex); + } + catch (Exception ex) { + // TargetSource.getTarget() failed + throw new AopConfigException("Unexpected AOP exception", ex); + } + } + + /** + * Creates the CGLIB {@link Enhancer}. Subclasses may wish to override this to return a custom + * {@link Enhancer} implementation. + */ + protected Enhancer createEnhancer() { + return new Enhancer(); + } + + /** + * Checks to see whether the supplied Class has already been validated and + * validates it if not. + */ + private void validateClassIfNecessary(Class proxySuperClass) { + if (logger.isWarnEnabled()) { + synchronized (validatedClasses) { + if (!validatedClasses.containsKey(proxySuperClass)) { + doValidateClass(proxySuperClass); + validatedClasses.put(proxySuperClass, Boolean.TRUE); + } + } + } + } + + /** + * Checks for final methods on the Class and writes warnings to the log + * for each one found. + */ + private void doValidateClass(Class proxySuperClass) { + Method[] methods = proxySuperClass.getMethods(); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + if (!Object.class.equals(method.getDeclaringClass()) && Modifier.isFinal(method.getModifiers())) { + logger.warn("Unable to proxy method [" + method + "] because it is final: " + + "All calls to this method via a proxy will be routed directly to the proxy."); + } + } + } + + private Callback[] getCallbacks(Class rootClass) throws Exception { + // Parameters used for optimisation choices... + boolean exposeProxy = this.advised.isExposeProxy(); + boolean isFrozen = this.advised.isFrozen(); + boolean isStatic = this.advised.getTargetSource().isStatic(); + + // Choose an "aop" interceptor (used for AOP calls). + Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised); + + // Choose a "straight to target" interceptor. (used for calls that are + // unadvised but can return this). May be required to expose the proxy. + Callback targetInterceptor = null; + + if (exposeProxy) { + targetInterceptor = isStatic ? + (Callback) new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) : + (Callback) new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()); + } + else { + targetInterceptor = isStatic ? + (Callback) new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) : + (Callback) new DynamicUnadvisedInterceptor(this.advised.getTargetSource()); + } + + // Choose a "direct to target" dispatcher (used for + // unadvised calls to static targets that cannot return this). + Callback targetDispatcher = isStatic ? + (Callback) new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp(); + + Callback[] mainCallbacks = new Callback[]{ + aopInterceptor, // for normal advice + targetInterceptor, // invoke target without considering advice, if optimized + new SerializableNoOp(), // no override for methods mapped to this + targetDispatcher, this.advisedDispatcher, + new EqualsInterceptor(this.advised), + new HashCodeInterceptor(this.advised) + }; + + Callback[] callbacks; + + // If the target is a static one and the advice chain is frozen, + // then we can make some optimisations by sending the AOP calls + // direct to the target using the fixed chain for that method. + if (isStatic && isFrozen) { + Method[] methods = rootClass.getMethods(); + Callback[] fixedCallbacks = new Callback[methods.length]; + this.fixedInterceptorMap = new HashMap(methods.length); + + // TODO: small memory optimisation here (can skip creation for + // methods with no advice) + for (int x = 0; x < methods.length; x++) { + List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(methods[x], rootClass); + fixedCallbacks[x] = new FixedChainStaticTargetInterceptor( + chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass()); + this.fixedInterceptorMap.put(methods[x].toString(), new Integer(x)); + } + + // Now copy both the callbacks from mainCallbacks + // and fixedCallbacks into the callbacks array. + callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length]; + + for (int x = 0; x < mainCallbacks.length; x++) { + callbacks[x] = mainCallbacks[x]; + } + + for (int x = 0; x < fixedCallbacks.length; x++) { + callbacks[x + mainCallbacks.length] = fixedCallbacks[x]; + } + + this.fixedInterceptorOffset = mainCallbacks.length; + } + else { + callbacks = mainCallbacks; + } + return callbacks; + } + + /** + * Wrap a return of this if necessary to be the proxy + */ + private static Object massageReturnTypeIfNecessary(Object proxy, Object target, Method method, Object retVal) { + // Massage return value if necessary + if (retVal != null && retVal == target && + !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) { + // Special case: it returned "this". + // Note that we can't help if the target sets a reference + // to itself in another returned object. + retVal = proxy; + } + return retVal; + } + + + public boolean equals(Object other) { + return (this == other || (other instanceof Cglib2AopProxy && + AopProxyUtils.equalsInProxy(this.advised, ((Cglib2AopProxy) other).advised))); + } + + public int hashCode() { + return Cglib2AopProxy.class.hashCode() * 13 + this.advised.getTargetSource().hashCode(); + } + + + /** + * Serializable replacement for CGLIB's NoOp interface. + * Public to allow use elsewhere in the framework. + */ + public static class SerializableNoOp implements NoOp, Serializable { + } + + + /** + * Method interceptor used for static targets with no advice chain. The call + * is passed directly back to the target. Used when the proxy needs to be + * exposed and it can't be determined that the method won't return + * this. + */ + private static class StaticUnadvisedInterceptor implements MethodInterceptor, Serializable { + + private final Object target; + + public StaticUnadvisedInterceptor(Object target) { + this.target = target; + } + + public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { + Object retVal = methodProxy.invoke(this.target, args); + return massageReturnTypeIfNecessary(proxy, this.target, method, retVal); + } + } + + + /** + * Method interceptor used for static targets with no advice chain, when the + * proxy is to be exposed. + */ + private static class StaticUnadvisedExposedInterceptor implements MethodInterceptor, Serializable { + + private final Object target; + + public StaticUnadvisedExposedInterceptor(Object target) { + this.target = target; + } + + public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { + Object oldProxy = null; + try { + oldProxy = AopContext.setCurrentProxy(proxy); + Object retVal = methodProxy.invoke(this.target, args); + return massageReturnTypeIfNecessary(proxy, this.target, method, retVal); + } + finally { + AopContext.setCurrentProxy(oldProxy); + } + } + } + + + /** + * Interceptor used to invoke a dynamic target without creating a method + * invocation or evaluating an advice chain. (We know there was no advice + * for this method.) + */ + private static class DynamicUnadvisedInterceptor implements MethodInterceptor, Serializable { + + private final TargetSource targetSource; + + public DynamicUnadvisedInterceptor(TargetSource targetSource) { + this.targetSource = targetSource; + } + + public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { + Object target = this.targetSource.getTarget(); + try { + Object retVal = methodProxy.invoke(target, args); + return massageReturnTypeIfNecessary(proxy, target, method, retVal); + } + finally { + this.targetSource.releaseTarget(target); + } + } + } + + + /** + * Interceptor for unadvised dynamic targets when the proxy needs exposing. + */ + private static class DynamicUnadvisedExposedInterceptor implements MethodInterceptor, Serializable { + + private final TargetSource targetSource; + + public DynamicUnadvisedExposedInterceptor(TargetSource targetSource) { + this.targetSource = targetSource; + } + + public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { + Object oldProxy = null; + Object target = this.targetSource.getTarget(); + try { + oldProxy = AopContext.setCurrentProxy(proxy); + Object retVal = methodProxy.invoke(target, args); + return massageReturnTypeIfNecessary(proxy, target, method, retVal); + } + finally { + AopContext.setCurrentProxy(oldProxy); + this.targetSource.releaseTarget(target); + } + } + } + + + /** + * Dispatcher for a static target. Dispatcher is much faster than + * interceptor. This will be used whenever it can be determined that a + * method definitely does not return "this" + */ + private static class StaticDispatcher implements Dispatcher, Serializable { + + private Object target; + + public StaticDispatcher(Object target) { + this.target = target; + } + + public Object loadObject() { + return this.target; + } + } + + + /** + * Dispatcher for any methods declared on the Advised class. + */ + private static class AdvisedDispatcher implements Dispatcher, Serializable { + + private final AdvisedSupport advised; + + public AdvisedDispatcher(AdvisedSupport advised) { + this.advised = advised; + } + + public Object loadObject() throws Exception { + return this.advised; + } + } + + + /** + * Dispatcher for the equals method. + * Ensures that the method call is always handled by this class. + */ + private static class EqualsInterceptor implements MethodInterceptor, Serializable { + + private final AdvisedSupport advised; + + public EqualsInterceptor(AdvisedSupport advised) { + this.advised = advised; + } + + public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) { + Object other = args[0]; + if (proxy == other) { + return Boolean.TRUE; + } + AdvisedSupport otherAdvised = null; + if (other instanceof Factory) { + Callback callback = ((Factory) other).getCallback(INVOKE_EQUALS); + if (!(callback instanceof EqualsInterceptor)) { + return Boolean.FALSE; + } + otherAdvised = ((EqualsInterceptor) callback).advised; + } + else { + return Boolean.FALSE; + } + return (AopProxyUtils.equalsInProxy(this.advised, otherAdvised) ? Boolean.TRUE : Boolean.FALSE); + } + } + + + /** + * Dispatcher for the hashCode method. + * Ensures that the method call is always handled by this class. + */ + private static class HashCodeInterceptor implements MethodInterceptor, Serializable { + + private final AdvisedSupport advised; + + public HashCodeInterceptor(AdvisedSupport advised) { + this.advised = advised; + } + + public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) { + return new Integer(Cglib2AopProxy.class.hashCode() * 13 + this.advised.getTargetSource().hashCode()); + } + } + + + /** + * Interceptor used specifically for advised methods on a frozen, static proxy. + */ + private static class FixedChainStaticTargetInterceptor implements MethodInterceptor, Serializable { + + private final List adviceChain; + + private final Object target; + + private final Class targetClass; + + public FixedChainStaticTargetInterceptor(List adviceChain, Object target, Class targetClass) { + this.adviceChain = adviceChain; + this.target = target; + this.targetClass = targetClass; + } + + public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { + Object retVal = null; + MethodInvocation invocation = new CglibMethodInvocation(proxy, this.target, method, args, + this.targetClass, this.adviceChain, methodProxy); + // If we get here, we need to create a MethodInvocation. + retVal = invocation.proceed(); + retVal = massageReturnTypeIfNecessary(proxy, this.target, method, retVal); + return retVal; + } + } + + + /** + * General purpose AOP callback. Used when the target is dynamic or when the + * proxy is not frozen. + */ + private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable { + + private AdvisedSupport advised; + + public DynamicAdvisedInterceptor(AdvisedSupport advised) { + this.advised = advised; + } + + public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { + MethodInvocation invocation = null; + Object oldProxy = null; + boolean setProxyContext = false; + Class targetClass = null; + Object target = null; + try { + Object retVal = null; + if (this.advised.exposeProxy) { + // Make invocation available if necessary. + oldProxy = AopContext.setCurrentProxy(proxy); + setProxyContext = true; + } + // May be null. Get as late as possible to minimize the time we + // "own" the target, in case it comes from a pool. + target = getTarget(); + if (target != null) { + targetClass = target.getClass(); + } + List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); + // Check whether we only have one InvokerInterceptor: that is, + // no real advice, but just reflective invocation of the target. + if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) { + // We can skip creating a MethodInvocation: just invoke the target directly. + // Note that the final invoker must be an InvokerInterceptor, so we know + // it does nothing but a reflective operation on the target, and no hot + // swapping or fancy proxying. + retVal = methodProxy.invoke(target, args); + } + else { + // We need to create a method invocation... + invocation = new CglibMethodInvocation(proxy, target, method, args, + targetClass, chain, methodProxy); + // If we get here, we need to create a MethodInvocation. + retVal = invocation.proceed(); + } + + retVal = massageReturnTypeIfNecessary(proxy, target, method, retVal); + return retVal; + } + finally { + if (target != null) { + releaseTarget(target); + } + if (setProxyContext) { + // Restore old proxy. + AopContext.setCurrentProxy(oldProxy); + } + } + } + + public boolean equals(Object other) { + return (this == other || + (other instanceof DynamicAdvisedInterceptor && + this.advised.equals(((DynamicAdvisedInterceptor) other).advised))); + } + + /** + * CGLIB uses this to drive proxy creation. + */ + public int hashCode() { + return this.advised.hashCode(); + } + + protected Object getTarget() throws Exception { + return this.advised.getTargetSource().getTarget(); + } + + protected void releaseTarget(Object target) throws Exception { + this.advised.getTargetSource().releaseTarget(target); + } + } + + + /** + * Implementation of AOP Alliance MethodInvocation used by this AOP proxy. + */ + private static class CglibMethodInvocation extends ReflectiveMethodInvocation { + + private final MethodProxy methodProxy; + + private boolean protectedMethod; + + public CglibMethodInvocation(Object proxy, Object target, Method method, Object[] arguments, + Class targetClass, List interceptorsAndDynamicMethodMatchers, MethodProxy methodProxy) { + super(proxy, target, method, arguments, targetClass, interceptorsAndDynamicMethodMatchers); + this.methodProxy = methodProxy; + this.protectedMethod = Modifier.isProtected(method.getModifiers()); + } + + /** + * Gives a marginal performance improvement versus using reflection to + * invoke the target when invoking public methods. + */ + protected Object invokeJoinpoint() throws Throwable { + if (this.protectedMethod) { + return super.invokeJoinpoint(); + } + else { + return this.methodProxy.invoke(this.target, this.arguments); + } + } + } + + + /** + * CallbackFilter to assign Callbacks to methods. + */ + private static class ProxyCallbackFilter implements CallbackFilter { + + private final AdvisedSupport advised; + + private final Map fixedInterceptorMap; + + private final int fixedInterceptorOffset; + + public ProxyCallbackFilter(AdvisedSupport advised, Map fixedInterceptorMap, int fixedInterceptorOffset) { + this.advised = advised; + this.fixedInterceptorMap = fixedInterceptorMap; + this.fixedInterceptorOffset = fixedInterceptorOffset; + } + + /** + * Implementation of CallbackFilter.accept() to return the index of the + * callback we need. + *

The callbacks for each proxy are built up of a set of fixed callbacks + * for general use and then a set of callbacks that are specific to a method + * for use on static targets with a fixed advice chain. + *

The callback used is determined thus: + *

+ *
For exposed proxies
+ *
Exposing the proxy requires code to execute before and after the + * method/chain invocation. This means we must use + * DynamicAdvisedInterceptor, since all other interceptors can avoid the + * need for a try/catch block
+ *
For Object.finalize():
+ *
No override for this method is used.
+ *
For equals():
+ *
The EqualsInterceptor is used to redirect equals() calls to a + * special handler to this proxy.
+ *
For methods on the Advised class:
+ *
the AdvisedDispatcher is used to dispatch the call directly to + * the target
+ *
For advised methods:
+ *
If the target is static and the advice chain is frozen then a + * FixedChainStaticTargetInterceptor specific to the method is used to + * invoke the advice chain. Otherwise a DyanmicAdvisedInterceptor is + * used.
+ *
For non-advised methods:
+ *
Where it can be determined that the method will not return this + * or when ProxyFactory.getExposeProxy() returns false, + * then a Dispatcher is used. For static targets, the StaticDispatcher is used; + * and for dynamic targets, a DynamicUnadvisedInterceptor is used. + * If it possible for the method to return this then a + * StaticUnadvisedInterceptor is used for static targets - the + * DynamicUnadvisedInterceptor already considers this.
+ *
+ */ + public int accept(Method method) { + if (AopUtils.isFinalizeMethod(method)) { + logger.debug("Found finalize() method - using NO_OVERRIDE"); + return NO_OVERRIDE; + } + if (!this.advised.isOpaque() && method.getDeclaringClass().isInterface() && + method.getDeclaringClass().isAssignableFrom(Advised.class)) { + if (logger.isDebugEnabled()) { + logger.debug("Method is declared on Advised interface: " + method); + } + return DISPATCH_ADVISED; + } + // We must always proxy equals, to direct calls to this. + if (AopUtils.isEqualsMethod(method)) { + logger.debug("Found 'equals' method: " + method); + return INVOKE_EQUALS; + } + // We must always calculate hashCode based on the proxy. + if (AopUtils.isHashCodeMethod(method)) { + logger.debug("Found 'hashCode' method: " + method); + return INVOKE_HASHCODE; + } + Class targetClass = this.advised.getTargetClass(); + // Proxy is not yet available, but that shouldn't matter. + List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); + boolean haveAdvice = !chain.isEmpty(); + boolean exposeProxy = this.advised.isExposeProxy(); + boolean isStatic = this.advised.getTargetSource().isStatic(); + boolean isFrozen = this.advised.isFrozen(); + if (haveAdvice || !isFrozen) { + // If exposing the proxy, then AOP_PROXY must be used. + if (exposeProxy) { + if (logger.isDebugEnabled()) { + logger.debug("Must expose proxy on advised method: " + method); + } + return AOP_PROXY; + } + String key = method.toString(); + // Check to see if we have fixed interceptor to serve this method. + // Else use the AOP_PROXY. + if (isStatic && isFrozen && this.fixedInterceptorMap.containsKey(key)) { + if (logger.isDebugEnabled()) { + logger.debug("Method has advice and optimisations are enabled: " + method); + } + // We know that we are optimising so we can use the + // FixedStaticChainInterceptors. + int index = ((Integer) this.fixedInterceptorMap.get(key)).intValue(); + return (index + this.fixedInterceptorOffset); + } + else { + if (logger.isDebugEnabled()) { + logger.debug("Unable to apply any optimisations to advised method: " + method); + } + return AOP_PROXY; + } + } + else { + // See if the return type of the method is outside the class hierarchy + // of the target type. If so we know it never needs to have return type + // massage and can use a dispatcher. + // If the proxy is being exposed, then must use the interceptor the + // correct one is already configured. If the target is not static cannot + // use a Dispatcher because the target can not then be released. + if (exposeProxy || !isStatic) { + return INVOKE_TARGET; + } + Class returnType = method.getReturnType(); + if (targetClass == returnType) { + if (logger.isDebugEnabled()) { + logger.debug("Method " + method + + "has return type same as target type (may return this) - using INVOKE_TARGET"); + } + return INVOKE_TARGET; + } + else if (returnType.isPrimitive() || !returnType.isAssignableFrom(targetClass)) { + if (logger.isDebugEnabled()) { + logger.debug("Method " + method + + " has return type that ensures this cannot be returned- using DISPATCH_TARGET"); + } + return DISPATCH_TARGET; + } + else { + if (logger.isDebugEnabled()) { + logger.debug("Method " + method + + "has return type that is assignable from the target type (may return this) - " + + "using INVOKE_TARGET"); + } + return INVOKE_TARGET; + } + } + } + + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof ProxyCallbackFilter)) { + return false; + } + ProxyCallbackFilter otherCallbackFilter = (ProxyCallbackFilter) other; + AdvisedSupport otherAdvised = otherCallbackFilter.advised; + if (this.advised == null || otherAdvised == null) { + return false; + } + if (this.advised.isFrozen() != otherAdvised.isFrozen()) { + return false; + } + if (this.advised.isExposeProxy() != otherAdvised.isExposeProxy()) { + return false; + } + if (this.advised.getTargetSource().isStatic() != otherAdvised.getTargetSource().isStatic()) { + return false; + } + if (!AopProxyUtils.equalsProxiedInterfaces(this.advised, otherAdvised)) { + return false; + } + // Advice instance identity is unimportant to the proxy class: + // All that matters is type and ordering. + Advisor[] thisAdvisors = this.advised.getAdvisors(); + Advisor[] thatAdvisors = otherAdvised.getAdvisors(); + if (thisAdvisors.length != thatAdvisors.length) { + return false; + } + for (int i = 0; i < thisAdvisors.length; i++) { + Advisor thisAdvisor = thisAdvisors[i]; + Advisor thatAdvisor = thatAdvisors[i]; + if (!equalsAdviceClasses(thisAdvisor, thatAdvisor)) { + return false; + } + if (!equalsPointcuts(thisAdvisor, thatAdvisor)) { + return false; + } + } + return true; + } + + private boolean equalsAdviceClasses(Advisor a, Advisor b) { + Advice aa = a.getAdvice(); + Advice ba = b.getAdvice(); + if (aa == null || ba == null) { + return (aa == ba); + } + return aa.getClass().equals(ba.getClass()); + } + + private boolean equalsPointcuts(Advisor a, Advisor b) { + // If only one of the advisor (but not both) is PointcutAdvisor, then it is a mismatch. + // Takes care of the situations where an IntroductionAdvisor is used (see SPR-3959). + if (a instanceof PointcutAdvisor ^ b instanceof PointcutAdvisor) { + return false; + } + // If both are PointcutAdvisor, match their pointcuts. + if (a instanceof PointcutAdvisor && b instanceof PointcutAdvisor) { + return ObjectUtils.nullSafeEquals(((PointcutAdvisor) a).getPointcut(), ((PointcutAdvisor) b).getPointcut()); + } + // If neither is PointcutAdvisor, then from the pointcut matching perspective, it is a match. + return true; + } + + public int hashCode() { + int hashCode = 0; + Advisor[] advisors = this.advised.getAdvisors(); + for (int i = 0; i < advisors.length; i++) { + Advice advice = advisors[i].getAdvice(); + if (advice != null) { + hashCode = 13 * hashCode + advice.getClass().hashCode(); + } + } + hashCode = 13 * hashCode + (this.advised.isFrozen() ? 1 : 0); + hashCode = 13 * hashCode + (this.advised.isExposeProxy() ? 1 : 0); + hashCode = 13 * hashCode + (this.advised.isOptimize() ? 1 : 0); + hashCode = 13 * hashCode + (this.advised.isOpaque() ? 1 : 0); + return hashCode; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/DefaultAdvisorChainFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/DefaultAdvisorChainFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/DefaultAdvisorChainFactory.java 17 Aug 2012 15:11:24 -0000 1.1 @@ -0,0 +1,108 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.aopalliance.intercept.Interceptor; +import org.aopalliance.intercept.MethodInterceptor; + +import org.springframework.aop.Advisor; +import org.springframework.aop.IntroductionAdvisor; +import org.springframework.aop.MethodMatcher; +import org.springframework.aop.PointcutAdvisor; +import org.springframework.aop.framework.adapter.AdvisorAdapterRegistry; +import org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry; +import org.springframework.aop.support.MethodMatchers; + +/** + * A simple but definitive way of working out an advice chain for a Method, + * given an {@link Advised} object. Always rebuilds each advice chain; + * caching can be provided by subclasses. + * + * @author Juergen Hoeller + * @author Rod Johnson + * @author Adrian Colyer + * @since 2.0.3 + */ +public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable { + + public List getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class targetClass) { + // This is somewhat tricky... we have to process introductions first, + // but we need to preserve order in the ultimate list. + List interceptorList = new ArrayList(config.getAdvisors().length); + boolean hasIntroductions = hasMatchingIntroductions(config, targetClass); + AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance(); + Advisor[] advisors = config.getAdvisors(); + for (int i = 0; i < advisors.length; i++) { + Advisor advisor = advisors[i]; + if (advisor instanceof PointcutAdvisor) { + // Add it conditionally. + PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor; + if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(targetClass)) { + MethodInterceptor[] interceptors = registry.getInterceptors(advisor); + MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher(); + if (MethodMatchers.matches(mm, method, targetClass, hasIntroductions)) { + if (mm.isRuntime()) { + // Creating a new object instance in the getInterceptors() method + // isn't a problem as we normally cache created chains. + for (int j = 0; j < interceptors.length; j++) { + interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptors[j], mm)); + } + } + else { + interceptorList.addAll(Arrays.asList(interceptors)); + } + } + } + } + else if (advisor instanceof IntroductionAdvisor) { + IntroductionAdvisor ia = (IntroductionAdvisor) advisor; + if (config.isPreFiltered() || ia.getClassFilter().matches(targetClass)) { + Interceptor[] interceptors = registry.getInterceptors(advisor); + interceptorList.addAll(Arrays.asList(interceptors)); + } + } + else { + Interceptor[] interceptors = registry.getInterceptors(advisor); + interceptorList.addAll(Arrays.asList(interceptors)); + } + } + return interceptorList; + } + + /** + * Determine whether the Advisors contain matching introductions. + */ + private static boolean hasMatchingIntroductions(Advised config, Class targetClass) { + for (int i = 0; i < config.getAdvisors().length; i++) { + Advisor advisor = config.getAdvisors()[i]; + if (advisor instanceof IntroductionAdvisor) { + IntroductionAdvisor ia = (IntroductionAdvisor) advisor; + if (ia.getClassFilter().matches(targetClass)) { + return true; + } + } + } + return false; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/DefaultAopProxyFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/DefaultAopProxyFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/DefaultAopProxyFactory.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,100 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import java.io.Serializable; + +import org.springframework.aop.SpringProxy; +import org.springframework.util.ClassUtils; + +/** + * Default {@link AopProxyFactory} implementation, + * creating either a CGLIB proxy or a JDK dynamic proxy. + * + *

Creates a CGLIB proxy if one the following is true + * for a given {@link AdvisedSupport} instance: + *

    + *
  • the "optimize" flag is set + *
  • the "proxyTargetClass" flag is set + *
  • no proxy interfaces have been specified + *
+ * + *

Note that the CGLIB library classes have to be present on + * the class path if an actual CGLIB proxy needs to be created. + * + *

In general, specify "proxyTargetClass" to enforce a CGLIB proxy, + * or specify one or more interfaces to use a JDK dynamic proxy. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 12.03.2004 + * @see AdvisedSupport#setOptimize + * @see AdvisedSupport#setProxyTargetClass + * @see AdvisedSupport#setInterfaces + */ +public class DefaultAopProxyFactory implements AopProxyFactory, Serializable { + + /** Whether the CGLIB2 library is present on the classpath */ + private static final boolean cglibAvailable = + ClassUtils.isPresent("net.sf.cglib.proxy.Enhancer", DefaultAopProxyFactory.class.getClassLoader()); + + + public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException { + if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) { + Class targetClass = config.getTargetClass(); + if (targetClass == null) { + throw new AopConfigException("TargetSource cannot determine target class: " + + "Either an interface or a target is required for proxy creation."); + } + if (targetClass.isInterface()) { + return new JdkDynamicAopProxy(config); + } + if (!cglibAvailable) { + throw new AopConfigException( + "Cannot proxy target class because CGLIB2 is not available. " + + "Add CGLIB to the class path or specify proxy interfaces."); + } + return CglibProxyFactory.createCglibProxy(config); + } + else { + return new JdkDynamicAopProxy(config); + } + } + + /** + * Determine whether the supplied {@link AdvisedSupport} has only the + * {@link org.springframework.aop.SpringProxy} interface specified + * (or no proxy interfaces specified at all). + */ + private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) { + Class[] interfaces = config.getProxiedInterfaces(); + return (interfaces.length == 0 || (interfaces.length == 1 && SpringProxy.class.equals(interfaces[0]))); + } + + + /** + * Inner factory class used to just introduce a CGLIB2 dependency + * when actually creating a CGLIB proxy. + */ + private static class CglibProxyFactory { + + public static AopProxy createCglibProxy(AdvisedSupport advisedSupport) { + return new Cglib2AopProxy(advisedSupport); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/InterceptorAndDynamicMethodMatcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/InterceptorAndDynamicMethodMatcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/InterceptorAndDynamicMethodMatcher.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import org.aopalliance.intercept.MethodInterceptor; + +import org.springframework.aop.MethodMatcher; + +/** + * Internal framework class, combining a MethodInterceptor instance + * with a MethodMatcher for use as an element in the advisor chain. + * + * @author Rod Johnson + */ +class InterceptorAndDynamicMethodMatcher { + + final MethodInterceptor interceptor; + + final MethodMatcher methodMatcher; + + public InterceptorAndDynamicMethodMatcher(MethodInterceptor interceptor, MethodMatcher methodMatcher) { + this.interceptor = interceptor; + this.methodMatcher = methodMatcher; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/JdkDynamicAopProxy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/JdkDynamicAopProxy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/JdkDynamicAopProxy.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,270 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import java.io.Serializable; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.List; + +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.aop.RawTargetAccess; +import org.springframework.aop.TargetSource; +import org.springframework.aop.support.AopUtils; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; + +/** + * JDK-based {@link AopProxy} implementation for the Spring AOP framework, + * based on JDK {@link java.lang.reflect.Proxy dynamic proxies}. + * + *

Creates a dynamic proxy, implementing the interfaces exposed by + * the AopProxy. Dynamic proxies cannot be used to proxy methods + * defined in classes, rather than interfaces. + * + *

Objects of this type should be obtained through proxy factories, + * configured by an {@link AdvisedSupport} class. This class is internal + * to Spring's AOP framework and need not be used directly by client code. + * + *

Proxies created using this class will be thread-safe if the + * underlying (target) class is thread-safe. + * + *

Proxies are serializable so long as all Advisors (including Advices + * and Pointcuts) and the TargetSource are serializable. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + * @see java.lang.reflect.Proxy + * @see AdvisedSupport + * @see ProxyFactory + */ +final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable { + + /** use serialVersionUID from Spring 1.2 for interoperability */ + private static final long serialVersionUID = 5531744639992436476L; + + + /* + * NOTE: We could avoid the code duplication between this class and the CGLIB + * proxies by refactoring "invoke" into a template method. However, this approach + * adds at least 10% performance overhead versus a copy-paste solution, so we sacrifice + * elegance for performance. (We have a good test suite to ensure that the different + * proxies behave the same :-) + * This way, we can also more easily take advantage of minor optimizations in each class. + */ + + /** We use a static Log to avoid serialization issues */ + private static Log logger = LogFactory.getLog(JdkDynamicAopProxy.class); + + /** Config used to configure this proxy */ + private final AdvisedSupport advised; + + /** + * Is the {@link #equals} method defined on the proxied interfaces? + */ + private boolean equalsDefined; + + /** + * Is the {@link #hashCode} method defined on the proxied interfaces? + */ + private boolean hashCodeDefined; + + + /** + * Construct a new JdkDynamicAopProxy for the given AOP configuration. + * @param config the AOP configuration as AdvisedSupport object + * @throws AopConfigException if the config is invalid. We try to throw an informative + * exception in this case, rather than let a mysterious failure happen later. + */ + public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException { + Assert.notNull(config, "AdvisedSupport must not be null"); + if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) { + throw new AopConfigException("No advisors and no TargetSource specified"); + } + this.advised = config; + } + + + public Object getProxy() { + return getProxy(ClassUtils.getDefaultClassLoader()); + } + + public Object getProxy(ClassLoader classLoader) { + if (logger.isDebugEnabled()) { + logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource()); + } + Class[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised); + findDefinedEqualsAndHashCodeMethods(proxiedInterfaces); + return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this); + } + + /** + * Finds any {@link #equals} or {@link #hashCode} method that may be defined + * on the supplied set of interfaces. + * @param proxiedInterfaces the interfaces to introspect + */ + private void findDefinedEqualsAndHashCodeMethods(Class[] proxiedInterfaces) { + for (int i = 0; i < proxiedInterfaces.length; i++) { + Class proxiedInterface = proxiedInterfaces[i]; + Method[] methods = proxiedInterface.getDeclaredMethods(); + for (int j = 0; j < methods.length; j++) { + Method method = methods[j]; + if (AopUtils.isEqualsMethod(method)) { + this.equalsDefined = true; + } + if (AopUtils.isHashCodeMethod(method)) { + this.hashCodeDefined = true; + } + if (this.equalsDefined && this.hashCodeDefined) { + return; + } + } + } + } + + + /** + * Implementation of InvocationHandler.invoke. + *

Callers will see exactly the exception thrown by the target, + * unless a hook method throws an exception. + */ + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + MethodInvocation invocation = null; + Object oldProxy = null; + boolean setProxyContext = false; + + TargetSource targetSource = this.advised.targetSource; + Class targetClass = null; + Object target = null; + + try { + if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) { + // The target does not implement the equals(Object) method itself. + return (equals(args[0]) ? Boolean.TRUE : Boolean.FALSE); + } + if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) { + // The target does not implement the hashCode() method itself. + return new Integer(hashCode()); + } + if (!this.advised.opaque && method.getDeclaringClass().isInterface() && + method.getDeclaringClass().isAssignableFrom(Advised.class)) { + // Service invocations on ProxyConfig with the proxy config... + return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args); + } + + Object retVal = null; + + if (this.advised.exposeProxy) { + // Make invocation available if necessary. + oldProxy = AopContext.setCurrentProxy(proxy); + setProxyContext = true; + } + + // May be null. Get as late as possible to minimize the time we "own" the target, + // in case it comes from a pool. + target = targetSource.getTarget(); + if (target != null) { + targetClass = target.getClass(); + } + + // Get the interception chain for this method. + List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); + + // Check whether we have any advice. If we don't, we can fallback on direct + // reflective invocation of the target, and avoid creating a MethodInvocation. + if (chain.isEmpty()) { + // We can skip creating a MethodInvocation: just invoke the target directly + // Note that the final invoker must be an InvokerInterceptor so we know it does + // nothing but a reflective operation on the target, and no hot swapping or fancy proxying. + retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args); + } + else { + // We need to create a method invocation... + invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain); + // Proceed to the joinpoint through the interceptor chain. + retVal = invocation.proceed(); + } + + // Massage return value if necessary. + if (retVal != null && retVal == target && method.getReturnType().isInstance(proxy) && + !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) { + // Special case: it returned "this" and the return type of the method + // is type-compatible. Note that we can't help if the target sets + // a reference to itself in another returned object. + retVal = proxy; + } + return retVal; + } + finally { + if (target != null && !targetSource.isStatic()) { + // Must have come from TargetSource. + targetSource.releaseTarget(target); + } + if (setProxyContext) { + // Restore old proxy. + AopContext.setCurrentProxy(oldProxy); + } + } + } + + + /** + * Equality means interfaces, advisors and TargetSource are equal. + *

The compared object may be a JdkDynamicAopProxy instance itself + * or a dynamic proxy wrapping a JdkDynamicAopProxy instance. + */ + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (other == null) { + return false; + } + + JdkDynamicAopProxy otherProxy = null; + if (other instanceof JdkDynamicAopProxy) { + otherProxy = (JdkDynamicAopProxy) other; + } + else if (Proxy.isProxyClass(other.getClass())) { + InvocationHandler ih = Proxy.getInvocationHandler(other); + if (!(ih instanceof JdkDynamicAopProxy)) { + return false; + } + otherProxy = (JdkDynamicAopProxy) ih; + } + else { + // Not a valid comparison... + return false; + } + + // If we get here, aopr2 is the other AopProxy. + return AopProxyUtils.equalsInProxy(this.advised, otherProxy.advised); + } + + /** + * Proxy uses the hash code of the TargetSource. + */ + public int hashCode() { + return JdkDynamicAopProxy.class.hashCode() * 13 + this.advised.getTargetSource().hashCode(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/ProxyConfig.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/ProxyConfig.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/ProxyConfig.java 17 Aug 2012 15:11:24 -0000 1.1 @@ -0,0 +1,171 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import java.io.Serializable; + +import org.springframework.util.Assert; + +/** + * Convenience superclass for configuration used in creating proxies, + * to ensure that all proxy creators have consistent properties. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see AdvisedSupport + */ +public class ProxyConfig implements Serializable { + + /** use serialVersionUID from Spring 1.2 for interoperability */ + private static final long serialVersionUID = -8409359707199703185L; + + + private boolean proxyTargetClass = false; + + private boolean optimize = false; + + boolean opaque = false; + + boolean exposeProxy = false; + + private boolean frozen = false; + + + /** + * Set whether to proxy the target class directly, instead of just proxying + * specific interfaces. Default is "false". + *

Set this to "true" to force proxying for the TargetSource's exposed + * target class. If that target class is an interface, a JDK proxy will be + * created for the given interface. If that target class is any other class, + * a CGLIB proxy will be created for the given class. + *

Note: Depending on the configuration of the concrete proxy factory, + * the proxy-target-class behavior will also be applied if no interfaces + * have been specified (and no interface autodetection is activated). + * @see org.springframework.aop.TargetSource#getTargetClass() + */ + public void setProxyTargetClass(boolean proxyTargetClass) { + this.proxyTargetClass = proxyTargetClass; + } + + /** + * Return whether to proxy the target class directly as well as any interfaces. + */ + public boolean isProxyTargetClass() { + return this.proxyTargetClass; + } + + /** + * Set whether proxies should perform aggressive optimizations. + * The exact meaning of "aggressive optimizations" will differ + * between proxies, but there is usually some tradeoff. + * Default is "false". + *

For example, optimization will usually mean that advice changes won't + * take effect after a proxy has been created. For this reason, optimization + * is disabled by default. An optimize value of "true" may be ignored + * if other settings preclude optimization: for example, if "exposeProxy" + * is set to "true" and that's not compatible with the optimization. + */ + public void setOptimize(boolean optimize) { + this.optimize = optimize; + } + + /** + * Return whether proxies should perform aggressive optimizations. + */ + public boolean isOptimize() { + return this.optimize; + } + + /** + * Set whether proxies created by this configuration should be prevented + * from being cast to {@link Advised} to query proxy status. + *

Default is "false", meaning that any AOP proxy can be cast to + * {@link Advised}. + */ + public void setOpaque(boolean opaque) { + this.opaque = opaque; + } + + /** + * Return whether proxies created by this configuration should be + * prevented from being cast to {@link Advised}. + */ + public boolean isOpaque() { + return this.opaque; + } + + /** + * Set whether the proxy should be exposed by the AOP framework as a + * ThreadLocal for retrieval via the AopContext class. This is useful + * if an advised object needs to call another advised method on itself. + * (If it uses this, the invocation will not be advised). + *

Default is "false", for optimal performance. + */ + public void setExposeProxy(boolean exposeProxy) { + this.exposeProxy = exposeProxy; + } + + /** + * Return whether the AOP proxy will expose the AOP proxy for + * each invocation. + */ + public boolean isExposeProxy() { + return this.exposeProxy; + } + + /** + * Set whether this config should be frozen. + *

When a config is frozen, no advice changes can be made. This is + * useful for optimization, and useful when we don't want callers to + * be able to manipulate configuration after casting to Advised. + */ + public void setFrozen(boolean frozen) { + this.frozen = frozen; + } + + /** + * Return whether the config is frozen, and no advice changes can be made. + */ + public boolean isFrozen() { + return this.frozen; + } + + + /** + * Copy configuration from the other config object. + * @param other object to copy configuration from + */ + public void copyFrom(ProxyConfig other) { + Assert.notNull(other, "Other ProxyConfig object must not be null"); + this.proxyTargetClass = other.proxyTargetClass; + this.optimize = other.optimize; + this.exposeProxy = other.exposeProxy; + this.frozen = other.frozen; + this.opaque = other.opaque; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("proxyTargetClass=").append(this.proxyTargetClass).append("; "); + sb.append("optimize=").append(this.optimize).append("; "); + sb.append("opaque=").append(this.opaque).append("; "); + sb.append("exposeProxy=").append(this.exposeProxy).append("; "); + sb.append("frozen=").append(this.frozen); + return sb.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/ProxyCreatorSupport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/ProxyCreatorSupport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/ProxyCreatorSupport.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,142 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import java.util.LinkedList; +import java.util.List; + +import org.springframework.util.Assert; + +/** + * Base class for proxy factories. + * Provides convenient access to a configurable AopProxyFactory. + * + * @author Juergen Hoeller + * @since 2.0.3 + * @see #createAopProxy() + */ +public class ProxyCreatorSupport extends AdvisedSupport { + + /** The AopProxyFactory to use */ + private AopProxyFactory aopProxyFactory; + + /** List of AdvisedSupportListener */ + private List listeners = new LinkedList(); + + /** Set to true when the first AOP proxy has been created */ + private boolean active = false; + + + /** + * Create a new ProxyCreatorSupport instance. + */ + public ProxyCreatorSupport() { + this.aopProxyFactory = new DefaultAopProxyFactory(); + } + + /** + * Create a new ProxyCreatorSupport instance. + * @param aopProxyFactory the AopProxyFactory to use + */ + public ProxyCreatorSupport(AopProxyFactory aopProxyFactory) { + Assert.notNull(aopProxyFactory, "AopProxyFactory must not be null"); + this.aopProxyFactory = aopProxyFactory; + } + + + /** + * Customize the AopProxyFactory, allowing different strategies + * to be dropped in without changing the core framework. + *

Default is {@link DefaultAopProxyFactory}, using dynamic JDK + * proxies or CGLIB proxies based on the requirements. + */ + public void setAopProxyFactory(AopProxyFactory aopProxyFactory) { + Assert.notNull(aopProxyFactory, "AopProxyFactory must not be null"); + this.aopProxyFactory = aopProxyFactory; + } + + /** + * Return the AopProxyFactory that this ProxyConfig uses. + */ + public AopProxyFactory getAopProxyFactory() { + return this.aopProxyFactory; + } + + /** + * Add the given AdvisedSupportListener to this proxy configuration. + * @param listener the listener to register + */ + public void addListener(AdvisedSupportListener listener) { + Assert.notNull(listener, "AdvisedSupportListener must not be null"); + this.listeners.add(listener); + } + + /** + * Remove the given AdvisedSupportListener from this proxy configuration. + * @param listener the listener to deregister + */ + public void removeListener(AdvisedSupportListener listener) { + Assert.notNull(listener, "AdvisedSupportListener must not be null"); + this.listeners.remove(listener); + } + + + /** + * Subclasses should call this to get a new AOP proxy. They should not + * create an AOP proxy with this as an argument. + */ + protected final synchronized AopProxy createAopProxy() { + if (!this.active) { + activate(); + } + return getAopProxyFactory().createAopProxy(this); + } + + /** + * Activate this proxy configuration. + * @see AdvisedSupportListener#activated + */ + private void activate() { + this.active = true; + for (int i = 0; i < this.listeners.size(); i++) { + ((AdvisedSupportListener) this.listeners.get(i)).activated(this); + } + } + + /** + * Propagate advice change event to all AdvisedSupportListeners. + * @see AdvisedSupportListener#adviceChanged + */ + protected void adviceChanged() { + super.adviceChanged(); + synchronized (this) { + if (this.active) { + for (int i = 0; i < this.listeners.size(); i++) { + ((AdvisedSupportListener) this.listeners.get(i)).adviceChanged(this); + } + } + } + } + + /** + * Subclasses can call this to check whether any AOP proxies have been created yet. + */ + protected final synchronized boolean isActive() { + return this.active; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/ProxyFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/ProxyFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/ProxyFactory.java 17 Aug 2012 15:11:24 -0000 1.1 @@ -0,0 +1,156 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import org.aopalliance.intercept.Interceptor; + +import org.springframework.aop.TargetSource; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; + +/** + * Factory for AOP proxies for programmatic use, rather than via a bean + * factory. This class provides a simple way of obtaining and configuring + * AOP proxies in code. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + * @since 14.03.2003 + */ +public class ProxyFactory extends ProxyCreatorSupport implements AopProxy { + + /** + * Create a new ProxyFactory. + */ + public ProxyFactory() { + } + + /** + * Create a new ProxyFactory. + *

Will proxy all interfaces that the given target implements. + * @param target the target object to be proxied + */ + public ProxyFactory(Object target) { + Assert.notNull(target, "Target object must not be null"); + setInterfaces(ClassUtils.getAllInterfaces(target)); + setTarget(target); + } + + /** + * Create a new ProxyFactory. + *

No target, only interfaces. Must add interceptors. + * @param proxyInterfaces the interfaces that the proxy should implement + */ + public ProxyFactory(Class[] proxyInterfaces) { + setInterfaces(proxyInterfaces); + } + + /** + * Create a new ProxyFactory for the given interface and interceptor. + *

Convenience method for creating a proxy for a single interceptor, + * assuming that the interceptor handles all calls itself rather than + * delegating to a target, like in the case of remoting proxies. + * @param proxyInterface the interface that the proxy should implement + * @param interceptor the interceptor that the proxy should invoke + */ + public ProxyFactory(Class proxyInterface, Interceptor interceptor) { + addInterface(proxyInterface); + addAdvice(interceptor); + } + + /** + * Create a ProxyFactory for the specified TargetSource, + * making the proxy implement the specified interface. + * @param proxyInterface the interface that the proxy should implement + * @param targetSource the TargetSource that the proxy should invoke + */ + public ProxyFactory(Class proxyInterface, TargetSource targetSource) { + addInterface(proxyInterface); + setTargetSource(targetSource); + } + + + /** + * Create a new proxy according to the settings in this factory. + *

Can be called repeatedly. Effect will vary if we've added + * or removed interfaces. Can add and remove interceptors. + *

Uses a default class loader: Usually, the thread context class loader + * (if necessary for proxy creation). + * @return the proxy object + */ + public Object getProxy() { + return createAopProxy().getProxy(); + } + + /** + * Create a new proxy according to the settings in this factory. + *

Can be called repeatedly. Effect will vary if we've added + * or removed interfaces. Can add and remove interceptors. + *

Uses the given class loader (if necessary for proxy creation). + * @param classLoader the class loader to create the proxy with + * (or null for the low-level proxy facility's default) + * @return the proxy object + */ + public Object getProxy(ClassLoader classLoader) { + return createAopProxy().getProxy(classLoader); + } + + + /** + * Create a new proxy for the given interface and interceptor. + *

Convenience method for creating a proxy for a single interceptor, + * assuming that the interceptor handles all calls itself rather than + * delegating to a target, like in the case of remoting proxies. + * @param proxyInterface the interface that the proxy should implement + * @param interceptor the interceptor that the proxy should invoke + * @return the proxy object + * @see #ProxyFactory(Class, org.aopalliance.intercept.Interceptor) + */ + public static Object getProxy(Class proxyInterface, Interceptor interceptor) { + return new ProxyFactory(proxyInterface, interceptor).getProxy(); + } + + /** + * Create a proxy for the specified TargetSource, + * implementing the specified interface. + * @param proxyInterface the interface that the proxy should implement + * @param targetSource the TargetSource that the proxy should invoke + * @return the proxy object + * @see #ProxyFactory(Class, org.springframework.aop.TargetSource) + */ + public static Object getProxy(Class proxyInterface, TargetSource targetSource) { + return new ProxyFactory(proxyInterface, targetSource).getProxy(); + } + + /** + * Create a proxy for the specified TargetSource that extends + * the target class of the TargetSource. + * @param targetSource the TargetSource that the proxy should invoke + * @return the proxy object + */ + public static Object getProxy(TargetSource targetSource) { + if (targetSource.getTargetClass() == null) { + throw new IllegalArgumentException("Cannot create class proxy for TargetSource with null target class"); + } + ProxyFactory proxyFactory = new ProxyFactory(); + proxyFactory.setTargetSource(targetSource); + proxyFactory.setProxyTargetClass(true); + return proxyFactory.getProxy(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/ProxyFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/ProxyFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/ProxyFactoryBean.java 17 Aug 2012 15:11:24 -0000 1.1 @@ -0,0 +1,658 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.aopalliance.aop.Advice; +import org.aopalliance.intercept.Interceptor; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.aop.Advisor; +import org.springframework.aop.TargetSource; +import org.springframework.aop.framework.adapter.AdvisorAdapterRegistry; +import org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry; +import org.springframework.aop.framework.adapter.UnknownAdviceTypeException; +import org.springframework.aop.target.SingletonTargetSource; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.FactoryBeanNotInitializedException; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.core.OrderComparator; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; + +/** + * {@link org.springframework.beans.factory.FactoryBean} implementation that builds an + * AOP proxy based on beans in Spring {@link org.springframework.beans.factory.BeanFactory}. + * + *

{@link org.aopalliance.intercept.MethodInterceptor MethodInterceptors} and + * {@link org.springframework.aop.Advisor Advisors} are identified by a list of bean + * names in the current bean factory, specified through the "interceptorNames" property. + * The last entry in the list can be the name of a target bean or a + * {@link org.springframework.aop.TargetSource}; however, it is normally preferable + * to use the "targetName"/"target"/"targetSource" properties instead. + * + *

Global interceptors and advisors can be added at the factory level. The specified + * ones are expanded in an interceptor list where an "xxx*" entry is included in the + * list, matching the given prefix with the bean names (e.g. "global*" would match + * both "globalBean1" and "globalBean2", "*" all defined interceptors). The matching + * interceptors get applied according to their returned order value, if they implement + * the {@link org.springframework.core.Ordered} interface. + * + *

Creates a JDK proxy when proxy interfaces are given, and a CGLIB proxy for the + * actual target class if not. Note that the latter will only work if the target class + * does not have final methods, as a dynamic subclass will be created at runtime. + * + *

It's possible to cast a proxy obtained from this factory to {@link Advised}, + * or to obtain the ProxyFactoryBean reference and programmatically manipulate it. + * This won't work for existing prototype references, which are independent. However, + * it will work for prototypes subsequently obtained from the factory. Changes to + * interception will work immediately on singletons (including existing references). + * However, to change interfaces or target it's necessary to obtain a new instance + * from the factory. This means that singleton instances obtained from the factory + * do not have the same object identity. However, they do have the same interceptors + * and target, and changing any reference will change all objects. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see #setInterceptorNames + * @see #setProxyInterfaces + * @see org.aopalliance.intercept.MethodInterceptor + * @see org.springframework.aop.Advisor + * @see Advised + */ +public class ProxyFactoryBean extends ProxyCreatorSupport + implements FactoryBean, BeanClassLoaderAware, BeanFactoryAware { + + /** + * This suffix in a value in an interceptor list indicates to expand globals. + */ + public static final String GLOBAL_SUFFIX = "*"; + + + protected final Log logger = LogFactory.getLog(getClass()); + + private String[] interceptorNames; + + private String targetName; + + private boolean autodetectInterfaces = true; + + private boolean singleton = true; + + private AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance(); + + private boolean freezeProxy = false; + + private transient ClassLoader proxyClassLoader = ClassUtils.getDefaultClassLoader(); + + private transient boolean classLoaderConfigured = false; + + private transient BeanFactory beanFactory; + + /** Whether the advisor chain has already been initialized */ + private boolean advisorChainInitialized = false; + + /** If this is a singleton, the cached singleton proxy instance */ + private Object singletonInstance; + + + /** + * Set the names of the interfaces we're proxying. If no interface + * is given, a CGLIB for the actual class will be created. + *

This is essentially equivalent to the "setInterfaces" method, + * but mirrors TransactionProxyFactoryBean's "setProxyInterfaces". + * @see #setInterfaces + * @see AbstractSingletonProxyFactoryBean#setProxyInterfaces + */ + public void setProxyInterfaces(Class[] proxyInterfaces) throws ClassNotFoundException { + setInterfaces(proxyInterfaces); + } + + /** + * Set the list of Advice/Advisor bean names. This must always be set + * to use this factory bean in a bean factory. + *

The referenced beans should be of type Interceptor, Advisor or Advice + * The last entry in the list can be the name of any bean in the factory. + * If it's neither an Advice nor an Advisor, a new SingletonTargetSource + * is added to wrap it. Such a target bean cannot be used if the "target" + * or "targetSource" or "targetName" property is set, in which case the + * "interceptorNames" array must contain only Advice/Advisor bean names. + *

NOTE: Specifying a target bean as final name in the "interceptorNames" + * list is deprecated and will be removed in a future Spring version. + * Use the {@link #setTargetName "targetName"} property instead. + * @see org.aopalliance.intercept.MethodInterceptor + * @see org.springframework.aop.Advisor + * @see org.aopalliance.aop.Advice + * @see org.springframework.aop.target.SingletonTargetSource + */ + public void setInterceptorNames(String[] interceptorNames) { + this.interceptorNames = interceptorNames; + } + + /** + * Set the name of the target bean. This is an alternative to specifying + * the target name at the end of the "interceptorNames" array. + *

You can also specify a target object or a TargetSource object + * directly, via the "target"/"targetSource" property, respectively. + * @see #setInterceptorNames(String[]) + * @see #setTarget(Object) + * @see #setTargetSource(org.springframework.aop.TargetSource) + */ + public void setTargetName(String targetName) { + this.targetName = targetName; + } + + /** + * Set whether to autodetect proxy interfaces if none specified. + *

Default is "true". Turn this flag off to create a CGLIB + * proxy for the full target class if no interfaces specified. + * @see #setProxyTargetClass + */ + public void setAutodetectInterfaces(boolean autodetectInterfaces) { + this.autodetectInterfaces = autodetectInterfaces; + } + + /** + * Set the value of the singleton property. Governs whether this factory + * should always return the same proxy instance (which implies the same target) + * or whether it should return a new prototype instance, which implies that + * the target and interceptors may be new instances also, if they are obtained + * from prototype bean definitions. This allows for fine control of + * independence/uniqueness in the object graph. + */ + public void setSingleton(boolean singleton) { + this.singleton = singleton; + } + + /** + * Specify the AdvisorAdapterRegistry to use. + * Default is the global AdvisorAdapterRegistry. + * @see org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry + */ + public void setAdvisorAdapterRegistry(AdvisorAdapterRegistry advisorAdapterRegistry) { + this.advisorAdapterRegistry = advisorAdapterRegistry; + } + + public void setFrozen(boolean frozen) { + this.freezeProxy = frozen; + } + + /** + * Set the ClassLoader to generate the proxy class in. + *

Default is the bean ClassLoader, i.e. the ClassLoader used by the + * containing BeanFactory for loading all bean classes. This can be + * overridden here for specific proxies. + */ + public void setProxyClassLoader(ClassLoader classLoader) { + this.proxyClassLoader = classLoader; + this.classLoaderConfigured = (classLoader != null); + } + + public void setBeanClassLoader(ClassLoader classLoader) { + if (!this.classLoaderConfigured) { + this.proxyClassLoader = classLoader; + } + } + + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + checkInterceptorNames(); + } + + + /** + * Return a proxy. Invoked when clients obtain beans from this factory bean. + * Create an instance of the AOP proxy to be returned by this factory. + * The instance will be cached for a singleton, and create on each call to + * getObject() for a proxy. + * @return a fresh AOP proxy reflecting the current state of this factory + */ + public Object getObject() throws BeansException { + initializeAdvisorChain(); + if (isSingleton()) { + return getSingletonInstance(); + } + else { + if (this.targetName == null) { + logger.warn("Using non-singleton proxies with singleton targets is often undesirable. " + + "Enable prototype proxies by setting the 'targetName' property."); + } + return newPrototypeInstance(); + } + } + + /** + * Return the type of the proxy. Will check the singleton instance if + * already created, else fall back to the proxy interface (in case of just + * a single one), the target bean type, or the TargetSource's target class. + * @see org.springframework.aop.TargetSource#getTargetClass + */ + public Class getObjectType() { + synchronized (this) { + if (this.singletonInstance != null) { + return this.singletonInstance.getClass(); + } + } + Class[] ifcs = getProxiedInterfaces(); + if (ifcs.length == 1) { + return ifcs[0]; + } + else if (ifcs.length > 1) { + return createCompositeInterface(ifcs); + } + else if (this.targetName != null && this.beanFactory != null) { + return this.beanFactory.getType(this.targetName); + } + else { + return getTargetClass(); + } + } + + public boolean isSingleton() { + return this.singleton; + } + + + /** + * Create a composite interface Class for the given interfaces, + * implementing the given interfaces in one single Class. + *

The default implementation builds a JDK proxy class for the + * given interfaces. + * @param interfaces the interfaces to merge + * @return the merged interface as Class + * @see java.lang.reflect.Proxy#getProxyClass + */ + protected Class createCompositeInterface(Class[] interfaces) { + return ClassUtils.createCompositeInterface(interfaces, this.proxyClassLoader); + } + + /** + * Return the singleton instance of this class's proxy object, + * lazily creating it if it hasn't been created already. + * @return the shared singleton proxy + */ + private synchronized Object getSingletonInstance() { + if (this.singletonInstance == null) { + this.targetSource = freshTargetSource(); + if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) { + // Rely on AOP infrastructure to tell us what interfaces to proxy. + Class targetClass = getTargetClass(); + if (targetClass == null) { + throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy"); + } + setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader)); + } + // Initialize the shared singleton instance. + super.setFrozen(this.freezeProxy); + this.singletonInstance = getProxy(createAopProxy()); + } + return this.singletonInstance; + } + + /** + * Create a new prototype instance of this class's created proxy object, + * backed by an independent AdvisedSupport configuration. + * @return a totally independent proxy, whose advice we may manipulate in isolation + */ + private synchronized Object newPrototypeInstance() { + // In the case of a prototype, we need to give the proxy + // an independent instance of the configuration. + // In this case, no proxy will have an instance of this object's configuration, + // but will have an independent copy. + if (logger.isTraceEnabled()) { + logger.trace("Creating copy of prototype ProxyFactoryBean config: " + this); + } + + ProxyCreatorSupport copy = new ProxyCreatorSupport(getAopProxyFactory()); + // The copy needs a fresh advisor chain, and a fresh TargetSource. + TargetSource targetSource = freshTargetSource(); + copy.copyConfigurationFrom(this, targetSource, freshAdvisorChain()); + if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) { + // Rely on AOP infrastructure to tell us what interfaces to proxy. + copy.setInterfaces( + ClassUtils.getAllInterfacesForClass(targetSource.getTargetClass(), this.proxyClassLoader)); + } + copy.setFrozen(this.freezeProxy); + + if (logger.isTraceEnabled()) { + logger.trace("Using ProxyCreatorSupport copy: " + copy); + } + return getProxy(copy.createAopProxy()); + } + + /** + * Return the proxy object to expose. + *

The default implementation uses a getProxy call with + * the factory's bean class loader. Can be overridden to specify a + * custom class loader. + * @param aopProxy the prepared AopProxy instance to get the proxy from + * @return the proxy object to expose + * @see AopProxy#getProxy(ClassLoader) + */ + protected Object getProxy(AopProxy aopProxy) { + return aopProxy.getProxy(this.proxyClassLoader); + } + + /** + * Check the interceptorNames list whether it contains a target name as final element. + * If found, remove the final name from the list and set it as targetName. + */ + private void checkInterceptorNames() { + if (!ObjectUtils.isEmpty(this.interceptorNames)) { + String finalName = this.interceptorNames[this.interceptorNames.length - 1]; + if (this.targetName == null && this.targetSource == EMPTY_TARGET_SOURCE) { + // The last name in the chain may be an Advisor/Advice or a target/TargetSource. + // Unfortunately we don't know; we must look at type of the bean. + if (!finalName.endsWith(GLOBAL_SUFFIX) && !isNamedBeanAnAdvisorOrAdvice(finalName)) { + // The target isn't an interceptor. + this.targetName = finalName; + if (logger.isDebugEnabled()) { + logger.debug("Bean with name '" + finalName + "' concluding interceptor chain " + + "is not an advisor class: treating it as a target or TargetSource"); + } + String[] newNames = new String[this.interceptorNames.length - 1]; + System.arraycopy(this.interceptorNames, 0, newNames, 0, newNames.length); + this.interceptorNames = newNames; + } + } + } + } + + /** + * Look at bean factory metadata to work out whether this bean name, + * which concludes the interceptorNames list, is an Advisor or Advice, + * or may be a target. + * @param beanName bean name to check + * @return true if it's an Advisor or Advice + */ + private boolean isNamedBeanAnAdvisorOrAdvice(String beanName) { + Class namedBeanClass = this.beanFactory.getType(beanName); + if (namedBeanClass != null) { + return (Advisor.class.isAssignableFrom(namedBeanClass) || Advice.class.isAssignableFrom(namedBeanClass)); + } + // Treat it as an target bean if we can't tell. + if (logger.isDebugEnabled()) { + logger.debug("Could not determine type of bean with name '" + beanName + + "' - assuming it is neither an Advisor nor an Advice"); + } + return false; + } + + /** + * Create the advisor (interceptor) chain. Aadvisors that are sourced + * from a BeanFactory will be refreshed each time a new prototype instance + * is added. Interceptors added programmatically through the factory API + * are unaffected by such changes. + */ + private synchronized void initializeAdvisorChain() throws AopConfigException, BeansException { + if (this.advisorChainInitialized) { + return; + } + + if (!ObjectUtils.isEmpty(this.interceptorNames)) { + if (this.beanFactory == null) { + throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) " + + "- cannot resolve interceptor names " + Arrays.asList(this.interceptorNames)); + } + + // Globals can't be last unless we specified a targetSource using the property... + if (this.interceptorNames[this.interceptorNames.length - 1].endsWith(GLOBAL_SUFFIX) && + this.targetName == null && this.targetSource == EMPTY_TARGET_SOURCE) { + throw new AopConfigException("Target required after globals"); + } + + // Materialize interceptor chain from bean names. + for (int i = 0; i < this.interceptorNames.length; i++) { + String name = this.interceptorNames[i]; + if (logger.isTraceEnabled()) { + logger.trace("Configuring advisor or advice '" + name + "'"); + } + + if (name.endsWith(GLOBAL_SUFFIX)) { + if (!(this.beanFactory instanceof ListableBeanFactory)) { + throw new AopConfigException( + "Can only use global advisors or interceptors with a ListableBeanFactory"); + } + addGlobalAdvisor((ListableBeanFactory) this.beanFactory, + name.substring(0, name.length() - GLOBAL_SUFFIX.length())); + } + + else { + // If we get here, we need to add a named interceptor. + // We must check if it's a singleton or prototype. + Object advice = null; + if (this.singleton || this.beanFactory.isSingleton(this.interceptorNames[i])) { + // Add the real Advisor/Advice to the chain. + advice = this.beanFactory.getBean(this.interceptorNames[i]); + } + else { + // It's a prototype Advice or Advisor: replace with a prototype. + // Avoid unnecessary creation of prototype bean just for advisor chain initialization. + advice = new PrototypePlaceholderAdvisor(this.interceptorNames[i]); + } + addAdvisorOnChainCreation(advice, this.interceptorNames[i]); + } + } + } + + this.advisorChainInitialized = true; + } + + + /** + * Return an independent advisor chain. + * We need to do this every time a new prototype instance is returned, + * to return distinct instances of prototype Advisors and Advices. + */ + private List freshAdvisorChain() { + Advisor[] advisors = getAdvisors(); + List freshAdvisors = new ArrayList(advisors.length); + + for (int i = 0; i < advisors.length; i++) { + if (advisors[i] instanceof PrototypePlaceholderAdvisor) { + PrototypePlaceholderAdvisor pa = (PrototypePlaceholderAdvisor) advisors[i]; + if (logger.isDebugEnabled()) { + logger.debug("Refreshing bean named '" + pa.getBeanName() + "'"); + } + // Replace the placeholder with a fresh prototype instance resulting + // from a getBean() lookup + if (this.beanFactory == null) { + throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) " + + "- cannot resolve prototype advisor '" + pa.getBeanName() + "'"); + } + Object bean = this.beanFactory.getBean(pa.getBeanName()); + Advisor refreshedAdvisor = namedBeanToAdvisor(bean); + freshAdvisors.add(refreshedAdvisor); + } + else { + // Add the shared instance. + freshAdvisors.add(advisors[i]); + } + } + return freshAdvisors; + } + + /** + * Add all global interceptors and pointcuts. + */ + private void addGlobalAdvisor(ListableBeanFactory beanFactory, String prefix) { + String[] globalAdvisorNames = + BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, Advisor.class); + String[] globalInterceptorNames = + BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, Interceptor.class); + List beans = new ArrayList(globalAdvisorNames.length + globalInterceptorNames.length); + Map names = new HashMap(); + for (int i = 0; i < globalAdvisorNames.length; i++) { + String name = globalAdvisorNames[i]; + Object bean = beanFactory.getBean(name); + beans.add(bean); + names.put(bean, name); + } + for (int i = 0; i < globalInterceptorNames.length; i++) { + String name = globalInterceptorNames[i]; + Object bean = beanFactory.getBean(name); + beans.add(bean); + names.put(bean, name); + } + Collections.sort(beans, new OrderComparator()); + for (Iterator it = beans.iterator(); it.hasNext();) { + Object bean = it.next(); + String name = (String) names.get(bean); + if (name.startsWith(prefix)) { + addAdvisorOnChainCreation(bean, name); + } + } + } + + /** + * Invoked when advice chain is created. + *

Add the given advice, advisor or object to the interceptor list. + * Because of these three possibilities, we can't type the signature + * more strongly. + * @param next advice, advisor or target object + * @param name bean name from which we obtained this object in our owning + * bean factory + */ + private void addAdvisorOnChainCreation(Object next, String name) { + // We need to convert to an Advisor if necessary so that our source reference + // matches what we find from superclass interceptors. + Advisor advisor = namedBeanToAdvisor(next); + if (logger.isTraceEnabled()) { + logger.trace("Adding advisor with name '" + name + "'"); + } + addAdvisor((Advisor) advisor); + } + + /** + * Return a TargetSource to use when creating a proxy. If the target was not + * specified at the end of the interceptorNames list, the TargetSource will be + * this class's TargetSource member. Otherwise, we get the target bean and wrap + * it in a TargetSource if necessary. + */ + private TargetSource freshTargetSource() { + if (this.targetName == null) { + if (logger.isTraceEnabled()) { + logger.trace("Not refreshing target: Bean name not specified in 'interceptorNames'."); + } + return this.targetSource; + } + else { + if (this.beanFactory == null) { + throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) " + + "- cannot resolve target with name '" + this.targetName + "'"); + } + if (logger.isDebugEnabled()) { + logger.debug("Refreshing target with name '" + this.targetName + "'"); + } + Object target = this.beanFactory.getBean(this.targetName); + return (target instanceof TargetSource ? (TargetSource) target : new SingletonTargetSource(target)); + } + } + + /** + * Convert the following object sourced from calling getBean() on a name in the + * interceptorNames array to an Advisor or TargetSource. + */ + private Advisor namedBeanToAdvisor(Object next) { + try { + return this.advisorAdapterRegistry.wrap(next); + } + catch (UnknownAdviceTypeException ex) { + // We expected this to be an Advisor or Advice, + // but it wasn't. This is a configuration error. + throw new AopConfigException("Unknown advisor type " + next.getClass() + + "; Can only include Advisor or Advice type beans in interceptorNames chain except for last entry," + + "which may also be target or TargetSource", ex); + } + } + + /** + * Blow away and recache singleton on an advice change. + */ + protected void adviceChanged() { + super.adviceChanged(); + if (this.singleton) { + logger.debug("Advice has changed; recaching singleton instance"); + synchronized (this) { + this.singletonInstance = null; + } + } + } + + + //--------------------------------------------------------------------- + // Serialization support + //--------------------------------------------------------------------- + + private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { + // Rely on default serialization; just initialize state after deserialization. + ois.defaultReadObject(); + + // Initialize transient fields. + this.proxyClassLoader = ClassUtils.getDefaultClassLoader(); + } + + + /** + * Used in the interceptor chain where we need to replace a bean with a prototype + * on creating a proxy. + */ + private static class PrototypePlaceholderAdvisor implements Advisor, Serializable { + + private final String beanName; + + private final String message; + + public PrototypePlaceholderAdvisor(String beanName) { + this.beanName = beanName; + this.message = "Placeholder for prototype Advisor/Advice with bean name '" + beanName + "'"; + } + + public String getBeanName() { + return beanName; + } + + public Advice getAdvice() { + throw new UnsupportedOperationException("Cannot invoke methods: " + this.message); + } + + public boolean isPerInstance() { + throw new UnsupportedOperationException("Cannot invoke methods: " + this.message); + } + + public String toString() { + return this.message; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/ReflectiveMethodInvocation.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/ReflectiveMethodInvocation.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/ReflectiveMethodInvocation.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,278 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.aop.ProxyMethodInvocation; +import org.springframework.aop.support.AopUtils; + +/** + * Spring's implementation of the AOP Alliance + * {@link org.aopalliance.intercept.MethodInvocation} interface, + * implementing the extended + * {@link org.springframework.aop.ProxyMethodInvocation} interface. + * + *

Invokes the target object using reflection. Subclasses can override the + * {@link #invokeJoinpoint()} method to change this behavior, so this is also + * a useful base class for more specialized MethodInvocation implementations. + * + *

It is possible to clone an invocation, to invoke {@link #proceed()} + * repeatedly (once per clone), using the {@link #invocableClone()} method. + * It is also possible to attach custom attributes to the invocation, + * using the {@link #setUserAttribute} / {@link #getUserAttribute} methods. + * + *

NOTE: This class is considered internal and should not be + * directly accessed. The sole reason for it being public is compatibility + * with existing framework integrations (e.g. Pitchfork). For any other + * purposes, use the {@link ProxyMethodInvocation} interface instead. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Adrian Colyer + * @see #invokeJoinpoint + * @see #proceed + * @see #invocableClone + * @see #setUserAttribute + * @see #getUserAttribute + */ +public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable { + + protected final Object proxy; + + protected final Object target; + + protected final Method method; + + protected Object[] arguments; + + private final Class targetClass; + + /** + * Lazily initialized map of user-specific attributes for this invocation. + */ + private Map userAttributes; + + /** + * List of MethodInterceptor and InterceptorAndDynamicMethodMatcher + * that need dynamic checks. + */ + protected final List interceptorsAndDynamicMethodMatchers; + + /** + * Index from 0 of the current interceptor we're invoking. + * -1 until we invoke: then the current interceptor. + */ + private int currentInterceptorIndex = -1; + + + /** + * Construct a new ReflectiveMethodInvocation with the given arguments. + * @param proxy the proxy object that the invocation was made on + * @param target the target object to invoke + * @param method the method to invoke + * @param arguments the arguments to invoke the method with + * @param targetClass the target class, for MethodMatcher invocations + * @param interceptorsAndDynamicMethodMatchers interceptors that should be applied, + * along with any InterceptorAndDynamicMethodMatchers that need evaluation at runtime. + * MethodMatchers included in this struct must already have been found to have matched + * as far as was possibly statically. Passing an array might be about 10% faster, + * but would complicate the code. And it would work only for static pointcuts. + */ + protected ReflectiveMethodInvocation( + Object proxy, Object target, Method method, Object[] arguments, + Class targetClass, List interceptorsAndDynamicMethodMatchers) { + + this.proxy = proxy; + this.target = target; + this.targetClass = targetClass; + this.method = method; + this.arguments = arguments; + this.interceptorsAndDynamicMethodMatchers = interceptorsAndDynamicMethodMatchers; + } + + + public final Object getProxy() { + return this.proxy; + } + + public final Object getThis() { + return this.target; + } + + public final AccessibleObject getStaticPart() { + return this.method; + } + + /** + * Return the method invoked on the proxied interface. + * May or may not correspond with a method invoked on an underlying + * implementation of that interface. + */ + public final Method getMethod() { + return this.method; + } + + public final Object[] getArguments() { + return (this.arguments != null ? this.arguments : new Object[0]); + } + + public void setArguments(Object[] arguments) { + this.arguments = arguments; + } + + + public Object proceed() throws Throwable { + // We start with an index of -1 and increment early. + if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) { + return invokeJoinpoint(); + } + + Object interceptorOrInterceptionAdvice = + this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex); + if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) { + // Evaluate dynamic method matcher here: static part will already have + // been evaluated and found to match. + InterceptorAndDynamicMethodMatcher dm = + (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice; + if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) { + return dm.interceptor.invoke(this); + } + else { + // Dynamic matching failed. + // Skip this interceptor and invoke the next in the chain. + return proceed(); + } + } + else { + // It's an interceptor, so we just invoke it: The pointcut will have + // been evaluated statically before this object was constructed. + return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this); + } + } + + /** + * Invoke the joinpoint using reflection. + * Subclasses can override this to use custom invocation. + * @return the return value of the joinpoint + * @throws Throwable if invoking the joinpoint resulted in an exception + */ + protected Object invokeJoinpoint() throws Throwable { + return AopUtils.invokeJoinpointUsingReflection(this.target, this.method, this.arguments); + } + + + /** + * This implementation returns a shallow copy of this invocation object, + * including an independent copy of the original arguments array. + *

We want a shallow copy in this case: We want to use the same interceptor + * chain and other object references, but we want an independent value for the + * current interceptor index. + * @see java.lang.Object#clone() + */ + public MethodInvocation invocableClone() { + Object[] cloneArguments = null; + if (this.arguments != null) { + // Build an independent copy of the arguments array. + cloneArguments = new Object[this.arguments.length]; + System.arraycopy(this.arguments, 0, cloneArguments, 0, this.arguments.length); + } + return invocableClone(cloneArguments); + } + + /** + * This implementation returns a shallow copy of this invocation object, + * using the given arguments array for the clone. + *

We want a shallow copy in this case: We want to use the same interceptor + * chain and other object references, but we want an independent value for the + * current interceptor index. + * @see java.lang.Object#clone() + */ + public MethodInvocation invocableClone(Object[] arguments) { + // Force initialization of the user attributes Map, + // for having a shared Map reference in the clone. + if (this.userAttributes == null) { + this.userAttributes = new HashMap(); + } + + // Create the MethodInvocation clone. + try { + ReflectiveMethodInvocation clone = (ReflectiveMethodInvocation) clone(); + clone.arguments = arguments; + return clone; + } + catch (CloneNotSupportedException ex) { + throw new IllegalStateException( + "Should be able to clone object of type [" + getClass() + "]: " + ex); + } + } + + + public void setUserAttribute(String key, Object value) { + if (value != null) { + if (this.userAttributes == null) { + this.userAttributes = new HashMap(); + } + this.userAttributes.put(key, value); + } + else { + if (this.userAttributes != null) { + this.userAttributes.remove(key); + } + } + } + + public Object getUserAttribute(String key) { + return (this.userAttributes != null ? this.userAttributes.get(key) : null); + } + + /** + * Return user attributes associated with this invocation. + * This method provides an invocation-bound alternative to a ThreadLocal. + *

This map is initialized lazily and is not used in the AOP framework itself. + * @return any user attributes associated with this invocation + * (never null) + */ + public Map getUserAttributes() { + if (this.userAttributes == null) { + this.userAttributes = new HashMap(); + } + return this.userAttributes; + } + + + public String toString() { + // Don't do toString on target, it may be proxied. + StringBuffer sb = new StringBuffer("ReflectiveMethodInvocation: "); + sb.append(this.method).append("; "); + if (this.target == null) { + sb.append("target is null"); + } + else { + sb.append("target is of class [").append(this.target.getClass().getName()).append(']'); + } + return sb.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/package.html 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,18 @@ + + + +Package containing Spring's basic AOP infrastructure, compliant with the +AOP Alliance interfaces. + +

Spring AOP supports proxying interfaces or classes, introductions, and offers +static and dynamic pointcuts. + +

Any Spring AOP proxy can be cast to the ProxyConfig AOP configuration interface +in this package to add or remove interceptors. + +

The ProxyFactoryBean is a convenient way to create AOP proxies in a BeanFactory +or ApplicationContext. However, proxies can be created programmatically using the +ProxyFactory class. + + + Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/AdvisorAdapter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/AdvisorAdapter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/AdvisorAdapter.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.adapter; + +import org.aopalliance.aop.Advice; +import org.aopalliance.intercept.MethodInterceptor; + +import org.springframework.aop.Advisor; + +/** + * Interface allowing extension to the Spring AOP framework to allow + * handling of new Advisors and Advice types. + * + *

Implementing objects can create AOP Alliance Interceptors from + * custom advice types, enabling these advice types to be used + * in the Spring AOP framework, which uses interception under the covers. + * + *

There is no need for most Spring users to implement this interface; + * do so only if you need to introduce more Advisor or Advice types to Spring. + * + * @author Rod Johnson + */ +public interface AdvisorAdapter { + + /** + * Does this adapter understand this advice object? Is it valid to + * invoke the getInterceptors method with an Advisor that + * contains this advice as an argument? + * @param advice an Advice such as a BeforeAdvice + * @return whether this adapter understands the given advice object + * @see #getInterceptor(org.springframework.aop.Advisor) + * @see org.springframework.aop.BeforeAdvice + */ + boolean supportsAdvice(Advice advice); + + /** + * Return an AOP Alliance MethodInterceptor exposing the behavior of + * the given advice to an interception-based AOP framework. + *

Don't worry about any Pointcut contained in the Advisor; + * the AOP framework will take care of checking the pointcut. + * @param advisor the Advisor. The supportsAdvice() method must have + * returned true on this object + * @return an AOP Alliance interceptor for this Advisor. There's + * no need to cache instances for efficiency, as the AOP framework + * caches advice chains. + */ + MethodInterceptor getInterceptor(Advisor advisor); + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationManager.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationManager.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationManager.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.adapter; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanPostProcessor; + +/** + * BeanPostProcessor that registers {@link AdvisorAdapter} beans in the BeanFactory with + * an {@link AdvisorAdapterRegistry} (by default the {@link GlobalAdvisorAdapterRegistry}). + * + *

The only requirement for it to work is that it needs to be defined + * in application context along with "non-native" Spring AdvisorAdapters + * that need to be "recognized" by Spring's AOP framework. + * + * @author Dmitriy Kopylenko + * @author Juergen Hoeller + * @since 27.02.2004 + * @see #setAdvisorAdapterRegistry + * @see AdvisorAdapter + */ +public class AdvisorAdapterRegistrationManager implements BeanPostProcessor { + + private AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance(); + + + /** + * Specify the AdvisorAdapterRegistry to register AdvisorAdapter beans with. + * Default is the global AdvisorAdapterRegistry. + * @see GlobalAdvisorAdapterRegistry + */ + public void setAdvisorAdapterRegistry(AdvisorAdapterRegistry advisorAdapterRegistry) { + this.advisorAdapterRegistry = advisorAdapterRegistry; + } + + + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + return bean; + } + + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + if (bean instanceof AdvisorAdapter){ + this.advisorAdapterRegistry.registerAdvisorAdapter((AdvisorAdapter) bean); + } + return bean; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/AdvisorAdapterRegistry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/AdvisorAdapterRegistry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/AdvisorAdapterRegistry.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.adapter; + +import org.aopalliance.intercept.MethodInterceptor; + +import org.springframework.aop.Advisor; + +/** + * Interface for registries of Advisor adapters. + * + *

This is an SPI interface, not to be implemented by any Spring user. + * + * @author Rod Johnson + * @author Rob Harrop + */ +public interface AdvisorAdapterRegistry { + + /** + * Return an Advisor wrapping the given advice. + *

Should by default at least support + * {@link org.aopalliance.intercept.MethodInterceptor}, + * {@link org.springframework.aop.MethodBeforeAdvice}, + * {@link org.springframework.aop.AfterReturningAdvice}, + * {@link org.springframework.aop.ThrowsAdvice}. + * @param advice object that should be an advice + * @return an Advisor wrapping the given advice. Never returns null. + * If the advice parameter is an Advisor, return it. + * @throws UnknownAdviceTypeException if no registered advisor adapter + * can wrap the supposed advice + */ + Advisor wrap(Object advice) throws UnknownAdviceTypeException; + + /** + * Return an array of AOP Alliance MethodInterceptors to allow use of the + * given Advisor in an interception-based framework. + *

Don't worry about the pointcut associated with the Advisor, + * if it's a PointcutAdvisor: just return an interceptor. + * @param advisor Advisor to find an interceptor for + * @return an array of MethodInterceptors to expose this Advisor's behavior + * @throws UnknownAdviceTypeException if the Advisor type is + * not understood by any registered AdvisorAdapter. + */ + MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException; + + /** + * Register the given AdvisorAdapter. Note that it is not necessary to register + * adapters for an AOP Alliance Interceptors or Spring Advices: these must be + * automatically recognized by an AdvisorAdapterRegistry implementation. + * @param adapter AdvisorAdapter that understands a particular Advisor + * or Advice types + */ + void registerAdvisorAdapter(AdvisorAdapter adapter); + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/AfterReturningAdviceAdapter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/AfterReturningAdviceAdapter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/AfterReturningAdviceAdapter.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.adapter; + +import java.io.Serializable; + +import org.aopalliance.aop.Advice; +import org.aopalliance.intercept.MethodInterceptor; + +import org.springframework.aop.Advisor; +import org.springframework.aop.AfterReturningAdvice; + +/** + * Adapter to enable {@link org.springframework.aop.AfterReturningAdvice} + * to be used in the Spring AOP framework. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +class AfterReturningAdviceAdapter implements AdvisorAdapter, Serializable { + + public boolean supportsAdvice(Advice advice) { + return (advice instanceof AfterReturningAdvice); + } + + public MethodInterceptor getInterceptor(Advisor advisor) { + AfterReturningAdvice advice = (AfterReturningAdvice) advisor.getAdvice(); + return new AfterReturningAdviceInterceptor(advice); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/AfterReturningAdviceInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/AfterReturningAdviceInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/AfterReturningAdviceInterceptor.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.adapter; + +import java.io.Serializable; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.aop.AfterAdvice; +import org.springframework.aop.AfterReturningAdvice; +import org.springframework.util.Assert; + +/** + * Interceptor to wrap am {@link org.springframework.aop.AfterReturningAdvice}. + * Used internally by the AOP framework; application developers should not need + * to use this class directly. + * + * @author Rod Johnson + */ +public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable { + + private final AfterReturningAdvice advice; + + + /** + * Create a new AfterReturningAdviceInterceptor for the given advice. + * @param advice the AfterReturningAdvice to wrap + */ + public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) { + Assert.notNull(advice, "Advice must not be null"); + this.advice = advice; + } + + public Object invoke(MethodInvocation mi) throws Throwable { + Object retVal = mi.proceed(); + this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis()); + return retVal; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/DefaultAdvisorAdapterRegistry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/DefaultAdvisorAdapterRegistry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/DefaultAdvisorAdapterRegistry.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,99 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.adapter; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.aopalliance.aop.Advice; +import org.aopalliance.intercept.MethodInterceptor; + +import org.springframework.aop.Advisor; +import org.springframework.aop.support.DefaultPointcutAdvisor; + +/** + * Default implementation of the {@link AdvisorAdapterRegistry} interface. + * Supports {@link org.aopalliance.intercept.MethodInterceptor}, + * {@link org.springframework.aop.MethodBeforeAdvice}, + * {@link org.springframework.aop.AfterReturningAdvice}, + * {@link org.springframework.aop.ThrowsAdvice}. + * + * @author Rod Johnson + * @author Rob Harrop + * @author Juergen Hoeller + */ +public class DefaultAdvisorAdapterRegistry implements AdvisorAdapterRegistry, Serializable { + + private final List adapters = new ArrayList(3); + + + /** + * Create a new DefaultAdvisorAdapterRegistry, registering well-known adapters. + */ + public DefaultAdvisorAdapterRegistry() { + registerAdvisorAdapter(new MethodBeforeAdviceAdapter()); + registerAdvisorAdapter(new AfterReturningAdviceAdapter()); + registerAdvisorAdapter(new ThrowsAdviceAdapter()); + } + + + public Advisor wrap(Object adviceObject) throws UnknownAdviceTypeException { + if (adviceObject instanceof Advisor) { + return (Advisor) adviceObject; + } + if (!(adviceObject instanceof Advice)) { + throw new UnknownAdviceTypeException(adviceObject); + } + Advice advice = (Advice) adviceObject; + if (advice instanceof MethodInterceptor) { + // So well-known it doesn't even need an adapter. + return new DefaultPointcutAdvisor(advice); + } + for (int i = 0; i < this.adapters.size(); i++) { + // Check that it is supported. + AdvisorAdapter adapter = (AdvisorAdapter) this.adapters.get(i); + if (adapter.supportsAdvice(advice)) { + return new DefaultPointcutAdvisor(advice); + } + } + throw new UnknownAdviceTypeException(advice); + } + + public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException { + List interceptors = new ArrayList(3); + Advice advice = advisor.getAdvice(); + if (advice instanceof MethodInterceptor) { + interceptors.add(advice); + } + for (int i = 0; i < this.adapters.size(); i++) { + AdvisorAdapter adapter = (AdvisorAdapter) this.adapters.get(i); + if (adapter.supportsAdvice(advice)) { + interceptors.add(adapter.getInterceptor(advisor)); + } + } + if (interceptors.isEmpty()) { + throw new UnknownAdviceTypeException(advisor.getAdvice()); + } + return (MethodInterceptor[]) interceptors.toArray(new MethodInterceptor[interceptors.size()]); + } + + public void registerAdvisorAdapter(AdvisorAdapter adapter) { + this.adapters.add(adapter); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/GlobalAdvisorAdapterRegistry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/GlobalAdvisorAdapterRegistry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/GlobalAdvisorAdapterRegistry.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.adapter; + +/** + * Singleton to publish a shared DefaultAdvisorAdapterRegistry instance. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see DefaultAdvisorAdapterRegistry + */ +public abstract class GlobalAdvisorAdapterRegistry { + + /** + * Keep track of a single instance so we can return it to classes that request it. + */ + private static final AdvisorAdapterRegistry instance = new DefaultAdvisorAdapterRegistry(); + + /** + * Return the singleton DefaultAdvisorAdapterRegistry instance. + */ + public static AdvisorAdapterRegistry getInstance() { + return instance; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/MethodBeforeAdviceAdapter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/MethodBeforeAdviceAdapter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/MethodBeforeAdviceAdapter.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.adapter; + +import java.io.Serializable; + +import org.aopalliance.aop.Advice; +import org.aopalliance.intercept.MethodInterceptor; + +import org.springframework.aop.Advisor; +import org.springframework.aop.MethodBeforeAdvice; + +/** + * Adapter to enable {@link org.springframework.aop.MethodBeforeAdvice} + * to be used in the Spring AOP framework. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable { + + public boolean supportsAdvice(Advice advice) { + return (advice instanceof MethodBeforeAdvice); + } + + public MethodInterceptor getInterceptor(Advisor advisor) { + MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice(); + return new MethodBeforeAdviceInterceptor(advice); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/MethodBeforeAdviceInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/MethodBeforeAdviceInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/MethodBeforeAdviceInterceptor.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.adapter; + +import java.io.Serializable; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.aop.MethodBeforeAdvice; +import org.springframework.util.Assert; + +/** + * Interceptor to wrap am {@link org.springframework.aop.MethodBeforeAdvice}. + * Used internally by the AOP framework; application developers should not need + * to use this class directly. + * + * @author Rod Johnson + */ +public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable { + + private MethodBeforeAdvice advice; + + + /** + * Create a new MethodBeforeAdviceInterceptor for the given advice. + * @param advice the MethodBeforeAdvice to wrap + */ + public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) { + Assert.notNull(advice, "Advice must not be null"); + this.advice = advice; + } + + public Object invoke(MethodInvocation mi) throws Throwable { + this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() ); + return mi.proceed(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/ThrowsAdviceAdapter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/ThrowsAdviceAdapter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/ThrowsAdviceAdapter.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.adapter; + +import java.io.Serializable; + +import org.aopalliance.aop.Advice; +import org.aopalliance.intercept.MethodInterceptor; + +import org.springframework.aop.Advisor; +import org.springframework.aop.ThrowsAdvice; + +/** + * Adapter to enable {@link org.springframework.aop.MethodBeforeAdvice} + * to be used in the Spring AOP framework. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +class ThrowsAdviceAdapter implements AdvisorAdapter, Serializable { + + public boolean supportsAdvice(Advice advice) { + return (advice instanceof ThrowsAdvice); + } + + public MethodInterceptor getInterceptor(Advisor advisor) { + return new ThrowsAdviceInterceptor(advisor.getAdvice()); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptor.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,153 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.adapter; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.aop.AfterAdvice; +import org.springframework.util.Assert; + +/** + * Interceptor to wrap an after-throwing advice. + * + *

The signatures on handler methods on the ThrowsAdvice + * implementation method argument must be of the form:
+ * + * void afterThrowing([Method, args, target], ThrowableSubclass); + * + *

Only the last argument is required. + * + *

Some examples of valid methods would be: + * + *

public void afterThrowing(Exception ex)
+ *
public void afterThrowing(RemoteException)
+ *
public void afterThrowing(Method method, Object[] args, Object target, Exception ex)
+ *
public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)
+ * + *

This is a framework class that need not be used directly by Spring users. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice { + + private static final String AFTER_THROWING = "afterThrowing"; + + private static final Log logger = LogFactory.getLog(ThrowsAdviceInterceptor.class); + + + private final Object throwsAdvice; + + /** Methods on throws advice, keyed by exception class */ + private final Map exceptionHandlerMap = new HashMap(); + + + /** + * Create a new ThrowsAdviceInterceptor for the given ThrowsAdvice. + * @param throwsAdvice the advice object that defines the exception + * handler methods (usually a {@link org.springframework.aop.ThrowsAdvice} + * implementation) + */ + public ThrowsAdviceInterceptor(Object throwsAdvice) { + Assert.notNull(throwsAdvice, "Advice must not be null"); + this.throwsAdvice = throwsAdvice; + + Method[] methods = throwsAdvice.getClass().getMethods(); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + if (method.getName().equals(AFTER_THROWING) && + //m.getReturnType() == null && + (method.getParameterTypes().length == 1 || method.getParameterTypes().length == 4) && + Throwable.class.isAssignableFrom(method.getParameterTypes()[method.getParameterTypes().length - 1]) + ) { + // Have an exception handler + this.exceptionHandlerMap.put(method.getParameterTypes()[method.getParameterTypes().length - 1], method); + if (logger.isDebugEnabled()) { + logger.debug("Found exception handler method: " + method); + } + } + } + + if (this.exceptionHandlerMap.isEmpty()) { + throw new IllegalArgumentException( + "At least one handler method must be found in class [" + throwsAdvice.getClass() + "]"); + } + } + + public int getHandlerMethodCount() { + return this.exceptionHandlerMap.size(); + } + + /** + * Determine the exception handle method. Can return null if not found. + * @param exception the exception thrown + * @return a handler for the given exception type + */ + private Method getExceptionHandler(Throwable exception) { + Class exceptionClass = exception.getClass(); + if (logger.isTraceEnabled()) { + logger.trace("Trying to find handler for exception of type [" + exceptionClass.getName() + "]"); + } + Method handler = (Method) this.exceptionHandlerMap.get(exceptionClass); + while (handler == null && !exceptionClass.equals(Throwable.class)) { + exceptionClass = exceptionClass.getSuperclass(); + handler = (Method) this.exceptionHandlerMap.get(exceptionClass); + } + if (handler != null && logger.isDebugEnabled()) { + logger.debug("Found handler for exception of type [" + exceptionClass.getName() + "]: " + handler); + } + return handler; + } + + public Object invoke(MethodInvocation mi) throws Throwable { + try { + return mi.proceed(); + } + catch (Throwable ex) { + Method handlerMethod = getExceptionHandler(ex); + if (handlerMethod != null) { + invokeHandlerMethod(mi, ex, handlerMethod); + } + throw ex; + } + } + + private void invokeHandlerMethod(MethodInvocation mi, Throwable ex, Method method) throws Throwable { + Object[] handlerArgs; + if (method.getParameterTypes().length == 1) { + handlerArgs = new Object[] { ex }; + } + else { + handlerArgs = new Object[] {mi.getMethod(), mi.getArguments(), mi.getThis(), ex}; + } + try { + method.invoke(this.throwsAdvice, handlerArgs); + } + catch (InvocationTargetException targetEx) { + throw targetEx.getTargetException(); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/UnknownAdviceTypeException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/UnknownAdviceTypeException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/UnknownAdviceTypeException.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.adapter; + +/** + * Exception thrown when an attempt is made to use an unsupported + * Advisor or Advice type. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see org.aopalliance.aop.Advice + * @see org.springframework.aop.Advisor + */ +public class UnknownAdviceTypeException extends IllegalArgumentException { + + /** + * Create a new UnknownAdviceTypeException for the given advice object. + * Will create a message text that says that the object is neither a + * subinterface of Advice nor an Advisor. + * @param advice the advice object of unknown type + */ + public UnknownAdviceTypeException(Object advice) { + super("Advice object [" + advice + "] is neither a supported subinterface of " + + "[org.aopalliance.aop.Advice] nor an [org.springframework.aop.Advisor]"); + } + + /** + * Create a new UnknownAdviceTypeException with the given message. + * @param message the message text + */ + public UnknownAdviceTypeException(String message) { + super(message); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/adapter/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/adapter/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/adapter/package.html 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,17 @@ + + + +SPI package allowing Spring AOP framework to handle arbitrary advice types. +
+Users who want merely to use the Spring AOP framework, rather than extend +its capabilities, don't need to concern themselves with this package. +
+ You may wish to use these adapters to wrap Spring-specific advices, such as MethodBeforeAdvice, + in MethodInterceptor, to allow their use in another AOP framework supporting the AOP Alliance interfaces. +
+
+ These adapters do not depend on any other Spring framework classes to allow such usage. +
+ + + Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,178 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.autoproxy; + +import java.util.Collections; +import java.util.List; + +import org.springframework.aop.TargetSource; +import org.springframework.aop.support.AopUtils; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.core.OrderComparator; + +/** + * Generic auto proxy creator that builds AOP proxies for specific beans + * based on detected Advisors for each bean. + * + *

Subclasses must implement the abstract {@link #findCandidateAdvisors()} + * method to return a list of Advisors applying to any object. Subclasses can + * also override the inherited {@link #shouldSkip} method to exclude certain + * objects from auto-proxying. + * + *

Advisors or advices requiring ordering should implement the + * {@link org.springframework.core.Ordered} interface. This class sorts + * Advisors by Ordered order value. Advisors that don't implement the + * Ordered interface will be considered as unordered; they will appear + * at the end of the advisor chain in undefined order. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see #findCandidateAdvisors + */ +public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator { + + private BeanFactoryAdvisorRetrievalHelper advisorRetrievalHelper; + + + public void setBeanFactory(BeanFactory beanFactory) { + super.setBeanFactory(beanFactory); + if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { + throw new IllegalStateException("Cannot use AdvisorAutoProxyCreator without a ConfigurableListableBeanFactory"); + } + initBeanFactory((ConfigurableListableBeanFactory) beanFactory); + } + + protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) { + this.advisorRetrievalHelper = new BeanFactoryAdvisorRetrievalHelperAdapter(beanFactory); + } + + + protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) { + List advisors = findEligibleAdvisors(beanClass, beanName); + if (advisors.isEmpty()) { + return DO_NOT_PROXY; + } + return advisors.toArray(); + } + + /** + * Find all eligible Advisors for auto-proxying this class. + * @param beanClass the clazz to find advisors for + * @param beanName the name of the currently proxied bean + * @return the empty List, not null, + * if there are no pointcuts or interceptors + * @see #findCandidateAdvisors + * @see #sortAdvisors + * @see #extendAdvisors + */ + protected List findEligibleAdvisors(Class beanClass, String beanName) { + List candidateAdvisors = findCandidateAdvisors(); + List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); + if (!eligibleAdvisors.isEmpty()) { + eligibleAdvisors = sortAdvisors(eligibleAdvisors); + } + extendAdvisors(eligibleAdvisors); + return eligibleAdvisors; + } + + /** + * Find all candidate Advisors to use in auto-proxying. + * @return the List of candidate Advisors + */ + protected List findCandidateAdvisors() { + return this.advisorRetrievalHelper.findAdvisorBeans(); + } + + /** + * Search the given candidate Advisors to find all Advisors that + * can apply to the specified bean. + * @param candidateAdvisors the candidate Advisors + * @param beanClass the target's bean class + * @param beanName the target's bean name + * @return the List of applicable Advisors + * @see ProxyCreationContext#getCurrentProxiedBeanName() + */ + protected List findAdvisorsThatCanApply(List candidateAdvisors, Class beanClass, String beanName) { + ProxyCreationContext.setCurrentProxiedBeanName(beanName); + try { + return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass); + } + finally { + ProxyCreationContext.setCurrentProxiedBeanName(null); + } + } + + /** + * Return whether the Advisor bean with the given name is eligible + * for proxying in the first place. + * @param beanName the name of the Advisor bean + * @return whether the bean is eligible + */ + protected boolean isEligibleAdvisorBean(String beanName) { + return true; + } + + /** + * Sort advisors based on ordering. Subclasses may choose to override this + * method to customize the sorting strategy. + * @param advisors the source List of Advisors + * @return the sorted List of Advisors + * @see org.springframework.core.Ordered + * @see org.springframework.core.OrderComparator + */ + protected List sortAdvisors(List advisors) { + Collections.sort(advisors, new OrderComparator()); + return advisors; + } + + /** + * Extension hook that subclasses can override to register additional Advisors, + * given the sorted Advisors obtained to date. + *

The default implementation is empty. + *

Typically used to add Advisors that expose contextual information + * required by some of the later advisors. + * @param candidateAdvisors Advisors that have already been identified as + * applying to a given bean + */ + protected void extendAdvisors(List candidateAdvisors) { + } + + /** + * This auto-proxy creator always returns pre-filtered Advisors. + */ + protected boolean advisorsPreFiltered() { + return true; + } + + + /** + * Subclass of BeanFactoryAdvisorRetrievalHelper that delegates to + * surrounding AbstractAdvisorAutoProxyCreator facilities. + */ + private class BeanFactoryAdvisorRetrievalHelperAdapter extends BeanFactoryAdvisorRetrievalHelper { + + public BeanFactoryAdvisorRetrievalHelperAdapter(ConfigurableListableBeanFactory beanFactory) { + super(beanFactory); + } + + protected boolean isEligibleBean(String beanName) { + return AbstractAdvisorAutoProxyCreator.this.isEligibleAdvisorBean(beanName); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,611 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.autoproxy; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.aopalliance.aop.Advice; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.aop.Advisor; +import org.springframework.aop.TargetSource; +import org.springframework.aop.framework.AopInfrastructureBean; +import org.springframework.aop.framework.ProxyConfig; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.aop.framework.adapter.AdvisorAdapterRegistry; +import org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry; +import org.springframework.aop.target.SingletonTargetSource; +import org.springframework.beans.BeansException; +import org.springframework.beans.PropertyValues; +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor; +import org.springframework.core.CollectionFactory; +import org.springframework.core.Ordered; +import org.springframework.util.ClassUtils; + +/** + * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation + * that wraps each eligible bean with an AOP proxy, delegating to specified interceptors + * before invoking the bean itself. + * + *

This class distinguishes between "common" interceptors: shared for all proxies it + * creates, and "specific" interceptors: unique per bean instance. There need not + * be any common interceptors. If there are, they are set using the interceptorNames + * property. As with ProxyFactoryBean, interceptors names in the current factory + * are used rather than bean references to allow correct handling of prototype + * advisors and interceptors: for example, to support stateful mixins. + * Any advice type is supported for "interceptorNames" entries. + * + *

Such auto-proxying is particularly useful if there's a large number of beans that + * need to be wrapped with similar proxies, i.e. delegating to the same interceptors. + * Instead of x repetitive proxy definitions for x target beans, you can register + * one single such post processor with the bean factory to achieve the same effect. + * + *

Subclasses can apply any strategy to decide if a bean is to be proxied, + * e.g. by type, by name, by definition details, etc. They can also return + * additional interceptors that should just be applied to the specific bean + * instance. The default concrete implementation is BeanNameAutoProxyCreator, + * identifying the beans to be proxied via a list of bean names. + * + *

Any number of {@link TargetSourceCreator} implementations can be used to create + * a custom target source - for example, to pool prototype objects. Auto-proxying will + * occur even if there is no advice, as long as a TargetSourceCreator specifies a custom + * {@link org.springframework.aop.TargetSource}. If there are no TargetSourceCreators set, + * or if none matches, a {@link org.springframework.aop.target.SingletonTargetSource} + * will be used by default to wrap the target bean instance. + * + * @author Juergen Hoeller + * @author Rod Johnson + * @author Rob Harrop + * @since 13.10.2003 + * @see #setInterceptorNames + * @see #getAdvicesAndAdvisorsForBean + * @see BeanNameAutoProxyCreator + * @see DefaultAdvisorAutoProxyCreator + */ +public abstract class AbstractAutoProxyCreator extends ProxyConfig + implements SmartInstantiationAwareBeanPostProcessor, BeanClassLoaderAware, BeanFactoryAware, + Ordered, AopInfrastructureBean { + + /** + * Convenience constant for subclasses: Return value for "do not proxy". + * @see #getAdvicesAndAdvisorsForBean + */ + protected static final Object[] DO_NOT_PROXY = null; + + /** + * Convenience constant for subclasses: Return value for + * "proxy without additional interceptors, just the common ones". + * @see #getAdvicesAndAdvisorsForBean + */ + protected static final Object[] PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS = new Object[0]; + + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + /** Default value is same as non-ordered */ + private int order = Integer.MAX_VALUE; + + /** Default is global AdvisorAdapterRegistry */ + private AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance(); + + /** + * Indicates whether or not the proxy should be frozen. Overridden from super + * to prevent the configuration from becoming frozen too early. + */ + private boolean freezeProxy = false; + + /** Default is no common interceptors */ + private String[] interceptorNames = new String[0]; + + private boolean applyCommonInterceptorsFirst = true; + + private TargetSourceCreator[] customTargetSourceCreators; + + private ClassLoader proxyClassLoader = ClassUtils.getDefaultClassLoader(); + + private boolean classLoaderConfigured = false; + + private BeanFactory beanFactory; + + /** + * Set of bean name Strings, referring to all beans that this auto-proxy creator + * created a custom TargetSource for. Used to detect own pre-built proxies (from + * "postProcessBeforeInstantiation") in the "postProcessAfterInitialization" method. + */ + private final Set targetSourcedBeans = Collections.synchronizedSet(new HashSet()); + + private final Set earlyProxyReferences = Collections.synchronizedSet(new HashSet()); + + private final Set advisedBeans = Collections.synchronizedSet(new HashSet()); + + private final Set nonAdvisedBeans = Collections.synchronizedSet(new HashSet()); + + private final Map proxyTypes = CollectionFactory.createConcurrentMapIfPossible(16); + + + /** + * Set the ordering which will apply to this class's implementation + * of Ordered, used when applying multiple BeanPostProcessors. + *

Default value is Integer.MAX_VALUE, meaning that it's non-ordered. + * @param order ordering value + */ + public final void setOrder(int order) { + this.order = order; + } + + public final int getOrder() { + return this.order; + } + + /** + * Set whether or not the proxy should be frozen, preventing advice + * from being added to it once it is created. + *

Overridden from the super class to prevent the proxy configuration + * from being frozen before the proxy is created. + */ + public void setFrozen(boolean frozen) { + this.freezeProxy = frozen; + } + + public boolean isFrozen() { + return this.freezeProxy; + } + + /** + * Specify the AdvisorAdapterRegistry to use. + * Default is the global AdvisorAdapterRegistry. + * @see org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry + */ + public void setAdvisorAdapterRegistry(AdvisorAdapterRegistry advisorAdapterRegistry) { + this.advisorAdapterRegistry = advisorAdapterRegistry; + } + + /** + * Set custom TargetSourceCreators to be applied in this order. + * If the list is empty, or they all return null, a SingletonTargetSource + * will be created for each bean. + *

Note that TargetSourceCreators will kick in even for target beans + * where no advices or advisors have been found. If a TargetSourceCreator + * returns a TargetSource for a specific bean, that bean will be proxied + * in any case. + *

TargetSourceCreators can only be invoked if this post processor is used + * in a BeanFactory, and its BeanFactoryAware callback is used. + * @param targetSourceCreators list of TargetSourceCreator. + * Ordering is significant: The TargetSource returned from the first matching + * TargetSourceCreator (that is, the first that returns non-null) will be used. + */ + public void setCustomTargetSourceCreators(TargetSourceCreator[] targetSourceCreators) { + this.customTargetSourceCreators = targetSourceCreators; + } + + /** + * Set the common interceptors. These must be bean names in the current factory. + * They can be of any advice or advisor type Spring supports. + *

If this property isn't set, there will be zero common interceptors. + * This is perfectly valid, if "specific" interceptors such as matching + * Advisors are all we want. + */ + public void setInterceptorNames(String[] interceptorNames) { + this.interceptorNames = interceptorNames; + } + + /** + * Set whether the common interceptors should be applied before bean-specific ones. + * Default is "true"; else, bean-specific interceptors will get applied first. + */ + public void setApplyCommonInterceptorsFirst(boolean applyCommonInterceptorsFirst) { + this.applyCommonInterceptorsFirst = applyCommonInterceptorsFirst; + } + + /** + * Set the ClassLoader to generate the proxy class in. + *

Default is the bean ClassLoader, i.e. the ClassLoader used by the + * containing BeanFactory for loading all bean classes. This can be + * overridden here for specific proxies. + */ + public void setProxyClassLoader(ClassLoader classLoader) { + this.proxyClassLoader = classLoader; + this.classLoaderConfigured = (classLoader != null); + } + + public void setBeanClassLoader(ClassLoader classLoader) { + if (!this.classLoaderConfigured) { + this.proxyClassLoader = classLoader; + } + } + + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + + /** + * Return the owning BeanFactory. + * May be null, as this object doesn't need to belong to a bean factory. + */ + protected BeanFactory getBeanFactory() { + return this.beanFactory; + } + + + public Class predictBeanType(Class beanClass, String beanName) { + Object cacheKey = getCacheKey(beanClass, beanName); + return (Class) this.proxyTypes.get(cacheKey); + } + + public Constructor[] determineCandidateConstructors(Class beanClass, String beanName) throws BeansException { + return null; + } + + public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException { + Object cacheKey = getCacheKey(bean.getClass(), beanName); + this.earlyProxyReferences.add(cacheKey); + return wrapIfNecessary(bean, beanName, cacheKey); + } + + public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException { + Object cacheKey = getCacheKey(beanClass, beanName); + + if (!this.targetSourcedBeans.contains(cacheKey)) { + if (this.advisedBeans.contains(cacheKey) || this.nonAdvisedBeans.contains(cacheKey)) { + return null; + } + if (isInfrastructureClass(beanClass, beanName) || shouldSkip(beanClass, beanName)) { + this.nonAdvisedBeans.add(cacheKey); + return null; + } + } + + // Create proxy here if we have a custom TargetSource. + // Suppresses unnecessary default instantiation of the target bean: + // The TargetSource will handle target instances in a custom fashion. + TargetSource targetSource = getCustomTargetSource(beanClass, beanName); + if (targetSource != null) { + this.targetSourcedBeans.add(beanName); + Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource); + Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource); + this.proxyTypes.put(cacheKey, proxy.getClass()); + return proxy; + } + + return null; + } + + public boolean postProcessAfterInstantiation(Object bean, String beanName) { + return true; + } + + public PropertyValues postProcessPropertyValues( + PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) { + + return pvs; + } + + public Object postProcessBeforeInitialization(Object bean, String beanName) { + return bean; + } + + /** + * Create a proxy with the configured interceptors if the bean is + * identified as one to proxy by the subclass. + * @see #getAdvicesAndAdvisorsForBean + */ + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + if (bean != null) { + Object cacheKey = getCacheKey(bean.getClass(), beanName); + if (!this.earlyProxyReferences.contains(cacheKey)) { + return wrapIfNecessary(bean, beanName, cacheKey); + } + } + return bean; + } + + + /** + * Build a cache key for the given bean class and bean name. + * @param beanClass the bean class + * @param beanName the bean name + * @return the cache key for the given class and name + */ + protected Object getCacheKey(Class beanClass, String beanName) { + return beanClass.getName() + "_" + beanName; + } + + /** + * Wrap the given bean if necessary, i.e. if it is eligible for being proxied. + * @param bean the raw bean instance + * @param beanName the name of the bean + * @param cacheKey the cache key for metadata access + * @return a proxy wrapping the bean, or the raw bean instance as-is + */ + protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { + if (this.targetSourcedBeans.contains(beanName)) { + return bean; + } + if (this.nonAdvisedBeans.contains(cacheKey)) { + return bean; + } + if (isInfrastructureClass(bean.getClass(), beanName) || shouldSkip(bean.getClass(), beanName)) { + this.nonAdvisedBeans.add(cacheKey); + return bean; + } + + // Create proxy if we have advice. + Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null); + if (specificInterceptors != DO_NOT_PROXY) { + this.advisedBeans.add(cacheKey); + Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); + this.proxyTypes.put(cacheKey, proxy.getClass()); + return proxy; + } + + this.nonAdvisedBeans.add(cacheKey); + return bean; + } + + /** + * Return whether the given bean class and bean name represents an + * infrastructure class that should never be proxied. + * @deprecated in favor of isInfrastructureClass(beanClass) + * @see #isInfrastructureClass(Class) + */ + protected boolean isInfrastructureClass(Class beanClass, String beanName) { + return isInfrastructureClass(beanClass); + } + + /** + * Return whether the given bean class represents an infrastructure class + * that should never be proxied. + *

Default implementation considers Advisors, Advices and + * AbstractAutoProxyCreators as infrastructure classes. + * @param beanClass the class of the bean + * @return whether the bean represents an infrastructure class + * @see org.springframework.aop.Advisor + * @see org.aopalliance.intercept.MethodInterceptor + * @see #shouldSkip + */ + protected boolean isInfrastructureClass(Class beanClass) { + boolean retVal = Advisor.class.isAssignableFrom(beanClass) || + Advice.class.isAssignableFrom(beanClass) || + AopInfrastructureBean.class.isAssignableFrom(beanClass); + if (retVal && logger.isTraceEnabled()) { + logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]"); + } + return retVal; + } + + /** + * Subclasses should override this method to return true if the + * given bean should not be considered for auto-proxying by this post-processor. + *

Sometimes we need to be able to avoid this happening if it will lead to + * a circular reference. This implementation returns false. + * @param beanClass the class of the bean + * @param beanName the name of the bean + * @return whether to skip the given bean + */ + protected boolean shouldSkip(Class beanClass, String beanName) { + return false; + } + + /** + * Create a target source for bean instances. Uses any TargetSourceCreators if set. + * Returns null if no custom TargetSource should be used. + *

This implementation uses the "customTargetSourceCreators" property. + * Subclasses can override this method to use a different mechanism. + * @param beanClass the class of the bean to create a TargetSource for + * @param beanName the name of the bean + * @return a TargetSource for this bean + * @see #setCustomTargetSourceCreators + */ + protected TargetSource getCustomTargetSource(Class beanClass, String beanName) { + // We can't create fancy target sources for directly registered singletons. + if (this.customTargetSourceCreators != null && + this.beanFactory != null && this.beanFactory.containsBean(beanName)) { + for (int i = 0; i < this.customTargetSourceCreators.length; i++) { + TargetSourceCreator tsc = this.customTargetSourceCreators[i]; + TargetSource ts = tsc.getTargetSource(beanClass, beanName); + if (ts != null) { + // Found a matching TargetSource. + if (logger.isDebugEnabled()) { + logger.debug("TargetSourceCreator [" + tsc + + " found custom TargetSource for bean with name '" + beanName + "'"); + } + return ts; + } + } + } + + // No custom TargetSource found. + return null; + } + + /** + * Create an AOP proxy for the given bean. + * @param beanClass the class of the bean + * @param beanName the name of the bean + * @param specificInterceptors the set of interceptors that is + * specific to this bean (may be empty, but not null) + * @param targetSource the TargetSource for the proxy, + * already pre-configured to access the bean + * @return the AOP proxy for the bean + * @see #buildAdvisors + */ + protected Object createProxy( + Class beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) { + + ProxyFactory proxyFactory = new ProxyFactory(); + // Copy our properties (proxyTargetClass etc) inherited from ProxyConfig. + proxyFactory.copyFrom(this); + + if (!shouldProxyTargetClass(beanClass, beanName)) { + // Must allow for introductions; can't just set interfaces to + // the target's interfaces only. + Class[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, this.proxyClassLoader); + for (int i = 0; i < targetInterfaces.length; i++) { + proxyFactory.addInterface(targetInterfaces[i]); + } + } + + Advisor[] advisors = buildAdvisors(beanName, specificInterceptors); + for (int i = 0; i < advisors.length; i++) { + proxyFactory.addAdvisor(advisors[i]); + } + + proxyFactory.setTargetSource(targetSource); + customizeProxyFactory(proxyFactory); + + proxyFactory.setFrozen(this.freezeProxy); + if (advisorsPreFiltered()) { + proxyFactory.setPreFiltered(true); + } + + return proxyFactory.getProxy(this.proxyClassLoader); + } + + /** + * Determine whether the given bean should be proxied with its target + * class rather than its interfaces. Checks the + * {@link #setProxyTargetClass "proxyTargetClass" setting} as well as the + * {@link AutoProxyUtils#PRESERVE_TARGET_CLASS_ATTRIBUTE "preserveTargetClass" attribute} + * of the corresponding bean definition. + * @param beanClass the class of the bean + * @param beanName the name of the bean + * @return whether the given bean should be proxied with its target class + * @see AutoProxyUtils#shouldProxyTargetClass + */ + protected boolean shouldProxyTargetClass(Class beanClass, String beanName) { + return (isProxyTargetClass() || + (this.beanFactory instanceof ConfigurableListableBeanFactory && + AutoProxyUtils.shouldProxyTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName))); + } + + /** + * Return whether the Advisors returned by the subclass are pre-filtered + * to match the bean's target class already, allowing the ClassFilter check + * to be skipped when building advisors chains for AOP invocations. + *

Default is false. Subclasses may override this if they + * will always return pre-filtered Advisors. + * @return whether the Advisors are pre-filtered + * @see #getAdvicesAndAdvisorsForBean + * @see org.springframework.aop.framework.Advised#setPreFiltered + */ + protected boolean advisorsPreFiltered() { + return false; + } + + /** + * Determine the advisors for the given bean, including the specific interceptors + * as well as the common interceptor, all adapted to the Advisor interface. + * @param beanName the name of the bean + * @param specificInterceptors the set of interceptors that is + * specific to this bean (may be empty, but not null) + * @return the list of Advisors for the given bean + */ + protected Advisor[] buildAdvisors(String beanName, Object[] specificInterceptors) { + // Handle prototypes correctly... + Advisor[] commonInterceptors = resolveInterceptorNames(); + + List allInterceptors = new ArrayList(); + if (specificInterceptors != null) { + allInterceptors.addAll(Arrays.asList(specificInterceptors)); + if (commonInterceptors != null) { + if (this.applyCommonInterceptorsFirst) { + allInterceptors.addAll(0, Arrays.asList(commonInterceptors)); + } + else { + allInterceptors.addAll(Arrays.asList(commonInterceptors)); + } + } + } + if (logger.isDebugEnabled()) { + int nrOfCommonInterceptors = (commonInterceptors != null ? commonInterceptors.length : 0); + int nrOfSpecificInterceptors = (specificInterceptors != null ? specificInterceptors.length : 0); + logger.debug("Creating implicit proxy for bean '" + beanName + "' with " + nrOfCommonInterceptors + + " common interceptors and " + nrOfSpecificInterceptors + " specific interceptors"); + } + + Advisor[] advisors = new Advisor[allInterceptors.size()]; + for (int i = 0; i < allInterceptors.size(); i++) { + advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i)); + } + return advisors; + } + + /** + * Resolves the specified interceptor names to Advisor objects. + * @see #setInterceptorNames + */ + private Advisor[] resolveInterceptorNames() { + ConfigurableBeanFactory cbf = + (this.beanFactory instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) this.beanFactory : null); + List advisors = new ArrayList(); + for (int i = 0; i < this.interceptorNames.length; i++) { + String beanName = this.interceptorNames[i]; + if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) { + Object next = this.beanFactory.getBean(beanName); + advisors.add(this.advisorAdapterRegistry.wrap(next)); + } + } + return (Advisor[]) advisors.toArray(new Advisor[advisors.size()]); + } + + /** + * Subclasses may choose to implement this: for example, + * to change the interfaces exposed. + *

The default implementation is empty. + * @param proxyFactory ProxyFactory that is already configured with + * TargetSource and interfaces and will be used to create the proxy + * immediably after this method returns + */ + protected void customizeProxyFactory(ProxyFactory proxyFactory) { + } + + + /** + * Return whether the given bean is to be proxied, what additional + * advices (e.g. AOP Alliance interceptors) and advisors to apply. + * @param beanClass the class of the bean to advise + * @param beanName the name of the bean + * @param customTargetSource the TargetSource returned by the + * {@link #getCustomTargetSource} method: may be ignored. + * Will be null if no custom target source is in use. + * @return an array of additional interceptors for the particular bean; + * or an empty array if no additional interceptors but just the common ones; + * or null if no proxy at all, not even with the common interceptors. + * See constants DO_NOT_PROXY and PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS. + * @throws BeansException in case of errors + * @see #DO_NOT_PROXY + * @see #PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS + */ + protected abstract Object[] getAdvicesAndAdvisorsForBean( + Class beanClass, String beanName, TargetSource customTargetSource) throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/AutoProxyUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/AutoProxyUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/AutoProxyUtils.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.autoproxy; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.core.Conventions; + +/** + * Utilities for auto-proxy aware components. + * Mainly for internal use within the framework. + * + * @author Juergen Hoeller + * @since 2.0.3 + * @see AbstractAutoProxyCreator + */ +public abstract class AutoProxyUtils { + + /** + * Bean definition attribute that may indicate whether a given bean is supposed + * to be proxied with its target class (in case of it getting proxied in the first + * place). The value is Boolean.TRUE or Boolean.FALSE. + *

Proxy factories can set this attribute if they built a target class proxy + * for a specific bean, and want to enforce that that bean can always be cast + * to its target class (even if AOP advices get applied through auto-proxying). + */ + public static final String PRESERVE_TARGET_CLASS_ATTRIBUTE = + Conventions.getQualifiedAttributeName(AutoProxyUtils.class, "preserveTargetClass"); + + + /** + * Determine whether the given bean should be proxied with its target + * class rather than its interfaces. Checks the + * {@link #PRESERVE_TARGET_CLASS_ATTRIBUTE "preserveTargetClass" attribute} + * of the corresponding bean definition. + * @param beanFactory the containing ConfigurableListableBeanFactory + * @param beanName the name of the bean + * @return whether the given bean should be proxied with its target class + */ + public static boolean shouldProxyTargetClass(ConfigurableListableBeanFactory beanFactory, String beanName) { + if (beanFactory.containsBeanDefinition(beanName)) { + BeanDefinition bd = beanFactory.getBeanDefinition(beanName); + return Boolean.TRUE.equals(bd.getAttribute(PRESERVE_TARGET_CLASS_ATTRIBUTE)); + } + return false; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/BeanFactoryAdvisorRetrievalHelper.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,119 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.autoproxy; + +import java.util.LinkedList; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.aop.Advisor; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanCurrentlyInCreationException; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.util.Assert; + +/** + * Helper for retrieving standard Spring Advisors from a BeanFactory, + * for use with auto-proxying. + * + * @author Juergen Hoeller + * @since 2.0.2 + * @see AbstractAdvisorAutoProxyCreator + */ +public class BeanFactoryAdvisorRetrievalHelper { + + private static final Log logger = LogFactory.getLog(BeanFactoryAdvisorRetrievalHelper.class); + + private final ConfigurableListableBeanFactory beanFactory; + + private String[] cachedAdvisorBeanNames; + + + /** + * Create a new BeanFactoryAdvisorRetrievalHelper for the given BeanFactory. + * @param beanFactory the ListableBeanFactory to scan + */ + public BeanFactoryAdvisorRetrievalHelper(ConfigurableListableBeanFactory beanFactory) { + Assert.notNull(beanFactory, "ListableBeanFactory must not be null"); + this.beanFactory = beanFactory; + } + + + /** + * Find all eligible Advisor beans in the current bean factory, + * ignoring FactoryBeans and excluding beans that are currently in creation. + * @return the list of {@link org.springframework.aop.Advisor} beans + * @see #isEligibleBean + */ + public List findAdvisorBeans() { + // Determine list of advisor bean names, if not cached already. + String[] advisorNames = null; + synchronized (this) { + advisorNames = this.cachedAdvisorBeanNames; + if (advisorNames == null) { + // Do not initialize FactoryBeans here: We need to leave all regular beans + // uninitialized to let the auto-proxy creator apply to them! + advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( + this.beanFactory, Advisor.class, true, false); + this.cachedAdvisorBeanNames = advisorNames; + } + } + if (advisorNames.length == 0) { + return new LinkedList(); + } + + List advisors = new LinkedList(); + for (int i = 0; i < advisorNames.length; i++) { + String name = advisorNames[i]; + if (isEligibleBean(name) && !this.beanFactory.isCurrentlyInCreation(name)) { + try { + advisors.add(this.beanFactory.getBean(name)); + } + catch (BeanCreationException ex) { + Throwable rootCause = ex.getMostSpecificCause(); + if (rootCause instanceof BeanCurrentlyInCreationException) { + BeanCreationException bce = (BeanCreationException) rootCause; + if (this.beanFactory.isCurrentlyInCreation(bce.getBeanName())) { + if (logger.isDebugEnabled()) { + logger.debug("Ignoring currently created advisor '" + name + "': " + ex.getMessage()); + } + // Ignore: indicates a reference back to the bean we're trying to advise. + // We want to find advisors other than the currently created bean itself. + continue; + } + } + throw ex; + } + } + } + return advisors; + } + + /** + * Determine whether the aspect bean with the given name is eligible. + *

The default implementation always returns true. + * @param beanName the name of the aspect bean + * @return whether the bean is eligible + */ + protected boolean isEligibleBean(String beanName) { + return true; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreator.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,106 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.autoproxy; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.springframework.aop.TargetSource; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.util.Assert; +import org.springframework.util.PatternMatchUtils; +import org.springframework.util.StringUtils; + +/** + * Auto proxy creator that identifies beans to proxy via a list of names. + * Checks for direct, "xxx*", and "*xxx" matches. + * + *

For configuration details, see the javadoc of the parent class + * AbstractAutoProxyCreator. Typically, you will specify a list of + * interceptor names to apply to all identified beans, via the + * "interceptorNames" property. + * + * @author Juergen Hoeller + * @since 10.10.2003 + * @see #setBeanNames + * @see #isMatch + * @see #setInterceptorNames + * @see AbstractAutoProxyCreator + */ +public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator { + + private List beanNames; + + + /** + * Set the names of the beans that should automatically get wrapped with proxies. + * A name can specify a prefix to match by ending with "*", e.g. "myBean,tx*" + * will match the bean named "myBean" and all beans whose name start with "tx". + *

NOTE: In case of a FactoryBean, only the objects created by the + * FactoryBean will get proxied. This default behavior applies as of Spring 2.0. + * If you intend to proxy a FactoryBean instance itself (a rare use case, but + * Spring 1.2's default behavior), specify the bean name of the FactoryBean + * including the factory-bean prefix "&": e.g. "&myFactoryBean". + * @see org.springframework.beans.factory.FactoryBean + * @see org.springframework.beans.factory.BeanFactory#FACTORY_BEAN_PREFIX + */ + public void setBeanNames(String[] beanNames) { + Assert.notEmpty(beanNames, "'beanNames' must not be empty"); + this.beanNames = new ArrayList(beanNames.length); + for (int i = 0; i < beanNames.length; i++) { + this.beanNames.add(StringUtils.trimWhitespace(beanNames[i])); + } + } + + + /** + * Identify as bean to proxy if the bean name is in the configured list of names. + */ + protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) { + if (this.beanNames != null) { + for (Iterator it = this.beanNames.iterator(); it.hasNext();) { + String mappedName = (String) it.next(); + if (FactoryBean.class.isAssignableFrom(beanClass)) { + if (!mappedName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) { + continue; + } + mappedName = mappedName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length()); + } + if (isMatch(beanName, mappedName)) { + return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS; + } + } + } + return DO_NOT_PROXY; + } + + /** + * Return if the given bean name matches the mapped name. + *

The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, + * as well as direct equality. Can be overridden in subclasses. + * @param beanName the bean name to check + * @param mappedName the name in the configured list of names + * @return if the names match + * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) + */ + protected boolean isMatch(String beanName, String mappedName) { + return PatternMatchUtils.simpleMatch(mappedName, beanName); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/DefaultAdvisorAutoProxyCreator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/DefaultAdvisorAutoProxyCreator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/DefaultAdvisorAutoProxyCreator.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,98 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.autoproxy; + +import org.springframework.beans.factory.BeanNameAware; + +/** + * BeanPostProcessor implementation that creates AOP proxies based on all candidate + * Advisors in the current BeanFactory. This class is completely generic; it contains + * no special code to handle any particular aspects, such as pooling aspects. + * + *

It's possible to filter out advisors - for example, to use multiple post processors + * of this type in the same factory - by setting the usePrefix property + * to true, in which case only advisors beginning with the DefaultAdvisorAutoProxyCreator's + * bean name followed by a dot (like "aapc.") will be used. This default prefix can be + * changed from the bean name by setting the advisorBeanNamePrefix property. + * The separator (.) will also be used in this case. + * + * @author Rod Johnson + * @author Rob Harrop + */ +public class DefaultAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator implements BeanNameAware { + + /** Separator between prefix and remainder of bean name */ + public final static String SEPARATOR = "."; + + + private boolean usePrefix; + + private String advisorBeanNamePrefix; + + + /** + * Set whether to exclude advisors with a certain prefix + * in the bean name. + */ + public void setUsePrefix(boolean usePrefix) { + this.usePrefix = usePrefix; + } + + /** + * Return whether to exclude advisors with a certain prefix + * in the bean name. + */ + public boolean isUsePrefix() { + return this.usePrefix; + } + + /** + * Set the prefix for bean names that will cause them to be included for + * auto-proxying by this object. This prefix should be set to avoid circular + * references. Default value is the bean name of this object + a dot. + * @param advisorBeanNamePrefix the exclusion prefix + */ + public void setAdvisorBeanNamePrefix(String advisorBeanNamePrefix) { + this.advisorBeanNamePrefix = advisorBeanNamePrefix; + } + + /** + * Return the prefix for bean names that will cause them to be included + * for auto-proxying by this object. + */ + public String getAdvisorBeanNamePrefix() { + return this.advisorBeanNamePrefix; + } + + public void setBeanName(String name) { + // If no infrastructure bean name prefix has been set, override it. + if (this.advisorBeanNamePrefix == null) { + this.advisorBeanNamePrefix = name + SEPARATOR; + } + } + + + /** + * Consider Advisor beans with the specified prefix as eligible, if activated. + * @see #setUsePrefix + * @see #setAdvisorBeanNamePrefix + */ + protected boolean isEligibleAdvisorBean(String beanName) { + return (!isUsePrefix() || beanName.startsWith(getAdvisorBeanNamePrefix())); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/InfrastructureAdvisorAutoProxyCreator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/InfrastructureAdvisorAutoProxyCreator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/InfrastructureAdvisorAutoProxyCreator.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.autoproxy; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; + +/** + * Auto-proxy creator that considers infrastructure Advisor beans only, + * ignoring any application-defined Advisors. + * + * @author Juergen Hoeller + * @since 2.0.7 + */ +public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator { + + private ConfigurableListableBeanFactory beanFactory; + + + protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) { + super.initBeanFactory(beanFactory); + this.beanFactory = beanFactory; + } + + protected boolean isEligibleAdvisorBean(String beanName) { + return (this.beanFactory.containsBeanDefinition(beanName) && + this.beanFactory.getBeanDefinition(beanName).getRole() == BeanDefinition.ROLE_INFRASTRUCTURE); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/ProxyCreationContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/ProxyCreationContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/ProxyCreationContext.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.autoproxy; + +import org.springframework.core.NamedThreadLocal; + +/** + * Holder for the current proxy creation context, as exposed by auto-proxy creators + * such as {@link AbstractAdvisorAutoProxyCreator}. + * + * @author Juergen Hoeller + * @author Ramnivas Laddad + * @since 2.5 + */ +public class ProxyCreationContext { + + /** ThreadLocal holding the current proxied bean name during Advisor matching */ + private static final ThreadLocal currentProxiedBeanName = + new NamedThreadLocal("Name of currently proxied bean"); + + + /** + * Return the name of the currently proxied bean instance. + * @return the name of the bean, or null if none available + */ + public static String getCurrentProxiedBeanName() { + return (String) currentProxiedBeanName.get(); + } + + /** + * Set the name of the currently proxied bean instance. + * @param beanName the name of the bean, or null to reset it + */ + static void setCurrentProxiedBeanName(String beanName) { + currentProxiedBeanName.set(beanName); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/TargetSourceCreator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/TargetSourceCreator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/TargetSourceCreator.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.autoproxy; + +import org.springframework.aop.TargetSource; + +/** + * Implementations can create special target sources, such as pooling target + * sources, for particular beans. For example, they may base their choice + * on attributes, such as a pooling attribute, on the target class. + * + *

AbstractAutoProxyCreator can support a number of TargetSourceCreators, + * which will be applied in order. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public interface TargetSourceCreator { + + /** + * Create a special TargetSource for the given bean, if any. + * @param beanClass the class of the bean to create a TargetSource for + * @param beanName the name of the bean + * @return a special TargetSource or null if this TargetSourceCreator isn't + * interested in the particular bean + */ + TargetSource getTargetSource(Class beanClass, String beanName); + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/package.html 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,15 @@ + + + +Bean post-processors for use in ApplicationContexts to simplify AOP usage +by automatically creating AOP proxies without the need to use a ProxyFactoryBean. + +

The various post-processors in this package need only be added to an ApplicationContext +(typically in an XML bean definition document) to automatically proxy selected beans. + +

NB: Automatic auto-proxying is not supported for BeanFactory implementations, +as post-processors beans are only automatically detected in application contexts. +Post-processors can be explicitly registered on a ConfigurableBeanFactory instead. + + + Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/target/AbstractBeanFactoryBasedTargetSourceCreator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/target/AbstractBeanFactoryBasedTargetSourceCreator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/target/AbstractBeanFactoryBasedTargetSourceCreator.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,200 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.autoproxy.target; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.aop.TargetSource; +import org.springframework.aop.framework.AopInfrastructureBean; +import org.springframework.aop.framework.autoproxy.TargetSourceCreator; +import org.springframework.aop.target.AbstractBeanFactoryBasedTargetSource; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.beans.factory.support.GenericBeanDefinition; + +/** + * Convenient superclass for + * {@link org.springframework.aop.framework.autoproxy.TargetSourceCreator} + * implementations that require creating multiple instances of a prototype bean. + * + *

Uses an internal BeanFactory to manage the target instances, + * copying the original bean definition to this internal factory. + * This is necessary because the original BeanFactory will just + * contain the proxy instance created through auto-proxying. + * + *

Requires running in an + * {@link org.springframework.beans.factory.support.AbstractBeanFactory}. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see org.springframework.aop.target.AbstractBeanFactoryBasedTargetSource + * @see org.springframework.beans.factory.support.AbstractBeanFactory + */ +public abstract class AbstractBeanFactoryBasedTargetSourceCreator + implements TargetSourceCreator, BeanFactoryAware, DisposableBean { + + protected final Log logger = LogFactory.getLog(getClass()); + + private ConfigurableBeanFactory beanFactory; + + /** Internally used DefaultListableBeanFactory instances, keyed by bean name */ + private final Map internalBeanFactories = new HashMap(); + + + public final void setBeanFactory(BeanFactory beanFactory) { + if (!(beanFactory instanceof ConfigurableBeanFactory)) { + throw new IllegalStateException("Cannot do auto-TargetSource creation with a BeanFactory " + + "that doesn't implement ConfigurableBeanFactory: " + beanFactory.getClass()); + } + this.beanFactory = (ConfigurableBeanFactory) beanFactory; + } + + /** + * Return the BeanFactory that this TargetSourceCreators runs in. + */ + protected final BeanFactory getBeanFactory() { + return this.beanFactory; + } + + + //--------------------------------------------------------------------- + // Implementation of the TargetSourceCreator interface + //--------------------------------------------------------------------- + + public final TargetSource getTargetSource(Class beanClass, String beanName) { + AbstractBeanFactoryBasedTargetSource targetSource = + createBeanFactoryBasedTargetSource(beanClass, beanName); + if (targetSource == null) { + return null; + } + + if (logger.isDebugEnabled()) { + logger.debug("Configuring AbstractBeanFactoryBasedTargetSource: " + targetSource); + } + + DefaultListableBeanFactory internalBeanFactory = getInternalBeanFactoryForBean(beanName); + + // We need to override just this bean definition, as it may reference other beans + // and we're happy to take the parent's definition for those. + // Always use prototype scope if demanded. + BeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName); + GenericBeanDefinition bdCopy = new GenericBeanDefinition(bd); + if (isPrototypeBased()) { + bdCopy.setScope(BeanDefinition.SCOPE_PROTOTYPE); + } + internalBeanFactory.registerBeanDefinition(beanName, bdCopy); + + // Complete configuring the PrototypeTargetSource. + targetSource.setTargetBeanName(beanName); + targetSource.setBeanFactory(internalBeanFactory); + + return targetSource; + } + + /** + * Return the internal BeanFactory to be used for the specified bean. + * @param beanName the name of the target bean + * @return the internal BeanFactory to be used + */ + protected DefaultListableBeanFactory getInternalBeanFactoryForBean(String beanName) { + DefaultListableBeanFactory internalBeanFactory = null; + synchronized (this.internalBeanFactories) { + internalBeanFactory = (DefaultListableBeanFactory) this.internalBeanFactories.get(beanName); + if (internalBeanFactory == null) { + internalBeanFactory = buildInternalBeanFactory(this.beanFactory); + this.internalBeanFactories.put(beanName, internalBeanFactory); + } + } + return internalBeanFactory; + } + + /** + * Build an internal BeanFactory for resolving target beans. + * @param containingFactory the containing BeanFactory that originally defines the beans + * @return an independent internal BeanFactory to hold copies of some target beans + */ + protected DefaultListableBeanFactory buildInternalBeanFactory(ConfigurableBeanFactory containingFactory) { + // Set parent so that references (up container hierarchies) are correctly resolved. + DefaultListableBeanFactory internalBeanFactory = new DefaultListableBeanFactory(containingFactory); + + // Required so that all BeanPostProcessors, Scopes, etc become available. + internalBeanFactory.copyConfigurationFrom(containingFactory); + + // Filter out BeanPostProcessors that are part of the AOP infrastructure, + // since those are only meant to apply to beans defined in the original factory. + for (Iterator it = internalBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) { + BeanPostProcessor postProcessor = (BeanPostProcessor) it.next(); + if (postProcessor instanceof AopInfrastructureBean) { + it.remove(); + } + } + + return internalBeanFactory; + } + + /** + * Destroys the internal BeanFactory on shutdown of the TargetSourceCreator. + * @see #getInternalBeanFactoryForBean + */ + public void destroy() { + synchronized (this.internalBeanFactories) { + for (Iterator it = this.internalBeanFactories.values().iterator(); it.hasNext();) { + ((DefaultListableBeanFactory) it.next()).destroySingletons(); + } + } + } + + + //--------------------------------------------------------------------- + // Template methods to be implemented by subclasses + //--------------------------------------------------------------------- + + /** + * Return whether this TargetSourceCreator is prototype-based. + * The scope of the target bean definition will be set accordingly. + *

Default is "true". + * @see org.springframework.beans.factory.config.BeanDefinition#isSingleton() + */ + protected boolean isPrototypeBased() { + return true; + } + + /** + * Subclasses must implement this method to return a new AbstractPrototypeBasedTargetSource + * if they wish to create a custom TargetSource for this bean, or null if they are + * not interested it in, in which case no special target source will be created. + * Subclasses should not call setTargetBeanName or setBeanFactory + * on the AbstractPrototypeBasedTargetSource: This class' implementation of + * getTargetSource() will do that. + * @param beanClass the class of the bean to create a TargetSource for + * @param beanName the name of the bean + * @return the AbstractPrototypeBasedTargetSource, or null if we don't match this + */ + protected abstract AbstractBeanFactoryBasedTargetSource createBeanFactoryBasedTargetSource( + Class beanClass, String beanName); + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/target/LazyInitTargetSourceCreator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/target/LazyInitTargetSourceCreator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/target/LazyInitTargetSourceCreator.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.autoproxy.target; + +import org.springframework.aop.target.AbstractBeanFactoryBasedTargetSource; +import org.springframework.aop.target.LazyInitTargetSource; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; + +/** + * TargetSourceCreator that enforces a LazyInitTargetSource for each bean + * that is defined as "lazy-init". This will lead to a proxy created for + * each of those beans, allowing to fetch a reference to such a bean + * without actually initialized the target bean instance. + * + *

To be registered as custom TargetSourceCreator for an auto-proxy creator, + * in combination with custom interceptors for specific beans or for the + * creation of lazy-init proxies only. For example, as autodetected + * infrastructure bean in an XML application context definition: + * + *

+ * <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
+ *   <property name="customTargetSourceCreators">
+ *     <list>
+ *       <bean class="org.springframework.aop.framework.autoproxy.target.LazyInitTargetSourceCreator"/>
+ *     </list>
+ *   </property>
+ * </bean>
+ *
+ * <bean id="myLazyInitBean" class="mypackage.MyBeanClass" lazy-init="true">
+ *   ...
+ * </bean>
+ * + * @author Juergen Hoeller + * @since 1.2 + * @see org.springframework.beans.factory.config.BeanDefinition#isLazyInit + * @see org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#setCustomTargetSourceCreators + * @see org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator + */ +public class LazyInitTargetSourceCreator extends AbstractBeanFactoryBasedTargetSourceCreator { + + protected boolean isPrototypeBased() { + return false; + } + + protected AbstractBeanFactoryBasedTargetSource createBeanFactoryBasedTargetSource( + Class beanClass, String beanName) { + + if (getBeanFactory() instanceof ConfigurableListableBeanFactory) { + BeanDefinition definition = + ((ConfigurableListableBeanFactory) getBeanFactory()).getBeanDefinition(beanName); + if (definition.isLazyInit()) { + return new LazyInitTargetSource(); + } + } + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/target/QuickTargetSourceCreator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/target/QuickTargetSourceCreator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/target/QuickTargetSourceCreator.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.framework.autoproxy.target; + +import org.springframework.aop.target.AbstractBeanFactoryBasedTargetSource; +import org.springframework.aop.target.CommonsPoolTargetSource; +import org.springframework.aop.target.PrototypeTargetSource; +import org.springframework.aop.target.ThreadLocalTargetSource; + +/** + * Convenient TargetSourceCreator using bean name prefixes to create one of three + * well-known TargetSource types: + *
  • : CommonsPoolTargetSource + *
  • % ThreadLocalTargetSource + *
  • ! PrototypeTargetSource + * + * @author Rod Johnson + * @see org.springframework.aop.target.CommonsPoolTargetSource + * @see org.springframework.aop.target.ThreadLocalTargetSource + * @see org.springframework.aop.target.PrototypeTargetSource + */ +public class QuickTargetSourceCreator extends AbstractBeanFactoryBasedTargetSourceCreator { + + public static final String PREFIX_COMMONS_POOL = ":"; + public static final String PREFIX_THREAD_LOCAL = "%"; + public static final String PREFIX_PROTOTYPE = "!"; + + protected final AbstractBeanFactoryBasedTargetSource createBeanFactoryBasedTargetSource( + Class beanClass, String beanName) { + + if (beanName.startsWith(PREFIX_COMMONS_POOL)) { + CommonsPoolTargetSource cpts = new CommonsPoolTargetSource(); + cpts.setMaxSize(25); + return cpts; + } + else if (beanName.startsWith(PREFIX_THREAD_LOCAL)) { + return new ThreadLocalTargetSource(); + } + else if (beanName.startsWith(PREFIX_PROTOTYPE)) { + return new PrototypeTargetSource(); + } + else { + // No match. Don't create a custom target source. + return null; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/target/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/target/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/framework/autoproxy/target/package.html 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,7 @@ + + + +Generic support classes for target source creation. + + + Index: 3rdParty_sources/spring/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/interceptor/AbstractMonitoringInterceptor.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,110 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.interceptor; + +import java.lang.reflect.Method; + +import org.aopalliance.intercept.MethodInvocation; + +/** + * Base class for monitoring interceptors, such as performance monitors. + * Provides prefix and suffix properties + * that help to classify/group performance monitoring results. + * + *

    Subclasses should call the createInvocationTraceName(MethodInvocation) + * method to create a name for the given trace that includes information about the + * method invocation under trace along with the prefix and suffix added as appropriate. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 1.2.7 + * @see #setPrefix + * @see #setSuffix + * @see #createInvocationTraceName + */ +public abstract class AbstractMonitoringInterceptor extends AbstractTraceInterceptor { + + private String prefix = ""; + + private String suffix = ""; + + private boolean logTargetClassInvocation = false; + + + /** + * Set the text that will get appended to the trace data. + *

    Default is none. + */ + public void setPrefix(String prefix) { + this.prefix = (prefix != null ? prefix : ""); + } + + /** + * Return the text that will get appended to the trace data. + */ + protected String getPrefix() { + return this.prefix; + } + + /** + * Set the text that will get prepended to the trace data. + *

    Default is none. + */ + public void setSuffix(String suffix) { + this.suffix = (suffix != null ? suffix : ""); + } + + /** + * Return the text that will get prepended to the trace data. + */ + protected String getSuffix() { + return this.suffix; + } + + /** + * Set whether to log the invocation on the target class, if applicable + * (i.e. if the method is actually delegated to the target class). + *

    Default is "false", logging the invocation based on the proxy + * interface/class name. + */ + public void setLogTargetClassInvocation(boolean logTargetClassInvocation) { + this.logTargetClassInvocation = logTargetClassInvocation; + } + + + /** + * Create a String name for the given MethodInvocation + * that can be used for trace/logging purposes. This name is made up of the + * configured prefix, followed by the fully-qualified name of the method being + * invoked, followed by the configured suffix. + * @see #setPrefix + * @see #setSuffix + */ + protected String createInvocationTraceName(MethodInvocation invocation) { + StringBuffer sb = new StringBuffer(getPrefix()); + Method method = invocation.getMethod(); + Class clazz = method.getDeclaringClass(); + if (this.logTargetClassInvocation && clazz.isInstance(invocation.getThis())) { + clazz = invocation.getThis().getClass(); + } + sb.append(clazz.getName()); + sb.append('.').append(method.getName()); + sb.append(getSuffix()); + return sb.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/interceptor/AbstractTraceInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/interceptor/AbstractTraceInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/interceptor/AbstractTraceInterceptor.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,191 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.interceptor; + +import java.io.Serializable; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.aop.support.AopUtils; + +/** + * Base MethodInterceptor implementation for tracing. + * + *

    By default, log messages are written to the log for the interceptor class, + * not the class which is being intercepted. Setting the useDynamicLogger + * bean property to true causes all log messages to be written to + * the Log for the target class being intercepted. + * + *

    Subclasses must implement the invokeUnderTrace method, which + * is invoked by this class ONLY when a particular invocation SHOULD be traced. + * Subclasses should write to the Log instance provided. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 1.2 + * @see #setUseDynamicLogger + * @see #invokeUnderTrace(org.aopalliance.intercept.MethodInvocation, org.apache.commons.logging.Log) + */ +public abstract class AbstractTraceInterceptor implements MethodInterceptor, Serializable { + + /** + * The default Log instance used to write trace messages. + * This instance is mapped to the implementing Class. + */ + protected transient Log defaultLogger = LogFactory.getLog(getClass()); + + /** + * Indicates whether or not proxy class names should be hidden when using dynamic loggers. + * @see #setUseDynamicLogger + */ + private boolean hideProxyClassNames = false; + + + /** + * Set whether to use a dynamic logger or a static logger. + * Default is a static logger for this trace interceptor. + *

    Used to determine which Log instance should be used to write + * log messages for a particular method invocation: a dynamic one for the + * Class getting called, or a static one for the Class + * of the trace interceptor. + *

    NOTE: Specify either this property or "loggerName", not both. + * @see #getLoggerForInvocation(org.aopalliance.intercept.MethodInvocation) + */ + public void setUseDynamicLogger(boolean useDynamicLogger) { + // Release default logger if it is not being used. + this.defaultLogger = (useDynamicLogger ? null : LogFactory.getLog(getClass())); + } + + /** + * Set the name of the logger to use. The name will be passed to the + * underlying logger implementation through Commons Logging, getting + * interpreted as log category according to the logger's configuration. + *

    This can be specified to not log into the category of a class + * (whether this interceptor's class or the class getting called) + * but rather into a specific named category. + *

    NOTE: Specify either this property or "useDynamicLogger", not both. + * @see org.apache.commons.logging.LogFactory#getLog(String) + * @see org.apache.log4j.Logger#getLogger(String) + * @see java.util.logging.Logger#getLogger(String) + */ + public void setLoggerName(String loggerName) { + this.defaultLogger = LogFactory.getLog(loggerName); + } + + /** + * Set to "true" to have {@link #setUseDynamicLogger dynamic loggers} hide + * proxy class names wherever possible. Default is "false". + */ + public void setHideProxyClassNames(boolean hideProxyClassNames) { + this.hideProxyClassNames = hideProxyClassNames; + } + + + /** + * Determines whether or not logging is enabled for the particular MethodInvocation. + * If not, the method invocation proceeds as normal, otherwise the method invocation is passed + * to the invokeUnderTrace method for handling. + * @see #invokeUnderTrace(org.aopalliance.intercept.MethodInvocation, org.apache.commons.logging.Log) + */ + public Object invoke(MethodInvocation invocation) throws Throwable { + Log logger = getLoggerForInvocation(invocation); + if (isInterceptorEnabled(invocation, logger)) { + return invokeUnderTrace(invocation, logger); + } + else { + return invocation.proceed(); + } + } + + /** + * Return the appropriate Log instance to use for the given + * MethodInvocation. If the useDynamicLogger flag + * is set, the Log instance will be for the target class of the + * MethodInvocation, otherwise the Log will be the + * default static logger. + * @param invocation the MethodInvocation being traced + * @return the Log instance to use + * @see #setUseDynamicLogger + */ + protected Log getLoggerForInvocation(MethodInvocation invocation) { + if (this.defaultLogger != null) { + return this.defaultLogger; + } + else { + Object target = invocation.getThis(); + return LogFactory.getLog(getClassForLogging(target)); + } + } + + /** + * Determine the class to use for logging purposes. + * @param target the target object to introspect + * @return the target class for the given object + * @see #setHideProxyClassNames + */ + protected Class getClassForLogging(Object target) { + return (this.hideProxyClassNames ? AopUtils.getTargetClass(target) : target.getClass()); + } + + /** + * Determine whether the interceptor should kick in, that is, + * whether the invokeUnderTrace method should be called. + *

    Default behavior is to check whether the given Log + * instance is enabled. Subclasses can override this to apply the + * interceptor in other cases as well. + * @param invocation the MethodInvocation being traced + * @param logger the Log instance to check + * @see #invokeUnderTrace + * @see #isLogEnabled + */ + protected boolean isInterceptorEnabled(MethodInvocation invocation, Log logger) { + return isLogEnabled(logger); + } + + /** + * Determine whether the given {@link Log} instance is enabled. + *

    Default is true when the "trace" level is enabled. + * Subclasses can override this to change the level under which 'tracing' occurs. + * @param logger the Log instance to check + */ + protected boolean isLogEnabled(Log logger) { + return logger.isTraceEnabled(); + } + + + /** + * Subclasses must override this method to perform any tracing around the + * supplied MethodInvocation. Subclasses are responsible for + * ensuring that the MethodInvocation actually executes by + * calling MethodInvocation.proceed(). + *

    By default, the passed-in Log instance will have log level + * "trace" enabled. Subclasses do not have to check for this again, unless + * they overwrite the isInterceptorEnabled method to modify + * the default behavior. + * @param logger the Log to write trace messages to + * @return the result of the call to MethodInvocation.proceed() + * @throws Throwable if the call to MethodInvocation.proceed() + * encountered any errors + * @see #isInterceptorEnabled + * @see #isLogEnabled + */ + protected abstract Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable; + +} Index: 3rdParty_sources/spring/org/springframework/aop/interceptor/ClassLoaderAnalyzerInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/interceptor/ClassLoaderAnalyzerInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/interceptor/ClassLoaderAnalyzerInterceptor.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.interceptor; + +import java.io.Serializable; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.util.ClassLoaderUtils; + +/** + * Trivial classloader analyzer interceptor. + * + * @author Rod Johnson + * @author Dmitriy Kopylenko + * @deprecated as of Spring 2.5, to be removed in Spring 3.0 + * @see org.springframework.util.ClassLoaderUtils + */ +public class ClassLoaderAnalyzerInterceptor implements MethodInterceptor, Serializable { + + /** Static to avoid serializing the logger */ + protected static final Log logger = LogFactory.getLog(ClassLoaderAnalyzerInterceptor.class); + + public Object invoke(MethodInvocation invocation) throws Throwable { + if (logger.isInfoEnabled()) { + logger.info( + ClassLoaderUtils.showClassLoaderHierarchy( + invocation.getThis(), + invocation.getThis().getClass().getName(), + "\n", + "-")); + } + return invocation.proceed(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptor.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.interceptor; + +import java.io.Serializable; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.util.ConcurrencyThrottleSupport; + +/** + * Interceptor that throttles concurrent access, blocking invocations + * if a specified concurrency limit is reached. + * + *

    Can be applied to methods of local services that involve heavy use + * of system resources, in a scenario where it is more efficient to + * throttle concurrency for a specific service rather than restricting + * the entire thread pool (e.g. the web container's thread pool). + * + *

    The default concurrency limit of this interceptor is 1. + * Specify the "concurrencyLimit" bean property to change this value. + * + * @author Juergen Hoeller + * @since 11.02.2004 + * @see #setConcurrencyLimit + */ +public class ConcurrencyThrottleInterceptor extends ConcurrencyThrottleSupport + implements MethodInterceptor, Serializable { + + public ConcurrencyThrottleInterceptor() { + setConcurrencyLimit(1); + } + + public Object invoke(MethodInvocation methodInvocation) throws Throwable { + beforeAccess(); + try { + return methodInvocation.proceed(); + } + finally { + afterAccess(); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,441 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.interceptor; + +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.logging.Log; + +import org.springframework.core.Constants; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.StopWatch; +import org.springframework.util.StringUtils; + +/** + * MethodInterceptor implementation that allows for highly customizable + * method-level tracing, using placeholders. + * + *

    Trace messages are written on method entry, and if the method invocation succeeds + * on method exit. If an invocation results in an exception, then an exception message + * is written. The contents of these trace messages is fully customizable and special + * placeholders are available to allow you to include runtime information in your log + * messages. The placeholders available are: + * + *

      + *
    • $[methodName] - replaced with the name of the method being invoked
    • + *
    • $[targetClassName] - replaced with the name of the class that is + * the target of the invocation
    • + *
    • $[targetClassShortName] - replaced with the short name of the class + * that is the target of the invocation
    • + *
    • $[returnValue] - replaced with the value returned by the invocation
    • + *
    • $[argumentTypes] - replaced with a comma-separated list of the + * short class names of the method arguments
    • + *
    • $[arguments] - replaced with a comma-separated list of the + * String representation of the method arguments
    • + *
    • $[exception] - replaced with the String representation + * of any Throwable raised during the invocation
    • + *
    • $[invocationTime] - replaced with the time, in milliseconds, + * taken by the method invocation
    • + *
    + * + *

    There are restrictions on which placeholders can be used in which messages: + * see the individual message properties for details on the valid placeholders. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 1.2 + * @see #setEnterMessage + * @see #setExitMessage + * @see #setExceptionMessage + * @see SimpleTraceInterceptor + */ +public class CustomizableTraceInterceptor extends AbstractTraceInterceptor { + + /** + * The $[methodName] placeholder. + * Replaced with the name of the method being invoked. + */ + public static final String PLACEHOLDER_METHOD_NAME = "$[methodName]"; + + /** + * The $[targetClassName] placeholder. + * Replaced with the fully-qualifed name of the Class + * of the method invocation target. + */ + public static final String PLACEHOLDER_TARGET_CLASS_NAME = "$[targetClassName]"; + + /** + * The $[targetClassShortName] placeholder. + * Replaced with the short name of the Class of the + * method invocation target. + */ + public static final String PLACEHOLDER_TARGET_CLASS_SHORT_NAME = "$[targetClassShortName]"; + + /** + * The $[returnValue] placeholder. + * Replaced with the String representation of the value + * returned by the method invocation. + */ + public static final String PLACEHOLDER_RETURN_VALUE = "$[returnValue]"; + + /** + * The $[argumentTypes] placeholder. + * Replaced with a comma-separated list of the argument types for the + * method invocation. Argument types are written as short class names. + */ + public static final String PLACEHOLDER_ARGUMENT_TYPES = "$[argumentTypes]"; + + /** + * The $[arguments] placeholder. + * Replaced with a comma separated list of the argument values for the + * method invocation. Relies on the toString() method of + * each argument type. + */ + public static final String PLACEHOLDER_ARGUMENTS = "$[arguments]"; + + /** + * The $[exception] placeholder. + * Replaced with the String representation of any + * Throwable raised during method invocation. + */ + public static final String PLACEHOLDER_EXCEPTION = "$[exception]"; + + /** + * The $[invocationTime] placeholder. + * Replaced with the time taken by the invocation (in milliseconds). + */ + public static final String PLACEHOLDER_INVOCATION_TIME = "$[invocationTime]"; + + /** + * The default message used for writing method entry messages. + */ + private static final String DEFAULT_ENTER_MESSAGE = + "Entering method '" + PLACEHOLDER_METHOD_NAME + "' of class [" + PLACEHOLDER_TARGET_CLASS_NAME + "]"; + + /** + * The default message used for writing method exit messages. + */ + private static final String DEFAULT_EXIT_MESSAGE = + "Exiting method '" + PLACEHOLDER_METHOD_NAME + "' of class [" + PLACEHOLDER_TARGET_CLASS_NAME + "]"; + + /** + * The default message used for writing exception messages. + */ + private static final String DEFAULT_EXCEPTION_MESSAGE = + "Exception thrown in method '" + PLACEHOLDER_METHOD_NAME + "' of class [" + PLACEHOLDER_TARGET_CLASS_NAME + "]"; + + /** + * The Pattern used to match placeholders. + */ + private static final Pattern PATTERN = Pattern.compile("\\$\\[\\p{Alpha}+\\]"); + + /** + * The Set of allowed placeholders. + */ + private static final Set ALLOWED_PLACEHOLDERS = + new Constants(CustomizableTraceInterceptor.class).getValues("PLACEHOLDER_"); + + + /** + * The message for method entry. + */ + private String enterMessage = DEFAULT_ENTER_MESSAGE; + + /** + * The message for method exit. + */ + private String exitMessage = DEFAULT_EXIT_MESSAGE; + + /** + * The message for exceptions during method execution. + */ + private String exceptionMessage = DEFAULT_EXCEPTION_MESSAGE; + + + /** + * Set the template used for method entry log messages. + * This template can contain any of the following placeholders: + *

      + *
    • $[targetClassName]
    • + *
    • $[targetClassShortName]
    • + *
    • $[argumentTypes]
    • + *
    • $[arguments]
    • + *
    + */ + public void setEnterMessage(String enterMessage) throws IllegalArgumentException { + Assert.hasText(enterMessage, "'enterMessage' must not be empty"); + checkForInvalidPlaceholders(enterMessage); + Assert.doesNotContain(enterMessage, PLACEHOLDER_RETURN_VALUE, + "enterMessage cannot contain placeholder [" + PLACEHOLDER_RETURN_VALUE + "]"); + Assert.doesNotContain(enterMessage, PLACEHOLDER_EXCEPTION, + "enterMessage cannot contain placeholder [" + PLACEHOLDER_EXCEPTION + "]"); + Assert.doesNotContain(enterMessage, PLACEHOLDER_INVOCATION_TIME, + "enterMessage cannot contain placeholder [" + PLACEHOLDER_INVOCATION_TIME + "]"); + this.enterMessage = enterMessage; + } + + /** + * Set the template used for method exit log messages. + * This template can contain any of the following placeholders: + *
      + *
    • $[targetClassName]
    • + *
    • $[targetClassShortName]
    • + *
    • $[argumentTypes]
    • + *
    • $[arguments]
    • + *
    • $[returnValue]
    • + *
    • $[invocationTime]
    • + *
    + */ + public void setExitMessage(String exitMessage) { + Assert.hasText(exitMessage, "'exitMessage' must not be empty"); + checkForInvalidPlaceholders(exitMessage); + Assert.doesNotContain(exitMessage, PLACEHOLDER_EXCEPTION, + "exitMessage cannot contain placeholder [" + PLACEHOLDER_EXCEPTION + "]"); + this.exitMessage = exitMessage; + } + + /** + * Set the template used for method exception log messages. + * This template can contain any of the following placeholders: + *
      + *
    • $[targetClassName]
    • + *
    • $[targetClassShortName]
    • + *
    • $[argumentTypes]
    • + *
    • $[arguments]
    • + *
    • $[exception]
    • + *
    + */ + public void setExceptionMessage(String exceptionMessage) { + Assert.hasText(exceptionMessage, "'exceptionMessage' must not be empty"); + checkForInvalidPlaceholders(exceptionMessage); + Assert.doesNotContain(exceptionMessage, PLACEHOLDER_RETURN_VALUE, + "exceptionMessage cannot contain placeholder [" + PLACEHOLDER_RETURN_VALUE + "]"); + Assert.doesNotContain(exceptionMessage, PLACEHOLDER_INVOCATION_TIME, + "exceptionMessage cannot contain placeholder [" + PLACEHOLDER_INVOCATION_TIME + "]"); + this.exceptionMessage = exceptionMessage; + } + + + /** + * Writes a log message before the invocation based on the value of enterMessage. + * If the invocation succeeds, then a log message is written on exit based on the value + * exitMessage. If an exception occurs during invocation, then a message is + * written based on the value of exceptionMessage. + * @see #setEnterMessage + * @see #setExitMessage + * @see #setExceptionMessage + */ + protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable { + String name = invocation.getMethod().getDeclaringClass().getName() + "." + invocation.getMethod().getName(); + StopWatch stopWatch = new StopWatch(name); + Object returnValue = null; + boolean exitThroughException = false; + try { + stopWatch.start(name); + writeToLog(logger, + replacePlaceholders(this.enterMessage, invocation, null, null, -1)); + returnValue = invocation.proceed(); + return returnValue; + } + catch (Throwable ex) { + if(stopWatch.isRunning()) { + stopWatch.stop(); + } + exitThroughException = true; + writeToLog(logger, + replacePlaceholders(this.exceptionMessage, invocation, null, ex, stopWatch.getTotalTimeMillis()), ex); + throw ex; + } + finally { + if (!exitThroughException) { + if(stopWatch.isRunning()) { + stopWatch.stop(); + } + writeToLog(logger, + replacePlaceholders(this.exitMessage, invocation, returnValue, null, stopWatch.getTotalTimeMillis())); + } + } + } + + /** + * Writes the supplied message to the supplied Log instance. + * @see #writeToLog(org.apache.commons.logging.Log, String, Throwable) + */ + protected void writeToLog(Log logger, String message) { + writeToLog(logger, message, null); + } + + /** + * Writes the supplied message and {@link Throwable} to the + * supplied Log instance. By default messages are written + * at TRACE level. Sub-classes can override this method + * to control which level the message is written at. + */ + protected void writeToLog(Log logger, String message, Throwable ex) { + if (ex != null) { + logger.trace(message, ex); + } + else { + logger.trace(message); + } + } + + /** + * Replace the placeholders in the given message with the supplied values, + * or values derived from those supplied. + * @param message the message template containing the placeholders to be replaced + * @param methodInvocation the MethodInvocation being logged. + * Used to derive values for all placeholders except $[exception] + * and $[returnValue]. + * @param returnValue any value returned by the invocation. + * Used to replace the $[returnValue] placeholder. May be null. + * @param throwable any Throwable raised during the invocation. + * The value of Throwable.toString() is replaced for the + * $[exception] placeholder. May be null. + * @param invocationTime the value to write in place of the + * $[invocationTime] placeholder + * @return the formatted output to write to the log + */ + protected String replacePlaceholders(String message, MethodInvocation methodInvocation, + Object returnValue, Throwable throwable, long invocationTime) { + + Matcher matcher = PATTERN.matcher(message); + + StringBuffer output = new StringBuffer(); + while (matcher.find()) { + String match = matcher.group(); + if (PLACEHOLDER_METHOD_NAME.equals(match)) { + matcher.appendReplacement(output, escape(methodInvocation.getMethod().getName())); + } + else if (PLACEHOLDER_TARGET_CLASS_NAME.equals(match)) { + String className = getClassForLogging(methodInvocation.getThis()).getName(); + matcher.appendReplacement(output, escape(className)); + } + else if (PLACEHOLDER_TARGET_CLASS_SHORT_NAME.equals(match)) { + String shortName = ClassUtils.getShortName(getClassForLogging(methodInvocation.getThis())); + matcher.appendReplacement(output, escape(shortName)); + } + else if (PLACEHOLDER_ARGUMENTS.equals(match)) { + matcher.appendReplacement(output, escape(StringUtils.arrayToCommaDelimitedString(methodInvocation.getArguments()))); + } + else if (PLACEHOLDER_ARGUMENT_TYPES.equals(match)) { + appendArgumentTypes(methodInvocation, matcher, output); + } + else if (PLACEHOLDER_RETURN_VALUE.equals(match)) { + appendReturnValue(methodInvocation, matcher, output, returnValue); + } + else if (throwable != null && PLACEHOLDER_EXCEPTION.equals(match)) { + matcher.appendReplacement(output, escape(throwable.toString())); + } + else if (PLACEHOLDER_INVOCATION_TIME.equals(match)) { + matcher.appendReplacement(output, Long.toString(invocationTime)); + } + else { + // Should not happen since placeholders are checked earlier. + throw new IllegalArgumentException("Unknown placeholder [" + match + "]"); + } + } + matcher.appendTail(output); + + return output.toString(); + } + + /** + * Adds the String representation of the method return value + * to the supplied StringBuffer. Correctly handles + * null and void results. + * @param methodInvocation the MethodInvocation that returned the value + * @param matcher the Matcher containing the matched placeholder + * @param output the StringBuffer to write output to + * @param returnValue the value returned by the method invocation. + */ + private void appendReturnValue( + MethodInvocation methodInvocation, Matcher matcher, StringBuffer output, Object returnValue) { + + if (methodInvocation.getMethod().getReturnType() == void.class) { + matcher.appendReplacement(output, "void"); + } + else if (returnValue == null) { + matcher.appendReplacement(output, "null"); + } + else { + matcher.appendReplacement(output, escape(returnValue.toString())); + } + } + + /** + * Adds a comma-separated list of the short Class names of the + * method argument types to the output. For example, if a method has signature + * put(java.lang.String, java.lang.Object) then the value returned + * will be String, Object. + * @param methodInvocation the MethodInvocation being logged. + * Arguments will be retrieved from the corresponding Method. + * @param matcher the Matcher containing the state of the output + * @param output the StringBuffer containing the output + */ + private void appendArgumentTypes(MethodInvocation methodInvocation, Matcher matcher, StringBuffer output) { + Class[] argumentTypes = methodInvocation.getMethod().getParameterTypes(); + String[] argumentTypeShortNames = new String[argumentTypes.length]; + for (int i = 0; i < argumentTypeShortNames.length; i++) { + argumentTypeShortNames[i] = ClassUtils.getShortName(argumentTypes[i]); + } + matcher.appendReplacement(output, escape(StringUtils.arrayToCommaDelimitedString(argumentTypeShortNames))); + } + + /** + * Checks to see if the supplied String has any placeholders + * that are not specified as constants on this class and throws an + * IllegalArgumentException if so. + */ + private void checkForInvalidPlaceholders(String message) throws IllegalArgumentException { + Matcher matcher = PATTERN.matcher(message); + while (matcher.find()) { + String match = matcher.group(); + if (!ALLOWED_PLACEHOLDERS.contains(match)) { + throw new IllegalArgumentException("Placeholder [" + match + "] is not valid"); + } + } + } + + /** + * Replaces $ in inner class names with \$. + *

    This code is equivalent to JDK 1.5's quoteReplacement + * method in the Matcher class itself. We're keeping our own version + * here for JDK 1.4 compliance reasons only. + */ + private String escape(String input) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < input.length(); i++) { + char c = input.charAt(i); + if (c == '\\') { + sb.append("\\\\"); + } + else if (c == '$') { + sb.append("\\$"); + } + else { + sb.append(c); + } + } + return sb.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/interceptor/DebugInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/interceptor/DebugInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/interceptor/DebugInterceptor.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.interceptor; + +import org.aopalliance.intercept.MethodInvocation; + +/** + * AOP Alliance MethodInterceptor that can be introduced in a chain + * to display verbose information about intercepted invocations to the logger. + * + *

    Logs full invocation details on method entry and method exit, + * including invocation arguments and invocation count. This is only + * intended for debugging purposes; use SimpleTraceInterceptor + * or CustomizableTraceInterceptor for pure tracing purposes. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see SimpleTraceInterceptor + * @see CustomizableTraceInterceptor + */ +public class DebugInterceptor extends SimpleTraceInterceptor { + + private volatile long count; + + + /** + * Create a new DebugInterceptor with a static logger. + */ + public DebugInterceptor() { + } + + /** + * Create a new DebugInterceptor with dynamic or static logger, + * according to the given flag. + * @param useDynamicLogger whether to use a dynamic logger or a static logger + * @see #setUseDynamicLogger + */ + public DebugInterceptor(boolean useDynamicLogger) { + setUseDynamicLogger(useDynamicLogger); + } + + + public Object invoke(MethodInvocation invocation) throws Throwable { + synchronized (this) { + this.count++; + } + return super.invoke(invocation); + } + + protected String getInvocationDescription(MethodInvocation invocation) { + return invocation + "; count=" + this.count; + } + + + /** + * Return the number of times this interceptor has been invoked. + */ + public long getCount() { + return this.count; + } + + /** + * Reset the invocation count to zero. + */ + public synchronized void resetCount() { + this.count = 0; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/interceptor/ExposeBeanNameAdvisors.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/interceptor/ExposeBeanNameAdvisors.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/interceptor/ExposeBeanNameAdvisors.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,148 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.interceptor; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.aop.Advisor; +import org.springframework.aop.ProxyMethodInvocation; +import org.springframework.aop.support.DefaultIntroductionAdvisor; +import org.springframework.aop.support.DefaultPointcutAdvisor; +import org.springframework.aop.support.DelegatingIntroductionInterceptor; +import org.springframework.beans.factory.NamedBean; + +/** + * Convenient methods for creating advisors that may be used when autoproxying beans + * created with the Spring IoC container, binding the bean name to the current + * invocation. May support a bean() pointcut designator with AspectJ. + * + *

    Typically used in Spring auto-proxying, where the bean name is known + * at proxy creation time. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see org.springframework.beans.factory.NamedBean + */ +public abstract class ExposeBeanNameAdvisors { + + /** + * Binding for the bean name of the bean which is currently being invoked + * in the ReflectiveMethodInvocation userAttributes Map. + */ + private static final String BEAN_NAME_ATTRIBUTE = ExposeBeanNameAdvisors.class.getName() + ".beanName"; + + + /** + * Find the bean name for the current invocation. Assumes that an ExposeBeanNameAdvisor + * has been included in the interceptor chain, and that the invocation is exposed + * with ExposeInvocationInterceptor. + * @return the bean name (never null) + * @throws IllegalStateException if the bean name has not been exposed + */ + public static String getBeanName() throws IllegalStateException { + return getBeanName(ExposeInvocationInterceptor.currentInvocation()); + } + + /** + * Find the bean name for the given invocation. Assumes that an ExposeBeanNameAdvisor + * has been included in the interceptor chain. + * @param mi MethodInvocation that should contain the bean name as an attribute + * @return the bean name (never null) + * @throws IllegalStateException if the bean name has not been exposed + */ + public static String getBeanName(MethodInvocation mi) throws IllegalStateException { + if (!(mi instanceof ProxyMethodInvocation)) { + throw new IllegalArgumentException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi); + } + ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi; + String beanName = (String) pmi.getUserAttribute(BEAN_NAME_ATTRIBUTE); + if (beanName == null) { + throw new IllegalStateException("Cannot get bean name; not set on MethodInvocation: " + mi); + } + return beanName; + } + + /** + * Create a new advisor that will expose the given bean name, + * with no introduction + * @param beanName bean name to expose + */ + public static Advisor createAdvisorWithoutIntroduction(String beanName) { + return new DefaultPointcutAdvisor(new ExposeBeanNameInterceptor(beanName)); + } + + /** + * Create a new advisor that will expose the given bean name, introducing + * the NamedBean interface to make the bean name accessible without forcing + * the target object to be aware of this Spring IoC concept. + * @param beanName the bean name to expose + */ + public static Advisor createAdvisorIntroducingNamedBean(String beanName) { + return new DefaultIntroductionAdvisor(new ExposeBeanNameIntroduction(beanName)); + } + + + /** + * Interceptor that exposes the specified bean name as invocation attribute. + */ + private static class ExposeBeanNameInterceptor implements MethodInterceptor { + + private final String beanName; + + public ExposeBeanNameInterceptor(String beanName) { + this.beanName = beanName; + } + + public Object invoke(MethodInvocation mi) throws Throwable { + if (!(mi instanceof ProxyMethodInvocation)) { + throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi); + } + ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi; + pmi.setUserAttribute(BEAN_NAME_ATTRIBUTE, beanName); + return mi.proceed(); + } + } + + + /** + * Introduction that exposes the specified bean name as invocation attribute. + */ + private static class ExposeBeanNameIntroduction extends DelegatingIntroductionInterceptor implements NamedBean { + + private final String beanName; + + public ExposeBeanNameIntroduction(String beanName) { + this.beanName = beanName; + } + + public Object invoke(MethodInvocation mi) throws Throwable { + if (!(mi instanceof ProxyMethodInvocation)) { + throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi); + } + ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi; + pmi.setUserAttribute(BEAN_NAME_ATTRIBUTE, beanName); + return super.invoke(mi); + } + + public String getBeanName() { + return this.beanName; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/interceptor/ExposeInvocationInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/interceptor/ExposeInvocationInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/interceptor/ExposeInvocationInterceptor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,105 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.interceptor; + +import java.io.Serializable; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.aop.Advisor; +import org.springframework.aop.support.DefaultPointcutAdvisor; +import org.springframework.core.NamedThreadLocal; + +/** + * Interceptor that exposes the current {@link org.aopalliance.intercept.MethodInvocation} + * as a thread-local object. We occasionally need to do this; for example, when a pointcut + * (e.g. an AspectJ expression pointcut) needs to know the full invocation context. + * + *

    Don't use this interceptor unless this is really necessary. Target objects should + * not normally know about Spring AOP, as this creates a dependency on Spring API. + * Target objects should be plain POJOs as far as possible. + * + *

    If used, this interceptor will normally be the first in the interceptor chain. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public class ExposeInvocationInterceptor implements MethodInterceptor, Serializable { + + /** Singleton instance of this class */ + public static final ExposeInvocationInterceptor INSTANCE = new ExposeInvocationInterceptor(); + + /** + * Singleton advisor for this class. Use in preference to INSTANCE when using + * Spring AOP, as it prevents the need to create a new Advisor to wrap the instance. + */ + public static final Advisor ADVISOR = new DefaultPointcutAdvisor(INSTANCE) { + public int getOrder() { + return Integer.MIN_VALUE; + } + public String toString() { + return ExposeInvocationInterceptor.class.getName() +".ADVISOR"; + } + }; + + private static final ThreadLocal invocation = new NamedThreadLocal("Current AOP method invocation"); + + + /** + * Return the AOP Alliance MethodInvocation object associated with the current invocation. + * @return the invocation object associated with the current invocation + * @throws IllegalStateException if there is no AOP invocation in progress, + * or if the ExposeInvocationInterceptor was not added to this interceptor chain + */ + public static MethodInvocation currentInvocation() throws IllegalStateException { + MethodInvocation mi = (MethodInvocation) invocation.get(); + if (mi == null) + throw new IllegalStateException( + "No MethodInvocation found: Check that an AOP invocation is in progress, " + + "and that the ExposeInvocationInterceptor is in the interceptor chain."); + return mi; + } + + + /** + * Ensures that only the canonical instance can be created. + */ + private ExposeInvocationInterceptor() { + } + + public Object invoke(MethodInvocation mi) throws Throwable { + Object old = invocation.get(); + invocation.set(mi); + try { + return mi.proceed(); + } + finally { + invocation.set(old); + } + } + + /** + * Required to support serialization. Replaces with canonical instance + * on deserialization, protecting Singleton pattern. + *

    Alternative to overriding the equals method. + */ + private Object readResolve() { + return INSTANCE; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/interceptor/JamonPerformanceMonitorInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/interceptor/JamonPerformanceMonitorInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/interceptor/JamonPerformanceMonitorInterceptor.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,115 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.interceptor; + +import com.jamonapi.Monitor; +import com.jamonapi.MonitorFactory; +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.logging.Log; + +/** + * Performance monitor interceptor that uses JAMon library + * to perform the performance measurement on the intercepted method + * and output the stats. + * + *

    This code is inspired by Thierry Templier's blog. + * + * @author Dmitriy Kopylenko + * @author Juergen Hoeller + * @author Rob Harrop + * @since 1.1.3 + * @see com.jamonapi.MonitorFactory + * @see PerformanceMonitorInterceptor + */ +public class JamonPerformanceMonitorInterceptor extends AbstractMonitoringInterceptor { + + private boolean trackAllInvocations = false; + + + /** + * Create a new JamonPerformanceMonitorInterceptor with a static logger. + */ + public JamonPerformanceMonitorInterceptor() { + } + + /** + * Create a new JamonPerformanceMonitorInterceptor with a dynamic or static logger, + * according to the given flag. + * @param useDynamicLogger whether to use a dynamic logger or a static logger + * @see #setUseDynamicLogger + */ + public JamonPerformanceMonitorInterceptor(boolean useDynamicLogger) { + setUseDynamicLogger(useDynamicLogger); + } + + /** + * Create a new JamonPerformanceMonitorInterceptor with a dynamic or static logger, + * according to the given flag. + * @param useDynamicLogger whether to use a dynamic logger or a static logger + * @param trackAllInvocations whether to track all invocations that go through + * this interceptor, or just invocations with trace logging enabled + * @see #setUseDynamicLogger + */ + public JamonPerformanceMonitorInterceptor(boolean useDynamicLogger, boolean trackAllInvocations) { + setUseDynamicLogger(useDynamicLogger); + setTrackAllInvocations(trackAllInvocations); + } + + + /** + * Set whether to track all invocations that go through this interceptor, + * or just invocations with trace logging enabled. + *

    Default is "false": Only invocations with trace logging enabled will + * be monitored. Specify "true" to let JAMon track all invocations, + * gathering statistics even when trace logging is disabled. + */ + public void setTrackAllInvocations(boolean trackAllInvocations) { + this.trackAllInvocations = trackAllInvocations; + } + + + /** + * Always applies the interceptor if the "trackAllInvocations" flag has been set; + * else just kicks in if the log is enabled. + * @see #setTrackAllInvocations + * @see #isLogEnabled + */ + protected boolean isInterceptorEnabled(MethodInvocation invocation, Log logger) { + return (this.trackAllInvocations || isLogEnabled(logger)); + } + + /** + * Wraps the invocation with a JAMon Monitor and writes the current + * performance statistics to the log (if enabled). + * @see com.jamonapi.MonitorFactory#start + * @see com.jamonapi.Monitor#stop + */ + protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable { + String name = createInvocationTraceName(invocation); + Monitor monitor = MonitorFactory.start(name); + try { + return invocation.proceed(); + } + finally { + monitor.stop(); + if (!this.trackAllInvocations || isLogEnabled(logger)) { + logger.trace("JAMon performance statistics for method [" + name + "]:\n" + monitor); + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/interceptor/PerformanceMonitorInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/interceptor/PerformanceMonitorInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/interceptor/PerformanceMonitorInterceptor.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.interceptor; + +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.logging.Log; + +import org.springframework.util.StopWatch; + +/** + * Simple AOP Alliance MethodInterceptor for performance monitoring. + * This interceptor has no effect on the intercepted method call. + * + *

    Uses a StopWatch for the actual performance measuring. + * + * @author Rod Johnson + * @author Dmitriy Kopylenko + * @author Rob Harrop + * @see org.springframework.util.StopWatch + * @see JamonPerformanceMonitorInterceptor + */ +public class PerformanceMonitorInterceptor extends AbstractMonitoringInterceptor { + + /** + * Create a new PerformanceMonitorInterceptor with a static logger. + */ + public PerformanceMonitorInterceptor() { + } + + /** + * Create a new PerformanceMonitorInterceptor with a dynamic or static logger, + * according to the given flag. + * @param useDynamicLogger whether to use a dynamic logger or a static logger + * @see #setUseDynamicLogger + */ + public PerformanceMonitorInterceptor(boolean useDynamicLogger) { + setUseDynamicLogger(useDynamicLogger); + } + + + protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable { + String name = createInvocationTraceName(invocation); + StopWatch stopWatch = new StopWatch(name); + stopWatch.start(name); + try { + return invocation.proceed(); + } + finally { + stopWatch.stop(); + logger.trace(stopWatch.shortSummary()); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/interceptor/SimpleTraceInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/interceptor/SimpleTraceInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/interceptor/SimpleTraceInterceptor.java 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.interceptor; + +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.logging.Log; + +/** + * Simple AOP Alliance MethodInterceptor that can be introduced + * in a chain to display verbose trace information about intercepted method + * invocations, with method entry and method exit info. + * + *

    Consider using CustomizableTraceInterceptor for more + * advanced needs. + * + * @author Dmitriy Kopylenko + * @author Juergen Hoeller + * @since 1.2 + * @see CustomizableTraceInterceptor + */ +public class SimpleTraceInterceptor extends AbstractTraceInterceptor { + + /** + * Create a new SimpleTraceInterceptor with a static logger. + */ + public SimpleTraceInterceptor() { + } + + /** + * Create a new SimpleTraceInterceptor with dynamic or static logger, + * according to the given flag. + * @param useDynamicLogger whether to use a dynamic logger or a static logger + * @see #setUseDynamicLogger + */ + public SimpleTraceInterceptor(boolean useDynamicLogger) { + setUseDynamicLogger(useDynamicLogger); + } + + + protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable { + String invocationDescription = getInvocationDescription(invocation); + logger.trace("Entering " + invocationDescription); + try { + Object rval = invocation.proceed(); + logger.trace("Exiting " + invocationDescription); + return rval; + } + catch (Throwable ex) { + logger.trace("Exception thrown in " + invocationDescription, ex); + throw ex; + } + } + + /** + * Return a description for the given method invocation. + * @param invocation the invocation to describe + * @return the description + */ + protected String getInvocationDescription(MethodInvocation invocation) { + return "method '" + invocation.getMethod().getName() + "' of class [" + + invocation.getThis().getClass().getName() + "]"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/interceptor/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/interceptor/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/interceptor/package.html 17 Aug 2012 15:11:45 -0000 1.1 @@ -0,0 +1,9 @@ + + + +Provides miscellaneous interceptor implementations. +More specific interceptors can be found in corresponding +functionality packages, like "transaction" and "orm". + + + Index: 3rdParty_sources/spring/org/springframework/aop/scope/DefaultScopedObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/scope/DefaultScopedObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/scope/DefaultScopedObject.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.scope; + +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.util.Assert; + +/** + * Default implementation of the {@link ScopedObject} interface. + * + *

    Simply delegates the calls to the underlying + * {@link ConfigurableBeanFactory bean factory} + * ({@link ConfigurableBeanFactory#getBean(String)}/ + * {@link ConfigurableBeanFactory#destroyScopedBean(String)}). + * + * @author Juergen Hoeller + * @since 2.0 + * @see org.springframework.beans.factory.BeanFactory#getBean + * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#destroyScopedBean + */ +public class DefaultScopedObject implements ScopedObject { + + private final ConfigurableBeanFactory beanFactory; + + private final String targetBeanName; + + + /** + * Creates a new instance of the {@link DefaultScopedObject} class. + * @param beanFactory the {@link ConfigurableBeanFactory} that holds the scoped target object + * @param targetBeanName the name of the target bean + * @throws IllegalArgumentException if either of the parameters is null; or + * if the targetBeanName consists wholly of whitespace + */ + public DefaultScopedObject(ConfigurableBeanFactory beanFactory, String targetBeanName) { + Assert.notNull(beanFactory, "BeanFactory must not be null"); + Assert.hasText(targetBeanName, "'targetBeanName' must not be empty"); + this.beanFactory = beanFactory; + this.targetBeanName = targetBeanName; + } + + + public Object getTargetObject() { + return this.beanFactory.getBean(this.targetBeanName); + } + + public void removeFromScope() { + this.beanFactory.destroyScopedBean(this.targetBeanName); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/scope/ScopedObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/scope/ScopedObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/scope/ScopedObject.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.scope; + +import org.springframework.aop.RawTargetAccess; + +/** + * An AOP introduction interface for scoped objects. + * + *

    Objects created from the {@link ScopedProxyFactoryBean} can be cast + * to this interface, enabling access to the raw target object + * and programmatic removal of the target object. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see ScopedProxyFactoryBean + */ +public interface ScopedObject extends RawTargetAccess { + + /** + * Return the current target object behind this scoped object proxy, + * in its raw form (as stored in the target scope). + *

    The raw target object can for example be passed to persistence + * providers which would not be able to handle the scoped proxy object. + * @return the current target object behind this scoped object proxy + */ + Object getTargetObject(); + + /** + * Remove this object from its target scope, for example from + * the backing session. + *

    Note that no further calls may be made to the scoped object + * afterwards (at least within the current thread, that is, with + * the exact same target object in the target scope). + */ + void removeFromScope(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/scope/ScopedProxyFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/scope/ScopedProxyFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/scope/ScopedProxyFactoryBean.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,134 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.scope; + +import java.lang.reflect.Modifier; + +import org.springframework.aop.framework.AopInfrastructureBean; +import org.springframework.aop.framework.ProxyConfig; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.aop.support.DelegatingIntroductionInterceptor; +import org.springframework.aop.target.SimpleBeanTargetSource; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.FactoryBeanNotInitializedException; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.util.ClassUtils; + +/** + * Convenient proxy factory bean for scoped objects. + * + *

    Proxies created using this factory bean are thread-safe singletons + * and may be injected into shared objects, with transparent scoping behavior. + * + *

    Proxies returned by this class implement the {@link ScopedObject} interface. + * This presently allows for removing the corresponding object from the scope, + * seamlessly creating a new instance in the scope on next access. + * + *

    Please note that the proxies created by this factory are + * class-based proxies by default. This can be customized + * through switching the "proxyTargetClass" property to "false". + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see #setProxyTargetClass + */ +public class ScopedProxyFactoryBean extends ProxyConfig implements FactoryBean, BeanFactoryAware { + + /** The TargetSource that manages scoping */ + private final SimpleBeanTargetSource scopedTargetSource = new SimpleBeanTargetSource(); + + /** The name of the target bean */ + private String targetBeanName; + + /** The cached singleton proxy */ + private Object proxy; + + + /** + * Create a new ScopedProxyFactoryBean instance. + */ + public ScopedProxyFactoryBean() { + setProxyTargetClass(true); + } + + + /** + * Set the name of the bean that is to be scoped. + */ + public void setTargetBeanName(String targetBeanName) { + this.targetBeanName = targetBeanName; + this.scopedTargetSource.setTargetBeanName(targetBeanName); + } + + public void setBeanFactory(BeanFactory beanFactory) { + if (!(beanFactory instanceof ConfigurableBeanFactory)) { + throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory); + } + ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) beanFactory; + + this.scopedTargetSource.setBeanFactory(beanFactory); + + ProxyFactory pf = new ProxyFactory(); + pf.copyFrom(this); + pf.setTargetSource(this.scopedTargetSource); + + Class beanType = beanFactory.getType(this.targetBeanName); + if (beanType == null) { + throw new IllegalStateException("Cannot create scoped proxy for bean '" + this.targetBeanName + + "': Target type could not be determined at the time of proxy creation."); + } + if (!isProxyTargetClass() || beanType.isInterface() || Modifier.isPrivate(beanType.getModifiers())) { + pf.setInterfaces(ClassUtils.getAllInterfacesForClass(beanType, cbf.getBeanClassLoader())); + } + + // Add an introduction that implements only the methods on ScopedObject. + ScopedObject scopedObject = new DefaultScopedObject(cbf, this.scopedTargetSource.getTargetBeanName()); + pf.addAdvice(new DelegatingIntroductionInterceptor(scopedObject)); + + // Add the AopInfrastructureBean marker to indicate that the scoped proxy + // itself is not subject to auto-proxying! Only its target bean is. + pf.addInterface(AopInfrastructureBean.class); + + this.proxy = pf.getProxy(cbf.getBeanClassLoader()); + } + + + public Object getObject() { + if (this.proxy == null) { + throw new FactoryBeanNotInitializedException(); + } + return this.proxy; + } + + public Class getObjectType() { + if (this.proxy != null) { + return this.proxy.getClass(); + } + if (this.scopedTargetSource != null) { + return this.scopedTargetSource.getTargetClass(); + } + return null; + } + + public boolean isSingleton() { + return true; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/scope/ScopedProxyUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/scope/ScopedProxyUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/scope/ScopedProxyUtils.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,92 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.scope; + +import org.springframework.aop.framework.autoproxy.AutoProxyUtils; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.RootBeanDefinition; + +/** + * Utility class for creating a scoped proxy. + * Used by ScopedProxyBeanDefinitionDecorator and ClassPathBeanDefinitionScanner. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @author Rob Harrop + * @since 2.5 + */ +public abstract class ScopedProxyUtils { + + private static final String TARGET_NAME_PREFIX = "scopedTarget."; + + + /** + * Generates a scoped proxy for the supplied target bean, registering the target + * bean with an internal name and setting 'targetBeanName' on the scoped proxy. + * @param definition the original bean definition + * @param registry the bean definition registry + * @param proxyTargetClass whether to create a target class proxy + * @return the scoped proxy definition + */ + public static BeanDefinitionHolder createScopedProxy(BeanDefinitionHolder definition, + BeanDefinitionRegistry registry, boolean proxyTargetClass) { + + String originalBeanName = definition.getBeanName(); + BeanDefinition targetDefinition = definition.getBeanDefinition(); + + // Create a scoped proxy definition for the original bean name, + // "hiding" the target bean in an internal target definition. + RootBeanDefinition scopedProxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class); + scopedProxyDefinition.setOriginatingBeanDefinition(definition.getBeanDefinition()); + scopedProxyDefinition.setSource(definition.getSource()); + scopedProxyDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + + String targetBeanName = getTargetBeanName(originalBeanName); + scopedProxyDefinition.getPropertyValues().addPropertyValue("targetBeanName", targetBeanName); + + if (proxyTargetClass) { + targetDefinition.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); + // ScopedFactoryBean's "proxyTargetClass" default is TRUE, so we don't need to set it explicitly here. + } + else { + scopedProxyDefinition.getPropertyValues().addPropertyValue("proxyTargetClass", Boolean.FALSE); + } + + scopedProxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate()); + // The target bean should be ignored in favor of the scoped proxy. + targetDefinition.setAutowireCandidate(false); + + // Register the target bean as separate bean in the factory. + registry.registerBeanDefinition(targetBeanName, targetDefinition); + + // Return the scoped proxy definition as primary bean definition + // (potentially an inner bean). + return new BeanDefinitionHolder(scopedProxyDefinition, originalBeanName, definition.getAliases()); + } + + /** + * Generates the bean name that is used within the scoped proxy to reference the target bean. + * @param originalBeanName the original name of bean + * @return the generated bean to be used to reference the target bean + */ + public static String getTargetBeanName(String originalBeanName) { + return TARGET_NAME_PREFIX + originalBeanName; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/scope/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/scope/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/scope/package.html 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,7 @@ + + + +Support for AOP-based scoping of target objects, with configurable backend. + + + Index: 3rdParty_sources/spring/org/springframework/aop/support/AbstractBeanFactoryPointcutAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/AbstractBeanFactoryPointcutAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/AbstractBeanFactoryPointcutAdvisor.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import org.aopalliance.aop.Advice; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.util.Assert; + +/** + * Abstract BeanFactory-based PointcutAdvisor that allows for any Advice + * to be configured as reference to an Advice bean in a BeanFactory. + * + *

    Specifying the name of an advice bean instead of the advice object itself + * (if running within a BeanFactory) increases loose coupling at initialization time, + * in order to not initialize the advice object until the pointcut actually matches. + * + * @author Juergen Hoeller + * @since 2.0.2 + * @see #setAdviceBeanName + * @see DefaultBeanFactoryPointcutAdvisor + */ +public abstract class AbstractBeanFactoryPointcutAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware { + + private String adviceBeanName; + + private BeanFactory beanFactory; + + private Advice advice; + + private final Object adviceMonitor = new Object(); + + + /** + * Specify the name of the advice bean that this advisor should refer to. + *

    An instance of the specified bean will be obtained on first access + * of this advisor's advice. This advisor will only ever obtain at most one + * single instance of the advice bean, caching the instance for the lifetime + * of the advisor. + * @see #getAdvice() + */ + public void setAdviceBeanName(String adviceBeanName) { + this.adviceBeanName = adviceBeanName; + } + + /** + * Return the name of the advice bean that this advisor refers to, if any. + */ + public String getAdviceBeanName() { + return this.adviceBeanName; + } + + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + + + public Advice getAdvice() { + synchronized (this.adviceMonitor) { + if (this.advice == null && this.adviceBeanName != null) { + Assert.state(this.beanFactory != null, "BeanFactory must be set to resolve 'adviceBeanName'"); + this.advice = (Advice) this.beanFactory.getBean(this.adviceBeanName, Advice.class); + } + return this.advice; + } + } + + public String toString() { + return getClass().getName() + ": advice bean '" + getAdviceBeanName() + "'"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/AbstractExpressionPointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/AbstractExpressionPointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/AbstractExpressionPointcut.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; + +/** + * Abstract superclass for expression pointcuts, + * offering location and expression properties. + * + * @author Rod Johnson + * @author Rob Harrop + * @since 2.0 + * @see #setLocation + * @see #setExpression + */ +public abstract class AbstractExpressionPointcut implements ExpressionPointcut, Serializable { + + private String location; + + private String expression; + + + /** + * Set the location for debugging. + */ + public void setLocation(String location) { + this.location = location; + } + + /** + * Return location information about the pointcut expression + * if available. This is useful in debugging. + * @return location information as a human-readable String, + * or null if none is available + */ + public String getLocation() { + return this.location; + } + + public void setExpression(String expression) { + this.expression = expression; + try { + onSetExpression(expression); + } + catch (IllegalArgumentException ex) { + // Fill in location information if possible. + if (this.location != null) { + throw new IllegalArgumentException("Invalid expression at location [" + this.location + "]: " + ex); + } + else { + throw ex; + } + } + } + + /** + * Called when a new pointcut expression is set. + * The expression should be parsed at this point if possible. + *

    This implementation is empty. + * @param expression expression to set + * @throws IllegalArgumentException if the expression is invalid + * @see #setExpression + */ + protected void onSetExpression(String expression) throws IllegalArgumentException { + } + + /** + * Return this pointcut's expression. + */ + public String getExpression() { + return this.expression; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/AbstractGenericPointcutAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/AbstractGenericPointcutAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/AbstractGenericPointcutAdvisor.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import org.aopalliance.aop.Advice; + +/** + * Abstract generic PointcutAdvisor that allows for any Advice to be configured. + * + * @author Juergen Hoeller + * @since 2.0 + * @see #setAdvice + * @see DefaultPointcutAdvisor + */ +public abstract class AbstractGenericPointcutAdvisor extends AbstractPointcutAdvisor { + + private Advice advice; + + + /** + * Specify the advice that this advisor should apply. + */ + public void setAdvice(Advice advice) { + this.advice = advice; + } + + public Advice getAdvice() { + return this.advice; + } + + + public String toString() { + return getClass().getName() + ": advice [" + getAdvice() + "]"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/AbstractPointcutAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/AbstractPointcutAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/AbstractPointcutAdvisor.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; + +import org.springframework.aop.PointcutAdvisor; +import org.springframework.core.Ordered; +import org.springframework.util.ObjectUtils; + +/** + * Abstract base class for {@link org.springframework.aop.PointcutAdvisor} + * implementations. Can be subclassed for returning a specific pointcut/advice + * or a freely configurable pointcut/advice. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 1.1.2 + * @see AbstractGenericPointcutAdvisor + */ +public abstract class AbstractPointcutAdvisor implements PointcutAdvisor, Ordered, Serializable { + + private int order = Ordered.LOWEST_PRECEDENCE; + + + public void setOrder(int order) { + this.order = order; + } + + public int getOrder() { + return this.order; + } + + public boolean isPerInstance() { + return true; + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof PointcutAdvisor)) { + return false; + } + PointcutAdvisor otherAdvisor = (PointcutAdvisor) other; + return (ObjectUtils.nullSafeEquals(getAdvice(), otherAdvisor.getAdvice()) && + ObjectUtils.nullSafeEquals(getPointcut(), otherAdvisor.getPointcut())); + } + + public int hashCode() { + return PointcutAdvisor.class.hashCode(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/AbstractRegexpMethodPointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/AbstractRegexpMethodPointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/AbstractRegexpMethodPointcut.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,228 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.Arrays; + +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +/** + * Abstract base regular expression pointcut bean. JavaBean properties are: + *

      + *
    • pattern: regular expression for the fully-qualified method names to match. + * The exact regexp syntax will depend on the subclass (e.g. Perl5 regular expressions) + *
    • patterns: alternative property taking a String array of patterns. The result will + * be the union of these patterns. + *
    + * + *

    Note: the regular expressions must be a match. For example, + * .*get.* will match com.mycom.Foo.getBar(). + * get.* will not. + * + *

    This base class is serializable. Subclasses should declare all fields transient + * - the initPatternRepresentation method in this class will be invoked again on the + * client side on deserialization. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + * @since 1.1 + * @see JdkRegexpMethodPointcut + */ +public abstract class AbstractRegexpMethodPointcut extends StaticMethodMatcherPointcut + implements Serializable { + + /** Regular expressions to match */ + private String[] patterns = new String[0]; + + /** Regaular expressions not to match */ + private String[] excludedPatterns = new String[0]; + + + /** + * Convenience method when we have only a single pattern. + * Use either this method or {@link #setPatterns}, not both. + * @see #setPatterns + */ + public void setPattern(String pattern) { + setPatterns(new String[] {pattern}); + } + + /** + * Set the regular expressions defining methods to match. + * Matching will be the union of all these; if any match, + * the pointcut matches. + */ + public void setPatterns(String[] patterns) { + Assert.notEmpty(patterns, "'patterns' must not be empty"); + this.patterns = new String[patterns.length]; + for (int i = 0; i < patterns.length; i++) { + this.patterns[i] = StringUtils.trimWhitespace(patterns[i]); + } + initPatternRepresentation(this.patterns); + } + + /** + * Return the regular expressions for method matching. + */ + public String[] getPatterns() { + return this.patterns; + } + + /** + * Convenience method when we have only a single exclusion pattern. + * Use either this method or {@link #setExcludedPatterns}, not both. + * @see #setExcludedPatterns + */ + public void setExcludedPattern(String excludedPattern) { + setExcludedPatterns(new String[] {excludedPattern}); + } + + /** + * Set the regular expressions defining methods to match for exclusion. + * Matching will be the union of all these; if any match, + * the pointcut matches. + */ + public void setExcludedPatterns(String[] excludedPatterns) { + Assert.notEmpty(excludedPatterns, "'excludedPatterns' must not be empty"); + this.excludedPatterns = new String[excludedPatterns.length]; + for (int i = 0; i < excludedPatterns.length; i++) { + this.excludedPatterns[i] = StringUtils.trimWhitespace(excludedPatterns[i]); + } + initExcludedPatternRepresentation(this.excludedPatterns); + } + + /** + * Returns the regular expressions for exclusion matching. + */ + public String[] getExcludedPatterns() { + return this.excludedPatterns; + } + + + /** + * Try to match the regular expression against the fully qualified name + * of the target class as well as against the method's declaring class, + * plus the name of the method. + */ + public boolean matches(Method method, Class targetClass) { + return ((targetClass != null && matchesPattern(targetClass.getName() + "." + method.getName())) || + matchesPattern(method.getDeclaringClass().getName() + "." + method.getName())); + } + + /** + * Match the specified candidate against the configured patterns. + * @param signatureString "java.lang.Object.hashCode" style signature + * @return whether the candidate matches at least one of the specified patterns + */ + protected boolean matchesPattern(String signatureString) { + for (int i = 0; i < this.patterns.length; i++) { + boolean matched = matches(signatureString, i); + if (matched) { + for (int j = 0; j < this.excludedPatterns.length; j++) { + boolean excluded = matchesExclusion(signatureString, j); + if (excluded) { + return false; + } + } + return true; + } + } + return false; + } + + + /** + * Subclasses must implement this to initialize regexp pointcuts. + * Can be invoked multiple times. + *

    This method will be invoked from the setPatterns method, + * and also on deserialization. + * @param patterns the patterns to initialize + * @throws IllegalArgumentException in case of an invalid pattern + */ + protected abstract void initPatternRepresentation(String[] patterns) throws IllegalArgumentException; + + protected abstract void initExcludedPatternRepresentation(String[] excludedPatterns) throws IllegalArgumentException; + + /** + * Does the pattern at the given index match this string? + * @param pattern String pattern to match + * @param patternIndex index of pattern from 0 + * @return true if there is a match, else false. + */ + protected abstract boolean matches(String pattern, int patternIndex); + + /** + * Does the exclusion pattern at the given index match this string? + * @param pattern String pattern to match. + * @param patternIndex index of pattern starting from 0. + * @return true if there is a match, else false. + */ + protected abstract boolean matchesExclusion(String pattern, int patternIndex); + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AbstractRegexpMethodPointcut)) { + return false; + } + AbstractRegexpMethodPointcut otherPointcut = (AbstractRegexpMethodPointcut) other; + return (Arrays.equals(this.patterns, otherPointcut.patterns) && + Arrays.equals(this.excludedPatterns, otherPointcut.excludedPatterns)); + } + + public int hashCode() { + int result = 27; + for (int i = 0; i < this.patterns.length; i++) { + String pattern = this.patterns[i]; + result = 13 * result + pattern.hashCode(); + } + for (int i = 0; i < this.excludedPatterns.length; i++) { + String excludedPattern = this.excludedPatterns[i]; + result = 13 * result + excludedPattern.hashCode(); + } + return result; + } + + public String toString() { + return getClass().getName() + ": patterns " + ObjectUtils.nullSafeToString(this.patterns) + + ", excluded patterns " + ObjectUtils.nullSafeToString(this.excludedPatterns); + } + + + //--------------------------------------------------------------------- + // Serialization support + //--------------------------------------------------------------------- + + private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { + // Rely on default serialization; just initialize state after deserialization. + ois.defaultReadObject(); + + // Ask subclass to reinitialize. + initPatternRepresentation(this.patterns); + initExcludedPatternRepresentation(this.excludedPatterns); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/AopUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/AopUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/AopUtils.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,323 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.springframework.aop.Advisor; +import org.springframework.aop.AopInvocationException; +import org.springframework.aop.IntroductionAdvisor; +import org.springframework.aop.IntroductionAwareMethodMatcher; +import org.springframework.aop.MethodMatcher; +import org.springframework.aop.Pointcut; +import org.springframework.aop.PointcutAdvisor; +import org.springframework.aop.SpringProxy; +import org.springframework.aop.TargetClassAware; +import org.springframework.core.BridgeMethodResolver; +import org.springframework.core.JdkVersion; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; + +/** + * Utility methods for AOP support code. + * Mainly for internal use within Spring's AOP support. + * + *

    See {@link org.springframework.aop.framework.AopProxyUtils} for a + * collection of framework-specific AOP utility methods which depend + * on internals of Spring's AOP framework implementation. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + * @see org.springframework.aop.framework.AopProxyUtils + */ +public abstract class AopUtils { + + /** + * Check whether the given object is a JDK dynamic proxy or a CGLIB proxy. + * @param object the object to check + * @see #isJdkDynamicProxy + * @see #isCglibProxy + */ + public static boolean isAopProxy(Object object) { + return (object instanceof SpringProxy && + (Proxy.isProxyClass(object.getClass()) || isCglibProxyClass(object.getClass()))); + } + + /** + * Check whether the given object is a JDK dynamic proxy. + * @param object the object to check + * @see java.lang.reflect.Proxy#isProxyClass + */ + public static boolean isJdkDynamicProxy(Object object) { + return (object instanceof SpringProxy && Proxy.isProxyClass(object.getClass())); + } + + /** + * Check whether the given object is a CGLIB proxy. + * @param object the object to check + */ + public static boolean isCglibProxy(Object object) { + return (object instanceof SpringProxy && isCglibProxyClass(object.getClass())); + } + + /** + * Check whether the specified class is a CGLIB-generated class. + * @param clazz the class to check + */ + public static boolean isCglibProxyClass(Class clazz) { + return (clazz != null && clazz.getName().indexOf(ClassUtils.CGLIB_CLASS_SEPARATOR) != -1); + } + + /** + * Determine the target class of the given bean instance, + * which might be an AOP proxy. + *

    Returns the target class for an AOP proxy and the plain class else. + * @param candidate the instance to check (might be an AOP proxy) + * @return the target class (or the plain class of the given object as fallback) + * @see org.springframework.aop.TargetClassAware#getTargetClass() + */ + public static Class getTargetClass(Object candidate) { + Assert.notNull(candidate, "Candidate object must not be null"); + if (candidate instanceof TargetClassAware) { + return ((TargetClassAware) candidate).getTargetClass(); + } + if (isCglibProxyClass(candidate.getClass())) { + return candidate.getClass().getSuperclass(); + } + return candidate.getClass(); + } + + /** + * Determine whether the given method is an "equals" method. + * @see java.lang.Object#equals + */ + public static boolean isEqualsMethod(Method method) { + return ReflectionUtils.isEqualsMethod(method); + } + + /** + * Determine whether the given method is a "hashCode" method. + * @see java.lang.Object#hashCode + */ + public static boolean isHashCodeMethod(Method method) { + return ReflectionUtils.isHashCodeMethod(method); + } + + /** + * Determine whether the given method is a "toString" method. + * @see java.lang.Object#toString() + */ + public static boolean isToStringMethod(Method method) { + return ReflectionUtils.isToStringMethod(method); + } + + /** + * Determine whether the given method is a "finalize" method. + * @see java.lang.Object#finalize() + */ + public static boolean isFinalizeMethod(Method method) { + return (method != null && method.getName().equals("finalize") && + method.getParameterTypes().length == 0); + } + + /** + * Given a method, which may come from an interface, and a target class used + * in the current AOP invocation, find the corresponding target method if there + * is one. E.g. the method may be IFoo.bar() and the target class + * may be DefaultFoo. In this case, the method may be + * DefaultFoo.bar(). This enables attributes on that method to be found. + *

    NOTE: In contrast to {@link org.springframework.util.ClassUtils#getMostSpecificMethod}, + * this method resolves Java 5 bridge methods in order to retrieve attributes + * from the original method definition. + * @param method the method to be invoked, which may come from an interface + * @param targetClass the target class for the current invocation. + * May be null or may not even implement the method. + * @return the specific target method, or the original method if the + * targetClass doesn't implement it or is null + * @see org.springframework.util.ClassUtils#getMostSpecificMethod + */ + public static Method getMostSpecificMethod(Method method, Class targetClass) { + Method resolvedMethod = ClassUtils.getMostSpecificMethod(method, targetClass); + // If we are dealing with method with generic parameters, find the original method. + if (JdkVersion.isAtLeastJava15()) { + resolvedMethod = BridgeMethodResolver.findBridgedMethod(resolvedMethod); + } + return resolvedMethod; + } + + + /** + * Can the given pointcut apply at all on the given class? + *

    This is an important test as it can be used to optimize + * out a pointcut for a class. + * @param pc the static or dynamic pointcut to check + * @param targetClass the class to test + * @return whether the pointcut can apply on any method + */ + public static boolean canApply(Pointcut pc, Class targetClass) { + return canApply(pc, targetClass, false); + } + + /** + * Can the given pointcut apply at all on the given class? + *

    This is an important test as it can be used to optimize + * out a pointcut for a class. + * @param pc the static or dynamic pointcut to check + * @param targetClass the class to test + * @param hasIntroductions whether or not the advisor chain + * for this bean includes any introductions + * @return whether the pointcut can apply on any method + */ + public static boolean canApply(Pointcut pc, Class targetClass, boolean hasIntroductions) { + if (!pc.getClassFilter().matches(targetClass)) { + return false; + } + + MethodMatcher methodMatcher = pc.getMethodMatcher(); + IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null; + if (methodMatcher instanceof IntroductionAwareMethodMatcher) { + introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher; + } + + Set classes = new HashSet(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); + classes.add(targetClass); + for (Iterator it = classes.iterator(); it.hasNext();) { + Class clazz = (Class) it.next(); + Method[] methods = clazz.getMethods(); + for (int j = 0; j < methods.length; j++) { + if ((introductionAwareMethodMatcher != null && + introductionAwareMethodMatcher.matches(methods[j], targetClass, hasIntroductions)) || + methodMatcher.matches(methods[j], targetClass)) { + return true; + } + } + } + + return false; + } + + /** + * Can the given advisor apply at all on the given class? + * This is an important test as it can be used to optimize + * out a advisor for a class. + * @param advisor the advisor to check + * @param targetClass class we're testing + * @return whether the pointcut can apply on any method + */ + public static boolean canApply(Advisor advisor, Class targetClass) { + return canApply(advisor, targetClass, false); + } + + /** + * Can the given advisor apply at all on the given class? + *

    This is an important test as it can be used to optimize out a advisor for a class. + * This version also takes into account introductions (for IntroductionAwareMethodMatchers). + * @param advisor the advisor to check + * @param targetClass class we're testing + * @param hasIntroductions whether or not the advisor chain for this bean includes + * any introductions + * @return whether the pointcut can apply on any method + */ + public static boolean canApply(Advisor advisor, Class targetClass, boolean hasIntroductions) { + if (advisor instanceof IntroductionAdvisor) { + return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass); + } + else if (advisor instanceof PointcutAdvisor) { + PointcutAdvisor pca = (PointcutAdvisor) advisor; + return canApply(pca.getPointcut(), targetClass, hasIntroductions); + } + else { + // It doesn't have a pointcut so we assume it applies. + return true; + } + } + + /** + * Determine the sublist of the candidateAdvisors list + * that is applicable to the given class. + * @param candidateAdvisors the Advisors to evaluate + * @param clazz the target class + * @return sublist of Advisors that can apply to an object of the given class + * (may be the incoming List as-is) + */ + public static List findAdvisorsThatCanApply(List candidateAdvisors, Class clazz) { + if (candidateAdvisors.isEmpty()) { + return candidateAdvisors; + } + List eligibleAdvisors = new LinkedList(); + for (Iterator it = candidateAdvisors.iterator(); it.hasNext();) { + Advisor candidate = (Advisor) it.next(); + if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) { + eligibleAdvisors.add(candidate); + } + } + boolean hasIntroductions = !eligibleAdvisors.isEmpty(); + for (Iterator it = candidateAdvisors.iterator(); it.hasNext();) { + Advisor candidate = (Advisor) it.next(); + if (candidate instanceof IntroductionAdvisor) { + // already processed + continue; + } + if (canApply(candidate, clazz, hasIntroductions)) { + eligibleAdvisors.add(candidate); + } + } + return eligibleAdvisors; + } + + + /** + * Invoke the given target via reflection, as part of an AOP method invocation. + * @param target the target object + * @param method the method to invoke + * @param args the arguments for the method + * @return the invocation result, if any + * @throws Throwable if thrown by the target method + * @throws org.springframework.aop.AopInvocationException in case of a reflection error + */ + public static Object invokeJoinpointUsingReflection(Object target, Method method, Object[] args) + throws Throwable { + + // Use reflection to invoke the method. + try { + ReflectionUtils.makeAccessible(method); + return method.invoke(target, args); + } + catch (InvocationTargetException ex) { + // Invoked method threw a checked exception. + // We must rethrow it. The client won't see the interceptor. + throw ex.getTargetException(); + } + catch (IllegalArgumentException ex) { + throw new AopInvocationException("AOP configuration seems to be invalid: tried calling method [" + + method + "] on target [" + target + "]", ex); + } + catch (IllegalAccessException ex) { + throw new AopInvocationException("Could not access method [" + method + "]", ex); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/ClassFilters.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/ClassFilters.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/ClassFilters.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,148 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; + +import org.springframework.aop.ClassFilter; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + +/** + * Static utility methods for composing + * {@link org.springframework.aop.ClassFilter ClassFilters}. + * + * @author Rod Johnson + * @author Rob Harrop + * @author Juergen Hoeller + * @since 11.11.2003 + * @see MethodMatchers + * @see Pointcuts + */ +public abstract class ClassFilters { + + /** + * Match all classes that either (or both) of the given ClassFilters matches. + * @param cf1 the first ClassFilter + * @param cf2 the second ClassFilter + * @return a distinct ClassFilter that matches all classes that either + * of the given ClassFilter matches + */ + public static ClassFilter union(ClassFilter cf1, ClassFilter cf2) { + Assert.notNull(cf1, "First ClassFilter must not be null"); + Assert.notNull(cf2, "Second ClassFilter must not be null"); + return new UnionClassFilter(new ClassFilter[] {cf1, cf2}); + } + + /** + * Match all classes that either (or all) of the given ClassFilters matches. + * @param classFilters the ClassFilters to match + * @return a distinct ClassFilter that matches all classes that either + * of the given ClassFilter matches + */ + public static ClassFilter union(ClassFilter[] classFilters) { + Assert.notEmpty(classFilters, "ClassFilter array must not be empty"); + return new UnionClassFilter(classFilters); + } + + /** + * Match all classes that both of the given ClassFilters match. + * @param cf1 the first ClassFilter + * @param cf2 the second ClassFilter + * @return a distinct ClassFilter that matches all classes that both + * of the given ClassFilter match + */ + public static ClassFilter intersection(ClassFilter cf1, ClassFilter cf2) { + Assert.notNull(cf1, "First ClassFilter must not be null"); + Assert.notNull(cf2, "Second ClassFilter must not be null"); + return new IntersectionClassFilter(new ClassFilter[] {cf1, cf2}); + } + + /** + * Match all classes that all of the given ClassFilters match. + * @param classFilters the ClassFilters to match + * @return a distinct ClassFilter that matches all classes that both + * of the given ClassFilter match + */ + public static ClassFilter intersection(ClassFilter[] classFilters) { + Assert.notEmpty(classFilters, "ClassFilter array must not be empty"); + return new IntersectionClassFilter(classFilters); + } + + + /** + * ClassFilter implementation for a union of the given ClassFilters. + */ + private static class UnionClassFilter implements ClassFilter, Serializable { + + private ClassFilter[] filters; + + public UnionClassFilter(ClassFilter[] filters) { + this.filters = filters; + } + + public boolean matches(Class clazz) { + for (int i = 0; i < this.filters.length; i++) { + if (this.filters[i].matches(clazz)) { + return true; + } + } + return false; + } + + public boolean equals(Object other) { + return (this == other || (other instanceof UnionClassFilter && + ObjectUtils.nullSafeEquals(this.filters, ((UnionClassFilter) other).filters))); + } + + public int hashCode() { + return ObjectUtils.nullSafeHashCode(this.filters); + } + } + + + /** + * ClassFilter implementation for an intersection of the given ClassFilters. + */ + private static class IntersectionClassFilter implements ClassFilter, Serializable { + + private ClassFilter[] filters; + + public IntersectionClassFilter(ClassFilter[] filters) { + this.filters = filters; + } + + public boolean matches(Class clazz) { + for (int i = 0; i < this.filters.length; i++) { + if (!this.filters[i].matches(clazz)) { + return false; + } + } + return true; + } + + public boolean equals(Object other) { + return (this == other || (other instanceof IntersectionClassFilter && + ObjectUtils.nullSafeEquals(this.filters, ((IntersectionClassFilter) other).filters))); + } + + public int hashCode() { + return ObjectUtils.nullSafeHashCode(this.filters); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/ComposablePointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/ComposablePointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/ComposablePointcut.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,211 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; + +import org.springframework.aop.ClassFilter; +import org.springframework.aop.MethodMatcher; +import org.springframework.aop.Pointcut; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + +/** + * Convenient class for building up pointcuts. All methods return + * ComposablePointcut, so we can use a concise idiom like: + * + * + * Pointcut pc = new ComposablePointcut().union(classFilter).intersection(methodMatcher).intersection(pointcut); + * + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + * @since 11.11.2003 + * @see Pointcuts + */ +public class ComposablePointcut implements Pointcut, Serializable { + + /** use serialVersionUID from Spring 1.2 for interoperability */ + private static final long serialVersionUID = -2743223737633663832L; + + private ClassFilter classFilter; + + private MethodMatcher methodMatcher; + + + /** + * Create a default ComposablePointcut, with ClassFilter.TRUE + * and MethodMatcher.TRUE. + */ + public ComposablePointcut() { + this.classFilter = ClassFilter.TRUE; + this.methodMatcher = MethodMatcher.TRUE; + } + + /** + * Create a ComposablePointcut based on the given Pointcut. + * @param pointcut the original Pointcut + */ + public ComposablePointcut(Pointcut pointcut) { + Assert.notNull(pointcut, "Pointcut must not be null"); + this.classFilter = pointcut.getClassFilter(); + this.methodMatcher = pointcut.getMethodMatcher(); + } + + /** + * Create a ComposablePointcut for the given ClassFilter, + * with MethodMatcher.TRUE. + * @param classFilter the ClassFilter to use + */ + public ComposablePointcut(ClassFilter classFilter) { + Assert.notNull(classFilter, "ClassFilter must not be null"); + this.classFilter = classFilter; + this.methodMatcher = MethodMatcher.TRUE; + } + + /** + * Create a ComposablePointcut for the given MethodMatcher, + * with ClassFilter.TRUE. + * @param methodMatcher the MethodMatcher to use + */ + public ComposablePointcut(MethodMatcher methodMatcher) { + Assert.notNull(methodMatcher, "MethodMatcher must not be null"); + this.classFilter = ClassFilter.TRUE; + this.methodMatcher = methodMatcher; + } + + /** + * Create a ComposablePointcut for the given ClassFilter and MethodMatcher. + * @param classFilter the ClassFilter to use + * @param methodMatcher the MethodMatcher to use + */ + public ComposablePointcut(ClassFilter classFilter, MethodMatcher methodMatcher) { + Assert.notNull(classFilter, "ClassFilter must not be null"); + Assert.notNull(methodMatcher, "MethodMatcher must not be null"); + this.classFilter = classFilter; + this.methodMatcher = methodMatcher; + } + + + /** + * Apply a union with the given ClassFilter. + * @param other the ClassFilter to apply a union with + * @return this composable pointcut (for call chaining) + */ + public ComposablePointcut union(ClassFilter other) { + this.classFilter = ClassFilters.union(this.classFilter, other); + return this; + } + + /** + * Apply an intersection with the given ClassFilter. + * @param other the ClassFilter to apply an intersection with + * @return this composable pointcut (for call chaining) + */ + public ComposablePointcut intersection(ClassFilter other) { + this.classFilter = ClassFilters.intersection(this.classFilter, other); + return this; + } + + /** + * Apply a union with the given MethodMatcher. + * @param other the MethodMatcher to apply a union with + * @return this composable pointcut (for call chaining) + */ + public ComposablePointcut union(MethodMatcher other) { + this.methodMatcher = MethodMatchers.union(this.methodMatcher, other); + return this; + } + + /** + * Apply an intersection with the given MethodMatcher. + * @param other the MethodMatcher to apply an intersection with + * @return this composable pointcut (for call chaining) + */ + public ComposablePointcut intersection(MethodMatcher other) { + this.methodMatcher = MethodMatchers.intersection(this.methodMatcher, other); + return this; + } + + /** + * Apply a union with the given Pointcut. + *

    Note that for a Pointcut union, methods will only match if their + * original ClassFilter (from the originating Pointcut) matches as well. + * MethodMatchers and ClassFilters from different Pointcuts will never + * get interleaved with each other. + * @param other the Pointcut to apply a union with + * @return this composable pointcut (for call chaining) + */ + public ComposablePointcut union(Pointcut other) { + this.methodMatcher = MethodMatchers.union( + this.methodMatcher, this.classFilter, other.getMethodMatcher(), other.getClassFilter()); + this.classFilter = ClassFilters.union(this.classFilter, other.getClassFilter()); + return this; + } + + /** + * Apply an intersection with the given Pointcut. + * @param other the Pointcut to apply an intersection with + * @return this composable pointcut (for call chaining) + */ + public ComposablePointcut intersection(Pointcut other) { + this.classFilter = ClassFilters.intersection(this.classFilter, other.getClassFilter()); + this.methodMatcher = MethodMatchers.intersection(this.methodMatcher, other.getMethodMatcher()); + return this; + } + + + public ClassFilter getClassFilter() { + return this.classFilter; + } + + public MethodMatcher getMethodMatcher() { + return this.methodMatcher; + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof ComposablePointcut)) { + return false; + } + + ComposablePointcut that = (ComposablePointcut) other; + return ObjectUtils.nullSafeEquals(that.classFilter, this.classFilter) && + ObjectUtils.nullSafeEquals(that.methodMatcher, this.methodMatcher); + } + + public int hashCode() { + int code = 17; + if (this.classFilter != null) { + code = 37 * code + this.classFilter.hashCode(); + } + if (this.methodMatcher != null) { + code = 37 * code + this.methodMatcher.hashCode(); + } + return code; + } + + public String toString() { + return "ComposablePointcut: ClassFilter [" + this.classFilter + + "], MethodMatcher [" + this.methodMatcher + "]"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/ControlFlowPointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/ControlFlowPointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/ControlFlowPointcut.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,131 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; +import java.lang.reflect.Method; + +import org.springframework.aop.ClassFilter; +import org.springframework.aop.MethodMatcher; +import org.springframework.aop.Pointcut; +import org.springframework.core.ControlFlow; +import org.springframework.core.ControlFlowFactory; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + +/** + * Pointcut and method matcher for use in simple cflow-style pointcut. + * Note that evaluating such pointcuts is 10-15 times slower than evaluating + * normal pointcuts, but they are useful in some cases. + * + * @author Rod Johnson + * @author Rob Harrop + * @see org.springframework.core.ControlFlow + */ +public class ControlFlowPointcut implements Pointcut, ClassFilter, MethodMatcher, Serializable { + + private Class clazz; + + private String methodName; + + private int evaluations; + + + /** + * Construct a new pointcut that matches all control flows below that class. + * @param clazz the clazz + */ + public ControlFlowPointcut(Class clazz) { + this(clazz, null); + } + + /** + * Construct a new pointcut that matches all calls below the + * given method in the given class. If the method name is null, + * matches all control flows below that class. + * @param clazz the clazz + * @param methodName the name of the method + */ + public ControlFlowPointcut(Class clazz, String methodName) { + Assert.notNull(clazz, "Class must not be null"); + this.clazz = clazz; + this.methodName = methodName; + } + + + /** + * Subclasses can override this for greater filtering (and performance). + */ + public boolean matches(Class clazz) { + return true; + } + + /** + * Subclasses can override this if it's possible to filter out + * some candidate classes. + */ + public boolean matches(Method method, Class targetClass) { + return true; + } + + public boolean isRuntime() { + return true; + } + + public boolean matches(Method method, Class targetClass, Object[] args) { + ++this.evaluations; + ControlFlow cflow = ControlFlowFactory.createControlFlow(); + return (this.methodName != null) ? cflow.under(this.clazz, this.methodName) : cflow.under(this.clazz); + } + + /** + * It's useful to know how many times we've fired, for optimization. + */ + public int getEvaluations() { + return evaluations; + } + + + public ClassFilter getClassFilter() { + return this; + } + + public MethodMatcher getMethodMatcher() { + return this; + } + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof ControlFlowPointcut)) { + return false; + } + ControlFlowPointcut that = (ControlFlowPointcut) other; + return (this.clazz.equals(that.clazz)) && ObjectUtils.nullSafeEquals(that.methodName, this.methodName); + } + + public int hashCode() { + int code = 17; + code = 37 * code + this.clazz.hashCode(); + if (this.methodName != null) { + code = 37 * code + this.methodName.hashCode(); + } + return code; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/DefaultBeanFactoryPointcutAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/DefaultBeanFactoryPointcutAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/DefaultBeanFactoryPointcutAdvisor.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import org.springframework.aop.Pointcut; + +/** + * Concrete BeanFactory-based PointcutAdvisor that allows for any Advice + * to be configured as reference to an Advice bean in the BeanFactory, + * as well as the Pointcut to be configured through a bean property. + * + *

    Specifying the name of an advice bean instead of the advice object itself + * (if running within a BeanFactory) increases loose coupling at initialization time, + * in order to not initialize the advice object until the pointcut actually matches. + * + * @author Juergen Hoeller + * @since 2.0.2 + * @see #setPointcut + * @see #setAdviceBeanName + */ +public class DefaultBeanFactoryPointcutAdvisor extends AbstractBeanFactoryPointcutAdvisor { + + private Pointcut pointcut = Pointcut.TRUE; + + + /** + * Specify the pointcut targeting the advice. + *

    Default is Pointcut.TRUE. + * @see #setAdviceBeanName + */ + public void setPointcut(Pointcut pointcut) { + this.pointcut = (pointcut != null ? pointcut : Pointcut.TRUE); + } + + public Pointcut getPointcut() { + return this.pointcut; + } + + + public String toString() { + return getClass().getName() + ": pointcut [" + getPointcut() + "]; advice bean '" + getAdviceBeanName() + "'"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/DefaultIntroductionAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/DefaultIntroductionAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/DefaultIntroductionAdvisor.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,167 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.aopalliance.aop.Advice; + +import org.springframework.aop.ClassFilter; +import org.springframework.aop.DynamicIntroductionAdvice; +import org.springframework.aop.IntroductionAdvisor; +import org.springframework.aop.IntroductionInfo; +import org.springframework.core.Ordered; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; + +/** + * Simple {@link org.springframework.aop.IntroductionAdvisor} implementation + * that by default applies to any class. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 11.11.2003 + */ +public class DefaultIntroductionAdvisor implements IntroductionAdvisor, ClassFilter, Ordered, Serializable { + + private final Advice advice; + + private final Set interfaces = new HashSet(); + + private int order = Integer.MAX_VALUE; + + + /** + * Create a DefaultIntroductionAdvisor for the given advice. + * @param advice the Advice to apply (may implement the + * {@link org.springframework.aop.IntroductionInfo} interface) + * @see #addInterface + */ + public DefaultIntroductionAdvisor(Advice advice) { + this(advice, (advice instanceof IntroductionInfo ? (IntroductionInfo) advice : null)); + } + + /** + * Create a DefaultIntroductionAdvisor for the given advice. + * @param advice the Advice to apply + * @param introductionInfo the IntroductionInfo that describes + * the interface to introduce (may be null) + */ + public DefaultIntroductionAdvisor(Advice advice, IntroductionInfo introductionInfo) { + Assert.notNull(advice, "Advice must not be null"); + this.advice = advice; + if (introductionInfo != null) { + Class[] introducedInterfaces = introductionInfo.getInterfaces(); + if (introducedInterfaces.length == 0) { + throw new IllegalArgumentException("IntroductionAdviceSupport implements no interfaces"); + } + for (int i = 0; i < introducedInterfaces.length; i++) { + addInterface(introducedInterfaces[i]); + } + } + } + + /** + * Create a DefaultIntroductionAdvisor for the given advice. + * @param advice the Advice to apply + * @param intf the interface to introduce + */ + public DefaultIntroductionAdvisor(DynamicIntroductionAdvice advice, Class intf) { + Assert.notNull(advice, "Advice must not be null"); + this.advice = advice; + addInterface(intf); + } + + + /** + * Add the specified interface to the list of interfaces to introduce. + * @param intf the interface to introduce + */ + public void addInterface(Class intf) { + Assert.notNull(intf, "Interface must not be null"); + if (!intf.isInterface()) { + throw new IllegalArgumentException("Specified class [" + intf.getName() + "] must be an interface"); + } + this.interfaces.add(intf); + } + + public Class[] getInterfaces() { + return (Class[]) this.interfaces.toArray(new Class[this.interfaces.size()]); + } + + public void validateInterfaces() throws IllegalArgumentException { + for (Iterator it = this.interfaces.iterator(); it.hasNext();) { + Class ifc = (Class) it.next(); + if (this.advice instanceof DynamicIntroductionAdvice && + !((DynamicIntroductionAdvice) this.advice).implementsInterface(ifc)) { + throw new IllegalArgumentException("DynamicIntroductionAdvice [" + this.advice + "] " + + "does not implement interface [" + ifc.getName() + "] specified for introduction"); + } + } + } + + + public void setOrder(int order) { + this.order = order; + } + + public int getOrder() { + return this.order; + } + + + public Advice getAdvice() { + return this.advice; + } + + public boolean isPerInstance() { + return true; + } + + public ClassFilter getClassFilter() { + return this; + } + + public boolean matches(Class clazz) { + return true; + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof DefaultIntroductionAdvisor)) { + return false; + } + DefaultIntroductionAdvisor otherAdvisor = (DefaultIntroductionAdvisor) other; + return (this.advice.equals(otherAdvisor.advice) && this.interfaces.equals(otherAdvisor.interfaces)); + } + + public int hashCode() { + return this.advice.hashCode() * 13 + this.interfaces.hashCode(); + } + + public String toString() { + return ClassUtils.getShortName(getClass()) + ": advice [" + this.advice + "]; interfaces " + + ClassUtils.classNamesToString(this.interfaces); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/DefaultPointcutAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/DefaultPointcutAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/DefaultPointcutAdvisor.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,88 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; + +import org.aopalliance.aop.Advice; + +import org.springframework.aop.Pointcut; + +/** + * Convenient Pointcut-driven Advisor implementation. + * + *

    This is the most commonly used Advisor implementation. It can be used + * with any pointcut and advice type, except for introductions. There is + * normally no need to subclass this class, or to implement custom Advisors. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see #setPointcut + * @see #setAdvice + */ +public class DefaultPointcutAdvisor extends AbstractGenericPointcutAdvisor implements Serializable { + + private Pointcut pointcut = Pointcut.TRUE; + + + /** + * Create an empty DefaultPointcutAdvisor. + *

    Advice must be set before use using setter methods. + * Pointcut will normally be set also, but defaults to Pointcut.TRUE. + */ + public DefaultPointcutAdvisor() { + } + + /** + * Create a DefaultPointcutAdvisor that matches all methods. + *

    Pointcut.TRUE will be used as Pointcut. + * @param advice the Advice to use + */ + public DefaultPointcutAdvisor(Advice advice) { + this(Pointcut.TRUE, advice); + } + + /** + * Create a DefaultPointcutAdvisor, specifying Pointcut and Advice. + * @param pointcut the Pointcut targeting the Advice + * @param advice the Advice to run when Pointcut matches + */ + public DefaultPointcutAdvisor(Pointcut pointcut, Advice advice) { + this.pointcut = pointcut; + setAdvice(advice); + } + + + /** + * Specify the pointcut targeting the advice. + *

    Default is Pointcut.TRUE. + * @see #setAdvice + */ + public void setPointcut(Pointcut pointcut) { + this.pointcut = (pointcut != null ? pointcut : Pointcut.TRUE); + } + + public Pointcut getPointcut() { + return this.pointcut; + } + + + public String toString() { + return getClass().getName() + ": pointcut [" + getPointcut() + "]; advice [" + getAdvice() + "]"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,140 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.util.Map; +import java.util.WeakHashMap; + +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.aop.DynamicIntroductionAdvice; +import org.springframework.aop.IntroductionInterceptor; +import org.springframework.aop.ProxyMethodInvocation; + +/** + * Convenient implementation of the + * {@link org.springframework.aop.IntroductionInterceptor} interface. + * + *

    This differs from {@link DelegatingIntroductionInterceptor} in that a single + * instance of this class can be used to advise multiple target objects, and each target + * object will have its own delegate (whereas DelegatingIntroductionInterceptor + * shares the same delegate, and hence the same state across all targets). + * + *

    The suppressInterface method can be used to suppress interfaces + * implemented by the delegate class but which should not be introduced to the + * owning AOP proxy. + * + *

    An instance of this class is serializable if the delegates are. + * + *

    Note: There are some implementation similarities between this class and + * {@link DelegatingIntroductionInterceptor} that suggest a possible refactoring + * to extract a common ancestor class in the future. + * + * @author Adrian Colyer + * @author Juergen Hoeller + * @since 2.0 + * @see #suppressInterface + * @see DelegatingIntroductionInterceptor + */ +public class DelegatePerTargetObjectIntroductionInterceptor extends IntroductionInfoSupport + implements IntroductionInterceptor { + + /** + * Hold weak references to keys as we don't want to interfere with garbage collection.. + */ + private Map delegateMap = new WeakHashMap(); + + private Class defaultImplType; + + private Class interfaceType; + + + public DelegatePerTargetObjectIntroductionInterceptor(Class defaultImplType, Class interfaceType) { + this.defaultImplType = defaultImplType; + this.interfaceType = interfaceType; + // cCeate a new delegate now (but don't store it in the map). + // We do this for two reasons: + // 1) to fail early if there is a problem instantiating delegates + // 2) to populate the interface map once and once only + Object delegate = createNewDelegate(); + implementInterfacesOnObject(delegate); + suppressInterface(IntroductionInterceptor.class); + suppressInterface(DynamicIntroductionAdvice.class); + } + + + /** + * Subclasses may need to override this if they want to perform custom + * behaviour in around advice. However, subclasses should invoke this + * method, which handles introduced interfaces and forwarding to the target. + */ + public Object invoke(MethodInvocation mi) throws Throwable { + if (isMethodOnIntroducedInterface(mi)) { + Object delegate = getIntroductionDelegateFor(mi.getThis()); + + // Using the following method rather than direct reflection, + // we get correct handling of InvocationTargetException + // if the introduced method throws an exception. + Object retVal = AopUtils.invokeJoinpointUsingReflection(delegate, mi.getMethod(), mi.getArguments()); + + // Massage return value if possible: if the delegate returned itself, + // we really want to return the proxy. + if (retVal == delegate && mi instanceof ProxyMethodInvocation) { + retVal = ((ProxyMethodInvocation) mi).getProxy(); + } + return retVal; + } + + return doProceed(mi); + } + + /** + * Proceed with the supplied {@link org.aopalliance.intercept.MethodInterceptor}. + * Subclasses can override this method to intercept method invocations on the + * target object which is useful when an introduction needs to monitor the object + * that it is introduced into. This method is never called for + * {@link MethodInvocation MethodInvocations} on the introduced interfaces. + */ + protected Object doProceed(MethodInvocation mi) throws Throwable { + // If we get here, just pass the invocation on. + return mi.proceed(); + } + + private Object getIntroductionDelegateFor(Object targetObject) { + synchronized(this.delegateMap) { + if (this.delegateMap.containsKey(targetObject)) { + return this.delegateMap.get(targetObject); + } + else { + Object delegate = createNewDelegate(); + this.delegateMap.put(targetObject, delegate); + return delegate; + } + } + } + + private Object createNewDelegate() { + try { + return this.defaultImplType.newInstance(); + } + catch (Throwable ex) { + throw new IllegalArgumentException("Cannot create default implementation for '" + + this.interfaceType.getName() + "' mixin (" + this.defaultImplType.getName() + "): " + ex); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/DelegatingIntroductionInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/DelegatingIntroductionInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/DelegatingIntroductionInterceptor.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,134 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.aop.DynamicIntroductionAdvice; +import org.springframework.aop.IntroductionInterceptor; +import org.springframework.aop.ProxyMethodInvocation; +import org.springframework.util.Assert; + +/** + * Convenient implementation of the + * {@link org.springframework.aop.IntroductionInterceptor} interface. + * + *

    Subclasses merely need to extend this class and implement the interfaces + * to be introduced themselves. In this case the delegate is the subclass + * instance itself. Alternatively a separate delegate may implement the + * interface, and be set via the delegate bean property. + * + *

    Delegates or subclasses may implement any number of interfaces. + * All interfaces except IntroductionInterceptor are picked up from + * the subclass or delegate by default. + * + *

    The suppressInterface method can be used to suppress interfaces + * implemented by the delegate but which should not be introduced to the owning + * AOP proxy. + * + *

    An instance of this class is serializable if the delegate is. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 16.11.2003 + * @see #suppressInterface + * @see DelegatePerTargetObjectIntroductionInterceptor + */ +public class DelegatingIntroductionInterceptor extends IntroductionInfoSupport + implements IntroductionInterceptor { + + /** + * Object that actually implements the interfaces. + * May be "this" if a subclass implements the introduced interfaces. + */ + private Object delegate; + + + /** + * Construct a new DelegatingIntroductionInterceptor, providing + * a delegate that implements the interfaces to be introduced. + * @param delegate the delegate that implements the introduced interfaces + */ + public DelegatingIntroductionInterceptor(Object delegate) { + init(delegate); + } + + /** + * Construct a new DelegatingIntroductionInterceptor. + * The delegate will be the subclass, which must implement + * additional interfaces. + */ + protected DelegatingIntroductionInterceptor() { + init(this); + } + + + /** + * Both constructors use this init method, as it is impossible to pass + * a "this" reference from one constructor to another. + * @param delegate the delegate object + */ + private void init(Object delegate) { + Assert.notNull(delegate, "Delegate must not be null"); + this.delegate = delegate; + implementInterfacesOnObject(delegate); + + // We don't want to expose the control interface + suppressInterface(IntroductionInterceptor.class); + suppressInterface(DynamicIntroductionAdvice.class); + } + + + /** + * Subclasses may need to override this if they want to perform custom + * behaviour in around advice. However, subclasses should invoke this + * method, which handles introduced interfaces and forwarding to the target. + */ + public Object invoke(MethodInvocation mi) throws Throwable { + if (isMethodOnIntroducedInterface(mi)) { + // Using the following method rather than direct reflection, we + // get correct handling of InvocationTargetException + // if the introduced method throws an exception. + Object retVal = AopUtils.invokeJoinpointUsingReflection(this.delegate, mi.getMethod(), mi.getArguments()); + + // Massage return value if possible: if the delegate returned itself, + // we really want to return the proxy. + if (retVal == this.delegate && mi instanceof ProxyMethodInvocation) { + Object proxy = ((ProxyMethodInvocation) mi).getProxy(); + if (mi.getMethod().getReturnType().isInstance(proxy)) { + retVal = proxy; + } + } + return retVal; + } + + return doProceed(mi); + } + + /** + * Proceed with the supplied {@link org.aopalliance.intercept.MethodInterceptor}. + * Subclasses can override this method to intercept method invocations on the + * target object which is useful when an introduction needs to monitor the object + * that it is introduced into. This method is never called for + * {@link MethodInvocation MethodInvocations} on the introduced interfaces. + */ + protected Object doProceed(MethodInvocation mi) throws Throwable { + // If we get here, just pass the invocation on. + return mi.proceed(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/DynamicMethodMatcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/DynamicMethodMatcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/DynamicMethodMatcher.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.lang.reflect.Method; + +import org.springframework.aop.MethodMatcher; + +/** + * Convenient abstract superclass for dynamic method matchers, + * which do care about arguments at runtime. + */ +public abstract class DynamicMethodMatcher implements MethodMatcher { + + public final boolean isRuntime() { + return true; + } + + /** + * Can override to add preconditions for dynamic matching. This implementation + * always returns true. + */ + public boolean matches(Method method, Class targetClass) { + return true; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/DynamicMethodMatcherPointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/DynamicMethodMatcherPointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/DynamicMethodMatcherPointcut.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import org.springframework.aop.ClassFilter; +import org.springframework.aop.MethodMatcher; +import org.springframework.aop.Pointcut; + +/** + * Convenient superclass when we want to force subclasses to + * implement MethodMatcher interface, but subclasses + * will want to be pointcuts. The getClassFilter() method can + * be overriden to customize ClassFilter behaviour as well. + * + * @author Rod Johnson + */ +public abstract class DynamicMethodMatcherPointcut extends DynamicMethodMatcher implements Pointcut { + + public ClassFilter getClassFilter() { + return ClassFilter.TRUE; + } + + public final MethodMatcher getMethodMatcher() { + return this; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/ExpressionPointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/ExpressionPointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/ExpressionPointcut.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import org.springframework.aop.Pointcut; + +/** + * Interface to be implemented by pointcuts that use String expressions. + * + * @author Rob Harrop + * @since 2.0 + */ +public interface ExpressionPointcut extends Pointcut { + + /** + * Return the String expression for this pointcut. + */ + String getExpression(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/IntroductionInfoSupport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/IntroductionInfoSupport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/IntroductionInfoSupport.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,137 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.Serializable; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.aopalliance.intercept.MethodInvocation; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.aop.IntroductionInfo; +import org.springframework.util.ClassUtils; + +/** + * Support for implementations of {@link org.springframework.aop.IntroductionInfo}. + * + *

    Allows subclasses to conveniently add all interfaces from a given object, + * and to suppress interfaces that should not be added. Also allows for querying + * all introduced interfaces. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public class IntroductionInfoSupport implements IntroductionInfo, Serializable { + + protected transient Log logger = LogFactory.getLog(getClass()); + + /** Set of interface Classes */ + protected Set publishedInterfaces = new HashSet(); + + /** + * Methods that we know we should implement here: key is Method, value is Boolean. + **/ + private transient Map rememberedMethods = createRememberedMethodMap(); + + + /** + * Suppress the specified interface, which may have been autodetected + * due to the delegate implementing it. Call this method to exclude + * internal interfaces from being visible at the proxy level. + *

    Does nothing if the interface is not implemented by the delegate. + * @param intf the interface to suppress + */ + public void suppressInterface(Class intf) { + this.publishedInterfaces.remove(intf); + } + + public Class[] getInterfaces() { + return (Class[]) this.publishedInterfaces.toArray(new Class[this.publishedInterfaces.size()]); + } + + /** + * Check whether the specified interfaces is a published introduction interface. + * @param intf the interface to check + * @return whether the interface is part of this introduction + */ + public boolean implementsInterface(Class intf) { + for (Iterator it = this.publishedInterfaces.iterator(); it.hasNext();) { + Class pubIntf = (Class) it.next(); + if (intf.isInterface() && intf.isAssignableFrom(pubIntf)) { + return true; + } + } + return false; + } + + /** + * Publish all interfaces that the given delegate implements at the proxy level. + * @param delegate the delegate object + */ + protected void implementInterfacesOnObject(Object delegate) { + this.publishedInterfaces.addAll(ClassUtils.getAllInterfacesAsSet(delegate)); + } + + private Map createRememberedMethodMap() { + return new IdentityHashMap(32); + } + + /** + * Is this method on an introduced interface? + * @param mi the method invocation + * @return whether the invoked method is on an introduced interface + */ + protected final boolean isMethodOnIntroducedInterface(MethodInvocation mi) { + Boolean rememberedResult = (Boolean) this.rememberedMethods.get(mi.getMethod()); + if (rememberedResult != null) { + return rememberedResult.booleanValue(); + } + else { + // Work it out and cache it. + boolean result = implementsInterface(mi.getMethod().getDeclaringClass()); + this.rememberedMethods.put(mi.getMethod(), (result ? Boolean.TRUE : Boolean.FALSE)); + return result; + } + } + + + //--------------------------------------------------------------------- + // Serialization support + //--------------------------------------------------------------------- + + /** + * This method is implemented only to restore the logger. + * We don't make the logger static as that would mean that subclasses + * would use this class's log category. + */ + private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { + // Rely on default serialization; just initialize state after deserialization. + ois.defaultReadObject(); + + // Initialize transient fields. + this.logger = LogFactory.getLog(getClass()); + this.rememberedMethods = createRememberedMethodMap(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/JdkRegexpMethodPointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/JdkRegexpMethodPointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/JdkRegexpMethodPointcut.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,97 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +/** + * Regular expression pointcut based on the java.util.regex package. + * Supports the following JavaBean properties: + *

      + *
    • pattern: regular expression for the fully-qualified method names to match + *
    • patterns: alternative property taking a String array of patterns. The result will + * be the union of these patterns. + *
    + * + *

    Note: the regular expressions must be a match. For example, + * .*get.* will match com.mycom.Foo.getBar(). + * get.* will not. + * + * @author Dmitriy Kopylenko + * @author Rob Harrop + * @since 1.1 + */ +public class JdkRegexpMethodPointcut extends AbstractRegexpMethodPointcut { + + /** + * Compiled form of the patterns. + */ + private transient Pattern[] compiledPatterns = new Pattern[0]; + + /** + * Compiled form of the exclusion patterns. + */ + private transient Pattern[] compiledExclusionPatterns = new Pattern[0]; + + + /** + * Initialize {@link Pattern Patterns} from the supplied String[]. + */ + protected void initPatternRepresentation(String[] patterns) throws PatternSyntaxException { + this.compiledPatterns = compilePatterns(patterns); + } + + /** + * Returns true if the {@link Pattern} at index patternIndex + * matches the supplied candidate String. + */ + protected boolean matches(String pattern, int patternIndex) { + Matcher matcher = this.compiledPatterns[patternIndex].matcher(pattern); + return matcher.matches(); + } + + /** + * Initialize exclusion {@link Pattern Patterns} from the supplied String[]. + */ + protected void initExcludedPatternRepresentation(String[] excludedPatterns) throws IllegalArgumentException { + this.compiledExclusionPatterns = compilePatterns(excludedPatterns); + } + + /** + * Returns true if the exclusion {@link Pattern} at index patternIndex + * matches the supplied candidate String. + */ + protected boolean matchesExclusion(String candidate, int patternIndex) { + Matcher matcher = this.compiledExclusionPatterns[patternIndex].matcher(candidate); + return matcher.matches(); + } + + /** + * Compiles the supplied String[] into an array of + * {@link Pattern} objects and returns that array. + */ + private Pattern[] compilePatterns(String[] source) { + Pattern[] destination = new Pattern[source.length]; + for (int i = 0; i < source.length; i++) { + destination[i] = Pattern.compile(source[i]); + } + return destination; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/MethodMatchers.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/MethodMatchers.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/MethodMatchers.java 17 Aug 2012 15:11:25 -0000 1.1 @@ -0,0 +1,254 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; +import java.lang.reflect.Method; + +import org.springframework.aop.ClassFilter; +import org.springframework.aop.IntroductionAwareMethodMatcher; +import org.springframework.aop.MethodMatcher; +import org.springframework.util.Assert; + +/** + * Static utility methods for composing + * {@link org.springframework.aop.MethodMatcher MethodMatchers}. + * + *

    A MethodMatcher may be evaluated statically (based on method + * and target class) or need further evaluation dynamically + * (based on arguments at the time of method invocation). + * + * @author Rod Johnson + * @author Rob Harrop + * @author Juergen Hoeller + * @since 11.11.2003 + * @see ClassFilters + * @see Pointcuts + */ +public abstract class MethodMatchers { + + /** + * Match all methods that either (or both) of the given MethodMatchers matches. + * @param mm1 the first MethodMatcher + * @param mm2 the second MethodMatcher + * @return a distinct MethodMatcher that matches all methods that either + * of the given MethodMatchers matches + */ + public static MethodMatcher union(MethodMatcher mm1, MethodMatcher mm2) { + return new UnionMethodMatcher(mm1, mm2); + } + + /** + * Match all methods that either (or both) of the given MethodMatchers matches. + * @param mm1 the first MethodMatcher + * @param cf1 the corresponding ClassFilter for the first MethodMatcher + * @param mm2 the second MethodMatcher + * @param cf2 the corresponding ClassFilter for the second MethodMatcher + * @return a distinct MethodMatcher that matches all methods that either + * of the given MethodMatchers matches + */ + static MethodMatcher union(MethodMatcher mm1, ClassFilter cf1, MethodMatcher mm2, ClassFilter cf2) { + return new ClassFilterAwareUnionMethodMatcher(mm1, cf1, mm2, cf2); + } + + /** + * Match all methods that both of the given MethodMatchers match. + * @param mm1 the first MethodMatcher + * @param mm2 the second MethodMatcher + * @return a distinct MethodMatcher that matches all methods that both + * of the given MethodMatchers match + */ + public static MethodMatcher intersection(MethodMatcher mm1, MethodMatcher mm2) { + return new IntersectionMethodMatcher(mm1, mm2); + } + + /** + * Apply the given MethodMatcher to the given Method, supporting an + * {@link org.springframework.aop.IntroductionAwareMethodMatcher} + * (if applicable). + * @param mm the MethodMatcher to apply (may be an IntroductionAwareMethodMatcher) + * @param method the candidate method + * @param targetClass the target class (may be null, in which case + * the candidate class must be taken to be the method's declaring class) + * @param hasIntroductions true if the object on whose behalf we are + * asking is the subject on one or more introductions; false otherwise + * @return whether or not this method matches statically + */ + public static boolean matches(MethodMatcher mm, Method method, Class targetClass, boolean hasIntroductions) { + Assert.notNull(mm, "MethodMatcher must not be null"); + return ((mm instanceof IntroductionAwareMethodMatcher && + ((IntroductionAwareMethodMatcher) mm).matches(method, targetClass, hasIntroductions)) || + mm.matches(method, targetClass)); + } + + + /** + * MethodMatcher implementation for a union of two given MethodMatchers. + */ + private static class UnionMethodMatcher implements IntroductionAwareMethodMatcher, Serializable { + + private MethodMatcher mm1; + private MethodMatcher mm2; + + public UnionMethodMatcher(MethodMatcher mm1, MethodMatcher mm2) { + Assert.notNull(mm1, "First MethodMatcher must not be null"); + Assert.notNull(mm2, "Second MethodMatcher must not be null"); + this.mm1 = mm1; + this.mm2 = mm2; + } + + public boolean matches(Method method, Class targetClass, boolean hasIntroductions) { + return (matchesClass1(targetClass) && MethodMatchers.matches(this.mm1, method, targetClass, hasIntroductions)) || + (matchesClass2(targetClass) && MethodMatchers.matches(this.mm2, method, targetClass, hasIntroductions)); + } + + public boolean matches(Method method, Class targetClass) { + return (matchesClass1(targetClass) && this.mm1.matches(method, targetClass)) || + (matchesClass2(targetClass) && this.mm2.matches(method, targetClass)); + } + + protected boolean matchesClass1(Class targetClass) { + return true; + } + + protected boolean matchesClass2(Class targetClass) { + return true; + } + + public boolean isRuntime() { + return this.mm1.isRuntime() || this.mm2.isRuntime(); + } + + public boolean matches(Method method, Class targetClass, Object[] args) { + return this.mm1.matches(method, targetClass, args) || this.mm2.matches(method, targetClass, args); + } + + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof UnionMethodMatcher)) { + return false; + } + UnionMethodMatcher that = (UnionMethodMatcher) obj; + return (this.mm1.equals(that.mm1) && this.mm2.equals(that.mm2)); + } + + public int hashCode() { + int hashCode = 17; + hashCode = 37 * hashCode + this.mm1.hashCode(); + hashCode = 37 * hashCode + this.mm2.hashCode(); + return hashCode; + } + } + + + /** + * MethodMatcher implementation for a union of two given MethodMatchers, + * supporting an associated ClassFilter per MethodMatcher. + */ + private static class ClassFilterAwareUnionMethodMatcher extends UnionMethodMatcher { + + private final ClassFilter cf1; + private final ClassFilter cf2; + + public ClassFilterAwareUnionMethodMatcher(MethodMatcher mm1, ClassFilter cf1, MethodMatcher mm2, ClassFilter cf2) { + super(mm1, mm2); + this.cf1 = cf1; + this.cf2 = cf2; + } + + protected boolean matchesClass1(Class targetClass) { + return this.cf1.matches(targetClass); + } + + protected boolean matchesClass2(Class targetClass) { + return this.cf2.matches(targetClass); + } + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof ClassFilterAwareUnionMethodMatcher)) { + return false; + } + ClassFilterAwareUnionMethodMatcher that = (ClassFilterAwareUnionMethodMatcher) other; + return (this.cf1.equals(that.cf1) && this.cf2.equals(that.cf2) && super.equals(other)); + } + } + + + /** + * MethodMatcher implementation for an intersection of two given MethodMatchers. + */ + private static class IntersectionMethodMatcher implements IntroductionAwareMethodMatcher, Serializable { + + private MethodMatcher mm1; + private MethodMatcher mm2; + + public IntersectionMethodMatcher(MethodMatcher mm1, MethodMatcher mm2) { + Assert.notNull(mm1, "First MethodMatcher must not be null"); + Assert.notNull(mm2, "Second MethodMatcher must not be null"); + this.mm1 = mm1; + this.mm2 = mm2; + } + + public boolean matches(Method method, Class targetClass, boolean hasIntroductions) { + return MethodMatchers.matches(this.mm1, method, targetClass, hasIntroductions) && + MethodMatchers.matches(this.mm2, method, targetClass, hasIntroductions); + } + + public boolean matches(Method method, Class targetClass) { + return this.mm1.matches(method, targetClass) && this.mm2.matches(method, targetClass); + } + + public boolean isRuntime() { + return this.mm1.isRuntime() || this.mm2.isRuntime(); + } + + public boolean matches(Method method, Class targetClass, Object[] args) { + // Because a dynamic intersection may be composed of a static and dynamic part, + // we must avoid calling the 3-arg matches method on a dynamic matcher, as + // it will probably be an unsupported operation. + boolean aMatches = this.mm1.isRuntime() ? + this.mm1.matches(method, targetClass, args) : this.mm1.matches(method, targetClass); + boolean bMatches = this.mm2.isRuntime() ? + this.mm2.matches(method, targetClass, args) : this.mm2.matches(method, targetClass); + return aMatches && bMatches; + } + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof IntersectionMethodMatcher)) { + return false; + } + IntersectionMethodMatcher that = (IntersectionMethodMatcher) other; + return (this.mm1.equals(that.mm1) && this.mm2.equals(that.mm2)); + } + + public int hashCode() { + int hashCode = 17; + hashCode = 37 * hashCode + this.mm1.hashCode(); + hashCode = 37 * hashCode + this.mm2.hashCode(); + return hashCode; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/NameMatchMethodPointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/NameMatchMethodPointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/NameMatchMethodPointcut.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,118 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.LinkedList; +import java.util.List; + +import org.springframework.util.ObjectUtils; +import org.springframework.util.PatternMatchUtils; + +/** + * Pointcut bean for simple method name matches, as alternative to regexp patterns. + * Does not handle overloaded methods: all methods *with a given name will be eligible. + * + * @author Juergen Hoeller + * @author Rod Johnson + * @author Rob Harrop + * @since 11.02.2004 + * @see #isMatch + */ +public class NameMatchMethodPointcut extends StaticMethodMatcherPointcut implements Serializable { + + private List mappedNames = new LinkedList(); + + + /** + * Convenience method when we have only a single method name to match. + * Use either this method or setMappedNames, not both. + * @see #setMappedNames + */ + public void setMappedName(String mappedName) { + setMappedNames(new String[] { mappedName }); + } + + /** + * Set the method names defining methods to match. + * Matching will be the union of all these; if any match, + * the pointcut matches. + */ + public void setMappedNames(String[] mappedNames) { + this.mappedNames = new LinkedList(); + if (mappedNames != null) { + for (int i = 0; i < mappedNames.length; i++) { + this.mappedNames.add(mappedNames[i]); + } + } + } + + /** + * Add another eligible method name, in addition to those already named. + * Like the set methods, this method is for use when configuring proxies, + * before a proxy is used. + *

    NB: This method does not work after the proxy is in + * use, as advice chains will be cached. + * @param name name of the additional method that will match + * @return this pointcut to allow for multiple additions in one line + */ + public NameMatchMethodPointcut addMethodName(String name) { + // TODO in a future release, consider a way of letting proxies + // cause advice changed events. + this.mappedNames.add(name); + return this; + } + + + public boolean matches(Method method, Class targetClass) { + for (int i = 0; i < this.mappedNames.size(); i++) { + String mappedName = (String) this.mappedNames.get(i); + if (mappedName.equals(method.getName()) || isMatch(method.getName(), mappedName)) { + return true; + } + } + return false; + } + + /** + * Return if the given method name matches the mapped name. + *

    The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, + * as well as direct equality. Can be overridden in subclasses. + * @param methodName the method name of the class + * @param mappedName the name in the descriptor + * @return if the names match + * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) + */ + protected boolean isMatch(String methodName, String mappedName) { + return PatternMatchUtils.simpleMatch(mappedName, methodName); + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + return (other instanceof NameMatchMethodPointcut && + ObjectUtils.nullSafeEquals(this.mappedNames, ((NameMatchMethodPointcut) other).mappedNames)); + } + + public int hashCode() { + return (this.mappedNames != null ? this.mappedNames.hashCode() : 0); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/NameMatchMethodPointcutAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/NameMatchMethodPointcutAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/NameMatchMethodPointcutAdvisor.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,91 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import org.aopalliance.aop.Advice; + +import org.springframework.aop.ClassFilter; +import org.springframework.aop.Pointcut; + +/** + * Convenient class for name-match method pointcuts that hold an Advice, + * making them an Advisor. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @see NameMatchMethodPointcut + */ +public class NameMatchMethodPointcutAdvisor extends AbstractGenericPointcutAdvisor { + + private final NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut(); + + + public NameMatchMethodPointcutAdvisor() { + } + + public NameMatchMethodPointcutAdvisor(Advice advice) { + setAdvice(advice); + } + + + /** + * Set the {@link ClassFilter} to use for this pointcut. + * Default is {@link ClassFilter#TRUE}. + * @see NameMatchMethodPointcut#setClassFilter + */ + public void setClassFilter(ClassFilter classFilter) { + this.pointcut.setClassFilter(classFilter); + } + + /** + * Convenience method when we have only a single method name to match. + * Use either this method or setMappedNames, not both. + * @see #setMappedNames + * @see NameMatchMethodPointcut#setMappedName + */ + public void setMappedName(String mappedName) { + this.pointcut.setMappedName(mappedName); + } + + /** + * Set the method names defining methods to match. + * Matching will be the union of all these; if any match, + * the pointcut matches. + * @see NameMatchMethodPointcut#setMappedNames + */ + public void setMappedNames(String[] mappedNames) { + this.pointcut.setMappedNames(mappedNames); + } + + /** + * Add another eligible method name, in addition to those already named. + * Like the set methods, this method is for use when configuring proxies, + * before a proxy is used. + * @param name name of the additional method that will match + * @return this pointcut to allow for multiple additions in one line + * @see NameMatchMethodPointcut#addMethodName + */ + public NameMatchMethodPointcut addMethodName(String name) { + return this.pointcut.addMethodName(name); + } + + + public Pointcut getPointcut() { + return this.pointcut; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/Pointcuts.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/Pointcuts.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/Pointcuts.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,127 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; +import java.lang.reflect.Method; + +import org.springframework.aop.MethodMatcher; +import org.springframework.aop.Pointcut; +import org.springframework.util.Assert; + +/** + * Pointcut constants for matching getters and setters, + * and static methods useful for manipulating and evaluating pointcuts. + * These methods are particularly useful for composing pointcuts + * using the union and intersection methods. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public abstract class Pointcuts { + + /** Pointcut matching all bean property setters, in any class */ + public static final Pointcut SETTERS = SetterPointcut.INSTANCE; + + /** Pointcut matching all bean property getters, in any class */ + public static final Pointcut GETTERS = GetterPointcut.INSTANCE; + + + /** + * Match all methods that either (or both) of the given pointcuts matches. + * @param pc1 the first Pointcut + * @param pc2 the second Pointcut + * @return a distinct Pointcut that matches all methods that either + * of the given Pointcuts matches + */ + public static Pointcut union(Pointcut pc1, Pointcut pc2) { + return new ComposablePointcut(pc1).union(pc2); + } + + /** + * Match all methods that both the given pointcuts match. + * @param pc1 the first Pointcut + * @param pc2 the second Pointcut + * @return a distinct Pointcut that matches all methods that both + * of the given Pointcuts match + */ + public static Pointcut intersection(Pointcut pc1, Pointcut pc2) { + return new ComposablePointcut(pc1).intersection(pc2); + } + + /** + * Perform the least expensive check for a pointcut match. + * @param pointcut the pointcut to match + * @param method the candidate method + * @param targetClass the target class + * @param args arguments to the method + * @return whether there's a runtime match + */ + public static boolean matches(Pointcut pointcut, Method method, Class targetClass, Object[] args) { + Assert.notNull(pointcut, "Pointcut must not be null"); + if (pointcut == Pointcut.TRUE) { + return true; + } + if (pointcut.getClassFilter().matches(targetClass)) { + // Only check if it gets past first hurdle. + MethodMatcher mm = pointcut.getMethodMatcher(); + if (mm.matches(method, targetClass)) { + // We may need additional runtime (argument) check. + return (!mm.isRuntime() || mm.matches(method, targetClass, args)); + } + } + return false; + } + + + /** + * Pointcut implementation that matches bean property setters. + */ + private static class SetterPointcut extends StaticMethodMatcherPointcut implements Serializable { + + public static SetterPointcut INSTANCE = new SetterPointcut(); + + public boolean matches(Method method, Class targetClass) { + return method.getName().startsWith("set") && + method.getParameterTypes().length == 1 && + method.getReturnType() == Void.TYPE; + } + + private Object readResolve() { + return INSTANCE; + } + } + + + /** + * Pointcut implementation that matches bean property getters. + */ + private static class GetterPointcut extends StaticMethodMatcherPointcut implements Serializable { + + public static GetterPointcut INSTANCE = new GetterPointcut(); + + public boolean matches(Method method, Class targetClass) { + return method.getName().startsWith("get") && + method.getParameterTypes().length == 0; + } + + private Object readResolve() { + return INSTANCE; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/RegexpMethodPointcutAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/RegexpMethodPointcutAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/RegexpMethodPointcutAdvisor.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,149 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; + +import org.aopalliance.aop.Advice; + +import org.springframework.aop.Pointcut; +import org.springframework.util.ObjectUtils; + +/** + * Convenient class for regexp method pointcuts that hold an Advice, + * making them an {@link org.springframework.aop.Advisor}. + * + *

    Configure this class using the "pattern" and "patterns" + * pass-through properties. These are analogous to the pattern + * and patterns properties of {@link AbstractRegexpMethodPointcut}. + * + *

    Can delegate to any {@link AbstractRegexpMethodPointcut} subclass. + * By default, {@link JdkRegexpMethodPointcut} will be used. To choose + * a specific one, override the {@link #createPointcut} method. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see #setPattern + * @see #setPatterns + * @see JdkRegexpMethodPointcut + */ +public class RegexpMethodPointcutAdvisor extends AbstractGenericPointcutAdvisor { + + private String[] patterns; + + private AbstractRegexpMethodPointcut pointcut; + + private final Object pointcutMonitor = new SerializableMonitor(); + + + /** + * Create an empty RegexpMethodPointcutAdvisor. + * @see #setPattern + * @see #setPatterns + * @see #setAdvice + */ + public RegexpMethodPointcutAdvisor() { + } + + /** + * Create a RegexpMethodPointcutAdvisor for the given advice. + * The pattern still needs to be specified afterwards. + * @param advice the advice to use + * @see #setPattern + * @see #setPatterns + */ + public RegexpMethodPointcutAdvisor(Advice advice) { + setAdvice(advice); + } + + /** + * Create a RegexpMethodPointcutAdvisor for the given advice. + * @param pattern the pattern to use + * @param advice the advice to use + */ + public RegexpMethodPointcutAdvisor(String pattern, Advice advice) { + setPattern(pattern); + setAdvice(advice); + } + + /** + * Create a RegexpMethodPointcutAdvisor for the given advice. + * @param patterns the patterns to use + * @param advice the advice to use + */ + public RegexpMethodPointcutAdvisor(String[] patterns, Advice advice) { + setPatterns(patterns); + setAdvice(advice); + } + + + /** + * Set the regular expression defining methods to match. + *

    Use either this method or {@link #setPatterns}, not both. + * @see #setPatterns + */ + public void setPattern(String pattern) { + setPatterns(new String[] {pattern}); + } + + /** + * Set the regular expressions defining methods to match. + * To be passed through to the pointcut implementation. + *

    Matching will be the union of all these; if any of the + * patterns matches, the pointcut matches. + * @see AbstractRegexpMethodPointcut#setPatterns + */ + public void setPatterns(String[] patterns) { + this.patterns = patterns; + } + + + /** + * Initialize the singleton Pointcut held within this Advisor. + */ + public Pointcut getPointcut() { + synchronized (this.pointcutMonitor) { + if (this.pointcut == null) { + this.pointcut = createPointcut(); + this.pointcut.setPatterns(this.patterns); + } + return pointcut; + } + } + + /** + * Create the actual pointcut: By default, a {@link JdkRegexpMethodPointcut} + * will be used. + * @return the Pointcut instance (never null) + */ + protected AbstractRegexpMethodPointcut createPointcut() { + return new JdkRegexpMethodPointcut(); + } + + public String toString() { + return getClass().getName() + ": advice [" + getAdvice() + + "], pointcut patterns " + ObjectUtils.nullSafeToString(this.patterns); + } + + + /** + * Empty class used for a serializable monitor object. + */ + private static class SerializableMonitor implements Serializable { + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/RootClassFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/RootClassFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/RootClassFilter.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; + +import org.springframework.aop.ClassFilter; + +/** + * Simple ClassFilter implementation that passes classes (and optionally subclasses) + * @author Rod Johnson + */ +public class RootClassFilter implements ClassFilter, Serializable { + + private Class clazz; + + // TODO inheritance + + public RootClassFilter(Class clazz) { + this.clazz = clazz; + } + + public boolean matches(Class candidate) { + return clazz.isAssignableFrom(candidate); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/StaticMethodMatcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/StaticMethodMatcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/StaticMethodMatcher.java 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.lang.reflect.Method; + +import org.springframework.aop.MethodMatcher; + +/** + * Convenient abstract superclass for static method matchers, which don't care + * about arguments at runtime. + */ +public abstract class StaticMethodMatcher implements MethodMatcher { + + public final boolean isRuntime() { + return false; + } + + public final boolean matches(Method method, Class targetClass, Object[] args) { + // should never be invoked because isRuntime() returns false + throw new UnsupportedOperationException("Illegal MethodMatcher usage"); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/StaticMethodMatcherPointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/StaticMethodMatcherPointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/StaticMethodMatcherPointcut.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import org.springframework.aop.ClassFilter; +import org.springframework.aop.MethodMatcher; +import org.springframework.aop.Pointcut; + +/** + * Convenient superclass when we want to force subclasses to implement the + * {@link MethodMatcher} interface but subclasses will want to be pointcuts. + * + *

    The {@link #setClassFilter "classFilter"} property can be set to customize + * {@link ClassFilter} behavior. The default is {@link ClassFilter#TRUE}. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public abstract class StaticMethodMatcherPointcut extends StaticMethodMatcher implements Pointcut { + + private ClassFilter classFilter = ClassFilter.TRUE; + + + /** + * Set the {@link ClassFilter} to use for this pointcut. + * Default is {@link ClassFilter#TRUE}. + */ + public void setClassFilter(ClassFilter classFilter) { + this.classFilter = classFilter; + } + + public ClassFilter getClassFilter() { + return this.classFilter; + } + + + public final MethodMatcher getMethodMatcher() { + return this; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/StaticMethodMatcherPointcutAdvisor.java 17 Aug 2012 15:11:27 -0000 1.1 @@ -0,0 +1,85 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support; + +import java.io.Serializable; + +import org.aopalliance.aop.Advice; + +import org.springframework.aop.Pointcut; +import org.springframework.aop.PointcutAdvisor; +import org.springframework.core.Ordered; +import org.springframework.util.Assert; + +/** + * Convenient base class for Advisors that are also static pointcuts. + * Serializable if Advice and subclass are. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public abstract class StaticMethodMatcherPointcutAdvisor extends StaticMethodMatcherPointcut + implements PointcutAdvisor, Ordered, Serializable { + + private int order = Integer.MAX_VALUE; + + private Advice advice; + + + /** + * Create a new StaticMethodMatcherPointcutAdvisor, + * expecting bean-style configuration. + * @see #setAdvice + */ + public StaticMethodMatcherPointcutAdvisor() { + } + + /** + * Create a new StaticMethodMatcherPointcutAdvisor for the given advice. + * @param advice the Advice to use + */ + public StaticMethodMatcherPointcutAdvisor(Advice advice) { + Assert.notNull(advice, "Advice must not be null"); + this.advice = advice; + } + + + public void setOrder(int order) { + this.order = order; + } + + public int getOrder() { + return this.order; + } + + public void setAdvice(Advice advice) { + this.advice = advice; + } + + public Advice getAdvice() { + return this.advice; + } + + public boolean isPerInstance() { + return true; + } + + public Pointcut getPointcut() { + return this; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/package.html 17 Aug 2012 15:11:26 -0000 1.1 @@ -0,0 +1,7 @@ + + + +Convenience classes for using Spring's AOP API. + + + Index: 3rdParty_sources/spring/org/springframework/aop/support/annotation/AnnotationClassFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/annotation/AnnotationClassFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/annotation/AnnotationClassFilter.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support.annotation; + +import java.lang.annotation.Annotation; + +import org.springframework.aop.ClassFilter; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.util.Assert; + +/** + * Simple ClassFilter that looks for a specific Java 5 annotation + * being present on a class. + * + * @author Juergen Hoeller + * @since 2.0 + * @see AnnotationMatchingPointcut + */ +public class AnnotationClassFilter implements ClassFilter { + + private final Class annotationType; + + private final boolean checkInherited; + + + /** + * Create a new AnnotationClassFilter for the given annotation type. + * @param annotationType the annotation type to look for + */ + public AnnotationClassFilter(Class annotationType) { + this(annotationType, false); + } + + /** + * Create a new AnnotationClassFilter for the given annotation type. + * @param annotationType the annotation type to look for + * @param checkInherited whether to explicitly check the superclasses and + * interfaces for the annotation type as well (even if the annotation type + * is not marked as inherited itself) + */ + public AnnotationClassFilter(Class annotationType, boolean checkInherited) { + Assert.notNull(annotationType, "Annotation type must not be null"); + this.annotationType = annotationType; + this.checkInherited = checkInherited; + } + + + public boolean matches(Class clazz) { + return (this.checkInherited ? + (AnnotationUtils.findAnnotation(clazz, this.annotationType) != null) : + clazz.isAnnotationPresent(this.annotationType)); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/annotation/AnnotationMatchingPointcut.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/annotation/AnnotationMatchingPointcut.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/annotation/AnnotationMatchingPointcut.java 17 Aug 2012 15:11:50 -0000 1.1 @@ -0,0 +1,124 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support.annotation; + +import java.lang.annotation.Annotation; + +import org.springframework.aop.ClassFilter; +import org.springframework.aop.MethodMatcher; +import org.springframework.aop.Pointcut; +import org.springframework.util.Assert; + +/** + * Simple Pointcut that looks for a specific Java 5 annotation + * being present on a {@link #forClassAnnotation class} or + * {@link #forMethodAnnotation method}. + * + * @author Juergen Hoeller + * @since 2.0 + * @see AnnotationClassFilter + * @see AnnotationMethodMatcher + */ +public class AnnotationMatchingPointcut implements Pointcut { + + private final ClassFilter classFilter; + + private final MethodMatcher methodMatcher; + + + /** + * Create a new AnnotationMatchingPointcut for the given annotation type. + * @param classAnnotationType the annotation type to look for at the class level + */ + public AnnotationMatchingPointcut(Class classAnnotationType) { + this.classFilter = new AnnotationClassFilter(classAnnotationType); + this.methodMatcher = MethodMatcher.TRUE; + } + + /** + * Create a new AnnotationMatchingPointcut for the given annotation type. + * @param classAnnotationType the annotation type to look for at the class level + * @param checkInherited whether to explicitly check the superclasses and + * interfaces for the annotation type as well (even if the annotation type + * is not marked as inherited itself) + */ + public AnnotationMatchingPointcut(Class classAnnotationType, boolean checkInherited) { + this.classFilter = new AnnotationClassFilter(classAnnotationType, checkInherited); + this.methodMatcher = MethodMatcher.TRUE; + } + + /** + * Create a new AnnotationMatchingPointcut for the given annotation type. + * @param classAnnotationType the annotation type to look for at the class level + * (can be null) + * @param methodAnnotationType the annotation type to look for at the method level + * (can be null) + */ + public AnnotationMatchingPointcut( + Class classAnnotationType, Class methodAnnotationType) { + + Assert.isTrue((classAnnotationType != null || methodAnnotationType != null), + "Either Class annotation type or Method annotation type needs to be specified (or both)"); + + if (classAnnotationType != null) { + this.classFilter = new AnnotationClassFilter(classAnnotationType); + } + else { + this.classFilter = ClassFilter.TRUE; + } + + if (methodAnnotationType != null) { + this.methodMatcher = new AnnotationMethodMatcher(methodAnnotationType); + } + else { + this.methodMatcher = MethodMatcher.TRUE; + } + } + + + public ClassFilter getClassFilter() { + return this.classFilter; + } + + public MethodMatcher getMethodMatcher() { + return this.methodMatcher; + } + + + /** + * Factory method for an AnnotationMatchingPointcut that matches + * for the specified annotation at the class level. + * @param annotationType the annotation type to look for at the class level + * @return the corresponding AnnotationMatchingPointcut + */ + public static AnnotationMatchingPointcut forClassAnnotation(Class annotationType) { + Assert.notNull(annotationType, "Annotation type must not be null"); + return new AnnotationMatchingPointcut(annotationType); + } + + /** + * Factory method for an AnnotationMatchingPointcut that matches + * for the specified annotation at the method level. + * @param annotationType the annotation type to look for at the method level + * @return the corresponding AnnotationMatchingPointcut + */ + public static AnnotationMatchingPointcut forMethodAnnotation(Class annotationType) { + Assert.notNull(annotationType, "Annotation type must not be null"); + return new AnnotationMatchingPointcut(null, annotationType); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/annotation/AnnotationMethodMatcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/annotation/AnnotationMethodMatcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/annotation/AnnotationMethodMatcher.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.support.annotation; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; + +import org.springframework.aop.support.AopUtils; +import org.springframework.aop.support.StaticMethodMatcher; +import org.springframework.util.Assert; + +/** + * Simple MethodMatcher that looks for a specific Java 5 annotation + * being present on a method (checking both the method on the invoked + * interface, if any, and the corresponding method on the target class). + * + * @author Juergen Hoeller + * @since 2.0 + * @see AnnotationMatchingPointcut + */ +public class AnnotationMethodMatcher extends StaticMethodMatcher { + + private final Class annotationType; + + + /** + * Create a new AnnotationClassFilter for the given annotation type. + * @param annotationType the annotation type to look for + */ + public AnnotationMethodMatcher(Class annotationType) { + Assert.notNull(annotationType, "Annotation type must not be null"); + this.annotationType = annotationType; + } + + + public boolean matches(Method method, Class targetClass) { + if (method.isAnnotationPresent(this.annotationType)) { + return true; + } + // The method may be on an interface, so let's check on the target class as well. + Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass); + return (specificMethod != method && specificMethod.isAnnotationPresent(this.annotationType)); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/support/annotation/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/support/annotation/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/support/annotation/package.html 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,7 @@ + + + +Annotation support for AOP pointcuts. + + + Index: 3rdParty_sources/spring/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/AbstractBeanFactoryBasedTargetSource.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,213 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +import java.io.NotSerializableException; +import java.io.ObjectStreamException; +import java.io.Serializable; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.aop.TargetSource; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; + +/** + * Base class for {@link org.springframework.aop.TargetSource} implementations + * that are based on a Spring {@link org.springframework.beans.factory.BeanFactory}, + * delegating to Spring-managed bean instances. + * + *

    Subclasses can create prototype instances or lazily access a + * singleton target, for example. See {@link LazyInitTargetSource} and + * {@link AbstractPrototypeBasedTargetSource}'s subclasses for concrete strategies. + * + *

    BeanFactory-based TargetSources are serializable. This involves + * disconnecting the current target and turning into a {@link SingletonTargetSource}. + * + * @author Juergen Hoeller + * @author Rod Johnson + * @since 1.1.4 + * @see org.springframework.beans.factory.BeanFactory#getBean + * @see LazyInitTargetSource + * @see PrototypeTargetSource + * @see ThreadLocalTargetSource + * @see CommonsPoolTargetSource + */ +public abstract class AbstractBeanFactoryBasedTargetSource + implements TargetSource, BeanFactoryAware, Serializable { + + /** use serialVersionUID from Spring 1.2.7 for interoperability */ + private static final long serialVersionUID = -4721607536018568393L; + + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + /** Name of the target bean we will create on each invocation */ + private String targetBeanName; + + /** Class of the target */ + private Class targetClass; + + /** + * BeanFactory that owns this TargetSource. We need to hold onto this + * reference so that we can create new prototype instances as necessary. + */ + private BeanFactory beanFactory; + + + /** + * Set the name of the target bean in the factory. + *

    The target bean should not be a singleton, else the same instance will + * always be obtained from the factory, resulting in the same behavior as + * provided by {@link SingletonTargetSource}. + * @param targetBeanName name of the target bean in the BeanFactory + * that owns this interceptor + * @see SingletonTargetSource + */ + public void setTargetBeanName(String targetBeanName) { + this.targetBeanName = targetBeanName; + } + + /** + * Return the name of the target bean in the factory. + */ + public String getTargetBeanName() { + return this.targetBeanName; + } + + /** + * Specify the target class explicitly, to avoid any kind of access to the + * target bean (for example, to avoid initialization of a FactoryBean instance). + *

    Default is to detect the type automatically, through a getType + * call on the BeanFactory (or even a full getBean call as fallback). + */ + public void setTargetClass(Class targetClass) { + this.targetClass = targetClass; + } + + /** + * Set the owning BeanFactory. We need to save a reference so that we can + * use the getBean method on every invocation. + */ + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + if (this.targetBeanName == null) { + throw new IllegalStateException("Property'targetBeanName' is required"); + } + this.beanFactory = beanFactory; + } + + /** + * Return the owning BeanFactory. + */ + public BeanFactory getBeanFactory() { + return this.beanFactory; + } + + + public synchronized Class getTargetClass() { + if (this.targetClass == null && this.beanFactory != null) { + // Determine type of the target bean. + this.targetClass = this.beanFactory.getType(this.targetBeanName); + if (this.targetClass == null) { + if (logger.isTraceEnabled()) { + logger.trace("Getting bean with name '" + this.targetBeanName + "' in order to determine type"); + } + this.targetClass = this.beanFactory.getBean(this.targetBeanName).getClass(); + } + } + return this.targetClass; + } + + public boolean isStatic() { + return false; + } + + public void releaseTarget(Object target) throws Exception { + // Nothing to do here. + } + + + /** + * Copy configuration from the other AbstractBeanFactoryBasedTargetSource object. + * Subclasses should override this if they wish to expose it. + * @param other object to copy configuration from + */ + protected void copyFrom(AbstractBeanFactoryBasedTargetSource other) { + this.targetBeanName = other.targetBeanName; + this.targetClass = other.targetClass; + this.beanFactory = other.beanFactory; + } + + /** + * Replaces this object with a SingletonTargetSource on serialization. + * Protected as otherwise it won't be invoked for subclasses. + * (The writeReplace() method must be visible to the class + * being serialized.) + *

    With this implementation of this method, there is no need to mark + * non-serializable fields in this class or subclasses as transient. + */ + protected Object writeReplace() throws ObjectStreamException { + if (logger.isDebugEnabled()) { + logger.debug("Disconnecting TargetSource [" + this + "]"); + } + try { + // Create disconnected SingletonTargetSource. + return new SingletonTargetSource(getTarget()); + } + catch (Exception ex) { + logger.error("Cannot get target for disconnecting TargetSource [" + this + "]", ex); + throw new NotSerializableException( + "Cannot get target for disconnecting TargetSource [" + this + "]: " + ex); + } + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (other == null || !getClass().equals(other.getClass())) { + return false; + } + AbstractBeanFactoryBasedTargetSource otherTargetSource = (AbstractBeanFactoryBasedTargetSource) other; + return (ObjectUtils.nullSafeEquals(this.beanFactory, otherTargetSource.beanFactory) && + ObjectUtils.nullSafeEquals(this.targetBeanName, otherTargetSource.targetBeanName)); + } + + public int hashCode() { + int hashCode = getClass().hashCode(); + hashCode = 13 * hashCode + ObjectUtils.nullSafeHashCode(this.beanFactory); + hashCode = 13 * hashCode + ObjectUtils.nullSafeHashCode(this.targetBeanName); + return hashCode; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append(ClassUtils.getShortName(getClass())); + sb.append(" for target bean '").append(this.targetBeanName).append("'"); + if (this.targetClass != null) { + sb.append(" of type [").append(this.targetClass.getName()).append("]"); + } + return sb.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/AbstractLazyCreationTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/AbstractLazyCreationTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/AbstractLazyCreationTargetSource.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,101 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.aop.TargetSource; + +/** + * {@link org.springframework.aop.TargetSource} implementation that will + * lazily create a user-managed object. + * + *

    Creation of the lazy target object is controlled by the user by implementing + * the {@link #createObject()} method. This TargetSource will invoke + * this method the first time the proxy is accessed. + * + *

    Useful when you need to pass a reference to some dependency to an object + * but you don't actually want the dependency to be created until it is first used. + * A typical scenario for this is a connection to a remote resource. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 1.2.4 + * @see #isInitialized() + * @see #createObject() + */ +public abstract class AbstractLazyCreationTargetSource implements TargetSource { + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + /** The lazily initialized target object */ + private Object lazyTarget; + + + /** + * Return whether the lazy target object of this TargetSource + * has already been fetched. + */ + public synchronized boolean isInitialized() { + return (this.lazyTarget != null); + } + + /** + * This default implementation returns null if the + * target is null (it is hasn't yet been initialized), + * or the target class if the target has already been initialized. + *

    Subclasses may wish to override this method in order to provide + * a meaningful value when the target is still null. + * @see #isInitialized() + */ + public synchronized Class getTargetClass() { + return (this.lazyTarget != null ? this.lazyTarget.getClass() : null); + } + + public boolean isStatic() { + return false; + } + + /** + * Returns the lazy-initialized target object, + * creating it on-the-fly if it doesn't exist already. + * @see #createObject() + */ + public synchronized Object getTarget() throws Exception { + if (this.lazyTarget == null) { + logger.debug("Initializing lazy target object"); + this.lazyTarget = createObject(); + } + return this.lazyTarget; + } + + public void releaseTarget(Object target) throws Exception { + // nothing to do + } + + + /** + * Subclasses should implement this method to return the lazy initialized object. + * Called the first time the proxy is invoked. + * @return the created object + * @throws Exception if creation failed + */ + protected abstract Object createObject() throws Exception; + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/AbstractPoolingTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/AbstractPoolingTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/AbstractPoolingTargetSource.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,120 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +import org.springframework.aop.support.DefaultIntroductionAdvisor; +import org.springframework.aop.support.DelegatingIntroductionInterceptor; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanInitializationException; +import org.springframework.beans.factory.DisposableBean; + +/** + * Abstract base class for pooling {@link org.springframework.aop.TargetSource} + * implementations which maintain a pool of target instances, acquiring and + * releasing a target object from the pool for each method invocation. + * This abstract base class is independent of concrete pooling technology; + * see the subclass {@link CommonsPoolTargetSource} for a concrete example. + * + *

    Subclasses must implement the {@link #getTarget} and + * {@link #releaseTarget} methods based on their chosen object pool. + * The {@link #newPrototypeInstance()} method inherited from + * {@link AbstractPrototypeBasedTargetSource} can be used to create objects + * in order to put them into the pool. + * + *

    Subclasses must also implement some of the monitoring methods from the + * {@link PoolingConfig} interface. The {@link #getPoolingConfigMixin()} method + * makes these stats available on proxied objects through an IntroductionAdvisor. + * + *

    This class implements the {@link org.springframework.beans.factory.DisposableBean} + * interface in order to force subclasses to implement a {@link #destroy()} + * method, closing down their object pool. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see #getTarget + * @see #releaseTarget + * @see #destroy + */ +public abstract class AbstractPoolingTargetSource extends AbstractPrototypeBasedTargetSource + implements PoolingConfig, DisposableBean { + + /** The maximum size of the pool */ + private int maxSize = -1; + + + /** + * Set the maximum size of the pool. + * Default is -1, indicating no size limit. + */ + public void setMaxSize(int maxSize) { + this.maxSize = maxSize; + } + + /** + * Return the maximum size of the pool. + */ + public int getMaxSize() { + return this.maxSize; + } + + + public final void setBeanFactory(BeanFactory beanFactory) throws BeansException { + super.setBeanFactory(beanFactory); + try { + createPool(); + } + catch (Throwable ex) { + throw new BeanInitializationException("Could not create instance pool for TargetSource", ex); + } + } + + + /** + * Create the pool. + * @throws Exception to avoid placing constraints on pooling APIs + */ + protected abstract void createPool() throws Exception; + + /** + * Acquire an object from the pool. + * @return an object from the pool + * @throws Exception we may need to deal with checked exceptions from pool + * APIs, so we're forgiving with our exception signature + */ + public abstract Object getTarget() throws Exception; + + /** + * Return the given object to the pool. + * @param target object that must have been acquired from the pool + * via a call to getTarget() + * @throws Exception to allow pooling APIs to throw exception + * @see #getTarget + */ + public abstract void releaseTarget(Object target) throws Exception; + + + /** + * Return an IntroductionAdvisor that providing a mixin + * exposing statistics about the pool maintained by this object. + */ + public DefaultIntroductionAdvisor getPoolingConfigMixin() { + DelegatingIntroductionInterceptor dii = new DelegatingIntroductionInterceptor(this); + return new DefaultIntroductionAdvisor(dii, PoolingConfig.class); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/AbstractPrototypeBasedTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/AbstractPrototypeBasedTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/AbstractPrototypeBasedTargetSource.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,85 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; + +/** + * Base class for dynamic TargetSources that can create new prototype bean + * instances to support a pooling or new-instance-per-invocation strategy. + * + *

    Such TargetSources must run in a BeanFactory, as it needs to call the + * getBean method to create a new prototype instance. + * Therefore, this base class extends {@link AbstractBeanFactoryBasedTargetSource}. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see org.springframework.beans.factory.BeanFactory#getBean + * @see PrototypeTargetSource + * @see ThreadLocalTargetSource + * @see CommonsPoolTargetSource + */ +public abstract class AbstractPrototypeBasedTargetSource extends AbstractBeanFactoryBasedTargetSource { + + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + super.setBeanFactory(beanFactory); + + // Check whether the target bean is defined as prototype. + if (!beanFactory.isPrototype(getTargetBeanName())) { + throw new BeanDefinitionStoreException( + "Cannot use prototype-based TargetSource against non-prototype bean with name '" + + getTargetBeanName() + "': instances would not be independent"); + } + } + + /** + * Subclasses should call this method to create a new prototype instance. + * @throws BeansException if bean creation failed + */ + protected Object newPrototypeInstance() throws BeansException { + if (this.logger.isDebugEnabled()) { + this.logger.debug("Creating new instance of bean '" + getTargetBeanName() + "'"); + } + return getBeanFactory().getBean(getTargetBeanName()); + } + + /** + * Subclasses should call this method to destroy an obsolete prototype instance. + * @param target the bean instance to destroy + */ + protected void destroyPrototypeInstance(Object target) { + if (this.logger.isDebugEnabled()) { + this.logger.debug("Destroying instance of bean '" + getTargetBeanName() + "'"); + } + if (getBeanFactory() instanceof ConfigurableBeanFactory) { + ((ConfigurableBeanFactory) getBeanFactory()).destroyBean(getTargetBeanName(), target); + } + else if (target instanceof DisposableBean) { + try { + ((DisposableBean) target).destroy(); + } + catch (Throwable ex) { + this.logger.error("Couldn't invoke destroy method of bean with name '" + getTargetBeanName() + "'", ex); + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/CommonsPoolTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/CommonsPoolTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/CommonsPoolTargetSource.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,290 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +import org.apache.commons.pool.ObjectPool; +import org.apache.commons.pool.PoolableObjectFactory; +import org.apache.commons.pool.impl.GenericObjectPool; + +import org.springframework.beans.BeansException; +import org.springframework.core.Constants; + +/** + * TargetSource implementation that holds objects in a configurable + * Jakarta Commons Pool. + * + *

    By default, an instance of GenericObjectPool is created. + * Subclasses may change the type of ObjectPool used by + * overriding the createObjectPool() method. + * + *

    Provides many configuration properties mirroring those of the Commons Pool + * GenericObjectPool class; these properties are passed to the + * GenericObjectPool during construction. If creating a subclass of this + * class to change the ObjectPool implementation type, pass in the values + * of configuration properties that are relevant to your chosen implementation. + * + *

    The testOnBorrow, testOnReturn and testWhileIdle + * properties are explictly not mirrored because the implementation of + * PoolableObjectFactory used by this class does not implement + * meaningful validation. All exposed Commons Pool properties use the corresponding + * Commons Pool defaults: for example, + * + * @author Rod Johnson + * @author Rob Harrop + * @author Juergen Hoeller + * @see GenericObjectPool + * @see #createObjectPool() + * @see #setMaxSize + * @see #setMaxIdle + * @see #setMinIdle + * @see #setMaxWait + * @see #setTimeBetweenEvictionRunsMillis + * @see #setMinEvictableIdleTimeMillis + */ +public class CommonsPoolTargetSource extends AbstractPoolingTargetSource + implements PoolableObjectFactory { + + private static final Constants constants = new Constants(GenericObjectPool.class); + + + private int maxIdle = GenericObjectPool.DEFAULT_MAX_IDLE; + + private int minIdle = GenericObjectPool.DEFAULT_MIN_IDLE; + + private long maxWait = GenericObjectPool.DEFAULT_MAX_WAIT; + + private long timeBetweenEvictionRunsMillis = GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS; + + private long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS; + + private byte whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION; + + /** + * The Jakarta Commons ObjectPool used to pool target objects + */ + private ObjectPool pool; + + + /** + * Create a CommonsPoolTargetSource with default settings. + * Default maximum size of the pool is 8. + * @see #setMaxSize + * @see GenericObjectPool#setMaxActive + */ + public CommonsPoolTargetSource() { + setMaxSize(GenericObjectPool.DEFAULT_MAX_ACTIVE); + } + + /** + * Set the maximum number of idle objects in the pool. + * Default is 8. + * @see GenericObjectPool#setMaxIdle + */ + public void setMaxIdle(int maxIdle) { + this.maxIdle = maxIdle; + } + + /** + * Return the maximum number of idle objects in the pool. + */ + public int getMaxIdle() { + return this.maxIdle; + } + + /** + * Set the minimum number of idle objects in the pool. + * Default is 0. + * @see GenericObjectPool#setMinIdle + */ + public void setMinIdle(int minIdle) { + this.minIdle = minIdle; + } + + /** + * Return the minimum number of idle objects in the pool. + */ + public int getMinIdle() { + return this.minIdle; + } + + /** + * Set the maximum waiting time for fetching an object from the pool. + * Default is -1, waiting forever. + * @see GenericObjectPool#setMaxWait + */ + public void setMaxWait(long maxWait) { + this.maxWait = maxWait; + } + + /** + * Return the maximum waiting time for fetching an object from the pool. + */ + public long getMaxWait() { + return this.maxWait; + } + + /** + * Set the time between eviction runs that check idle objects whether + * they have been idle for too long or have become invalid. + * Default is -1, not performing any eviction. + * @see GenericObjectPool#setTimeBetweenEvictionRunsMillis + */ + public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { + this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; + } + + /** + * Return the time between eviction runs that check idle objects. + */ + public long getTimeBetweenEvictionRunsMillis() { + return this.timeBetweenEvictionRunsMillis; + } + + /** + * Set the minimum time that an idle object can sit in the pool before + * it becomes subject to eviction. Default is 1800000 (30 minutes). + *

    Note that eviction runs need to be performed to take this + * setting into effect. + * @see #setTimeBetweenEvictionRunsMillis + * @see GenericObjectPool#setMinEvictableIdleTimeMillis + */ + public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { + this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; + } + + /** + * Return the minimum time that an idle object can sit in the pool. + */ + public long getMinEvictableIdleTimeMillis() { + return this.minEvictableIdleTimeMillis; + } + + /** + * Set the action to take when the pool is exhausted. Uses the + * constant names defined in Commons Pool's GenericObjectPool class: + * "WHEN_EXHAUSTED_BLOCK", "WHEN_EXHAUSTED_FAIL", "WHEN_EXHAUSTED_GROW". + * @see #setWhenExhaustedAction(byte) + */ + public void setWhenExhaustedActionName(String whenExhaustedActionName) { + setWhenExhaustedAction(constants.asNumber(whenExhaustedActionName).byteValue()); + } + + /** + * Set the action to take when the pool is exhausted. Uses the + * constant values defined in Commons Pool's GenericObjectPool class. + * @see GenericObjectPool#setWhenExhaustedAction(byte) + * @see GenericObjectPool#WHEN_EXHAUSTED_BLOCK + * @see GenericObjectPool#WHEN_EXHAUSTED_FAIL + * @see GenericObjectPool#WHEN_EXHAUSTED_GROW + */ + public void setWhenExhaustedAction(byte whenExhaustedAction) { + this.whenExhaustedAction = whenExhaustedAction; + } + + /** + * Return the action to take when the pool is exhausted. + */ + public byte getWhenExhaustedAction() { + return whenExhaustedAction; + } + + + /** + * Creates and holds an ObjectPool instance. + * @see #createObjectPool() + */ + protected final void createPool() { + logger.debug("Creating Commons object pool"); + this.pool = createObjectPool(); + } + + /** + * Subclasses can override this if they want to return a specific Commons pool. + * They should apply any configuration properties to the pool here. + *

    Default is a GenericObjectPool instance with the given pool size. + * @return an empty Commons ObjectPool. + * @see org.apache.commons.pool.impl.GenericObjectPool + * @see #setMaxSize + */ + protected ObjectPool createObjectPool() { + GenericObjectPool gop = new GenericObjectPool(this); + gop.setMaxActive(getMaxSize()); + gop.setMaxIdle(getMaxIdle()); + gop.setMinIdle(getMinIdle()); + gop.setMaxWait(getMaxWait()); + gop.setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis()); + gop.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis()); + gop.setWhenExhaustedAction(getWhenExhaustedAction()); + return gop; + } + + + /** + * Borrow an object from the ObjectPool. + */ + public Object getTarget() throws Exception { + return this.pool.borrowObject(); + } + + /** + * Returns the specified object to the underlying ObjectPool. + */ + public void releaseTarget(Object target) throws Exception { + this.pool.returnObject(target); + } + + public int getActiveCount() throws UnsupportedOperationException { + return this.pool.getNumActive(); + } + + public int getIdleCount() throws UnsupportedOperationException { + return this.pool.getNumIdle(); + } + + + /** + * Closes the underlying ObjectPool when destroying this object. + */ + public void destroy() throws Exception { + logger.debug("Closing Commons ObjectPool"); + this.pool.close(); + } + + + //---------------------------------------------------------------------------- + // Implementation of org.apache.commons.pool.PoolableObjectFactory interface + //---------------------------------------------------------------------------- + + public Object makeObject() throws BeansException { + return newPrototypeInstance(); + } + + public void destroyObject(Object obj) throws Exception { + destroyPrototypeInstance(obj); + } + + public boolean validateObject(Object obj) { + return true; + } + + public void activateObject(Object obj) { + } + + public void passivateObject(Object obj) { + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/EmptyTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/EmptyTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/EmptyTargetSource.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,146 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +import java.io.Serializable; + +import org.springframework.aop.TargetSource; +import org.springframework.util.ObjectUtils; + +/** + * Canonical TargetSource when there is no target + * (or just the target class known), and behavior is supplied + * by interfaces and advisors only. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public class EmptyTargetSource implements TargetSource, Serializable { + + /** use serialVersionUID from Spring 1.2 for interoperability */ + private static final long serialVersionUID = 3680494563553489691L; + + + //--------------------------------------------------------------------- + // Static factory methods + //--------------------------------------------------------------------- + + /** + * The canonical (Singleton) instance of this {@link EmptyTargetSource}. + */ + public static final EmptyTargetSource INSTANCE = new EmptyTargetSource(null, true); + + + /** + * Return an EmptyTargetSource for the given target Class. + * @param targetClass the target Class (may be null) + * @see #getTargetClass() + */ + public static EmptyTargetSource forClass(Class targetClass) { + return forClass(targetClass, true); + } + + /** + * Return an EmptyTargetSource for the given target Class. + * @param targetClass the target Class (may be null) + * @param isStatic whether the TargetSource should be marked as static + * @see #getTargetClass() + */ + public static EmptyTargetSource forClass(Class targetClass, boolean isStatic) { + return (targetClass == null && isStatic ? INSTANCE : new EmptyTargetSource(targetClass, isStatic)); + } + + + //--------------------------------------------------------------------- + // Instance implementation + //--------------------------------------------------------------------- + + private final Class targetClass; + + private final boolean isStatic; + + + /** + * Create a new instance of the {@link EmptyTargetSource} class. + *

    This constructor is private to enforce the + * Singleton pattern / factory method pattern. + * @param targetClass the target class to expose (may be null) + * @param isStatic whether the TargetSource is marked as static + */ + private EmptyTargetSource(Class targetClass, boolean isStatic) { + this.targetClass = targetClass; + this.isStatic = isStatic; + } + + /** + * Always returns the specified target Class, or null if none. + */ + public Class getTargetClass() { + return this.targetClass; + } + + /** + * Always returns true. + */ + public boolean isStatic() { + return this.isStatic; + } + + /** + * Always returns null. + */ + public Object getTarget() { + return null; + } + + /** + * Nothing to release. + */ + public void releaseTarget(Object target) { + } + + + /** + * Returns the canonical instance on deserialization in case + * of no target class, thus protecting the Singleton pattern. + */ + private Object readResolve() { + return (this.targetClass == null && this.isStatic ? INSTANCE : this); + } + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof EmptyTargetSource)) { + return false; + } + EmptyTargetSource otherTs = (EmptyTargetSource) other; + return (ObjectUtils.nullSafeEquals(this.targetClass, otherTs.targetClass) && this.isStatic == otherTs.isStatic); + } + + public int hashCode() { + return EmptyTargetSource.class.hashCode() * 13 + ObjectUtils.nullSafeHashCode(this.targetClass); + } + + public String toString() { + return "EmptyTargetSource: " + + (this.targetClass != null ? "target class [" + this.targetClass.getName() + "]" : "no target class") + + ", " + (this.isStatic ? "static" : "dynamic"); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/HotSwappableTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/HotSwappableTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/HotSwappableTargetSource.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,110 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +import java.io.Serializable; + +import org.springframework.aop.TargetSource; +import org.springframework.util.Assert; + +/** + * {@link org.springframework.aop.TargetSource} implementation that + * caches a local target object, but allows the target to be swapped + * while the application is running. + * + *

    If configuring an object of this class in a Spring IoC container, + * use constructor injection. + * + *

    This TargetSource is serializable if the target is at the time + * of serialization. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public class HotSwappableTargetSource implements TargetSource, Serializable { + + /** use serialVersionUID from Spring 1.2 for interoperability */ + private static final long serialVersionUID = 7497929212653839187L; + + + /** The current target object */ + private Object target; + + + /** + * Create a new HotSwappableTargetSource with the given initial target object. + * @param initialTarget the initial target object + */ + public HotSwappableTargetSource(Object initialTarget) { + Assert.notNull(initialTarget, "Target object must not be null"); + this.target = initialTarget; + } + + + /** + * Return the type of the current target object. + *

    The returned type should usually be constant across all target objects. + */ + public synchronized Class getTargetClass() { + return this.target.getClass(); + } + + public final boolean isStatic() { + return false; + } + + public synchronized Object getTarget() { + return this.target; + } + + public void releaseTarget(Object target) { + // nothing to do + } + + + /** + * Swap the target, returning the old target object. + * @param newTarget the new target object + * @return the old target object + * @throws IllegalArgumentException if the new target is invalid + */ + public synchronized Object swap(Object newTarget) throws IllegalArgumentException { + Assert.notNull(newTarget, "Target object must not be null"); + Object old = this.target; + this.target = newTarget; + return old; + } + + + /** + * Two HotSwappableTargetSources are equal if the current target + * objects are equal. + */ + public boolean equals(Object other) { + return (this == other || (other instanceof HotSwappableTargetSource && + this.target.equals(((HotSwappableTargetSource) other).target))); + } + + public int hashCode() { + return HotSwappableTargetSource.class.hashCode(); + } + + public String toString() { + return "HotSwappableTargetSource for target: " + this.target; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/LazyInitTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/LazyInitTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/LazyInitTargetSource.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +import org.springframework.beans.BeansException; + +/** + * {@link org.springframework.aop.TargetSource} that lazily accesses a + * singleton bean from a {@link org.springframework.beans.factory.BeanFactory}. + * + *

    Useful when a proxy reference is needed on initialization but + * the actual target object should not be initialized until first use. + * When the target bean is defined in an + * {@link org.springframework.context.ApplicationContext} (or a + * BeanFactory that is eagerly pre-instantiating singleton beans) + * it must be marked as "lazy-init" too, else it will be instantiated by said + * ApplicationContext (or BeanFactory) on startup. + *

    For example: + * + *

    + * <bean id="serviceTarget" class="example.MyService" lazy-init="true">
    + *   ...
    + * </bean>
    + *
    + * <bean id="service" class="org.springframework.aop.framework.ProxyFactoryBean">
    + *   <property name="targetSource">
    + *     <bean class="org.springframework.aop.target.LazyInitTargetSource">
    + *       <property name="targetBeanName"><idref local="serviceTarget"/></property>
    + *     </bean>
    + *   </property>
    + * </bean>
    + * + * The "serviceTarget" bean will not get initialized until a method on the + * "service" proxy gets invoked. + * + *

    Subclasses can extend this class and override the {@link #postProcessTargetObject(Object)} to + * perform some additional processing with the target object when it is first loaded. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @since 1.1.4 + * @see org.springframework.beans.factory.BeanFactory#getBean + * @see #postProcessTargetObject + */ +public class LazyInitTargetSource extends AbstractBeanFactoryBasedTargetSource { + + private Object target; + + + public synchronized Object getTarget() throws BeansException { + if (this.target == null) { + this.target = getBeanFactory().getBean(getTargetBeanName()); + postProcessTargetObject(this.target); + } + return this.target; + } + + /** + * Subclasses may override this method to perform additional processing on + * the target object when it is first loaded. + * @param targetObject the target object that has just been instantiated (and configured) + */ + protected void postProcessTargetObject(Object targetObject) { + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/PoolingConfig.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/PoolingConfig.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/PoolingConfig.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +/** + * Config interface for a pooling target source. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public interface PoolingConfig { + + /** + * Return the maximum size of the pool. + */ + int getMaxSize(); + + /** + * Return the number of active objects in the pool. + * @throws UnsupportedOperationException if not supported by the pool + */ + int getActiveCount() throws UnsupportedOperationException; + + /** + * Return the number of idle objects in the pool. + * @throws UnsupportedOperationException if not supported by the pool + */ + int getIdleCount() throws UnsupportedOperationException; + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/PrototypeTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/PrototypeTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/PrototypeTargetSource.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +import org.springframework.beans.BeansException; + +/** + * TargetSource that creates a new instance of the target bean for each + * request, destroying each instance on release (after each request). + * Obtains bean instances from its containing + * {@link org.springframework.beans.factory.BeanFactory}. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see #setBeanFactory + * @see #setTargetBeanName + */ +public class PrototypeTargetSource extends AbstractPrototypeBasedTargetSource { + + /** + * Obtain a new prototype instance for every call. + * @see #newPrototypeInstance() + */ + public Object getTarget() throws BeansException { + return newPrototypeInstance(); + } + + /** + * Destroy the given independent instance. + * @see #destroyPrototypeInstance + */ + public void releaseTarget(Object target) { + destroyPrototypeInstance(target); + } + + public String toString() { + return "PrototypeTargetSource for target bean with name '" + getTargetBeanName() + "'"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/SimpleBeanTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/SimpleBeanTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/SimpleBeanTargetSource.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +/** + * Simple {@link org.springframework.aop.TargetSource} implementation, + * freshly obtaining the specified target bean from its containing + * Spring {@link org.springframework.beans.factory.BeanFactory}. + * + *

    Can obtain any kind of target bean: singleton, scoped, or prototype. + * Typically used for scoped beans. + * + * @author Juergen Hoeller + * @since 2.0.3 + */ +public class SimpleBeanTargetSource extends AbstractBeanFactoryBasedTargetSource { + + public Object getTarget() throws Exception { + return getBeanFactory().getBean(getTargetBeanName()); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/SingletonTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/SingletonTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/SingletonTargetSource.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,101 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +import java.io.Serializable; + +import org.springframework.aop.TargetSource; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + +/** + * Implementation of the {@link org.springframework.aop.TargetSource} interface + * that holds a given object. This is the default implementation of the TargetSource + * interface, as used by the Spring AOP framework. There is usually no need to + * create objects of this class in application code. + * + *

    This class is serializable. However, the actual serializability of a + * SingletonTargetSource will depend on whether the target is serializable. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see org.springframework.aop.framework.AdvisedSupport#setTarget(Object) + */ +public class SingletonTargetSource implements TargetSource, Serializable { + + /** use serialVersionUID from Spring 1.2 for interoperability */ + private static final long serialVersionUID = 9031246629662423738L; + + + /** Target cached and invoked using reflection */ + private final Object target; + + + /** + * Create a new SingletonTargetSource for the given target. + * @param target the target object + */ + public SingletonTargetSource(Object target) { + Assert.notNull(target, "Target object must not be null"); + this.target = target; + } + + + public Class getTargetClass() { + return this.target.getClass(); + } + + public Object getTarget() { + return this.target; + } + + public void releaseTarget(Object target) { + // nothing to do + } + + public boolean isStatic() { + return true; + } + + + /** + * Two invoker interceptors are equal if they have the same target or if the + * targets or the targets are equal. + */ + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof SingletonTargetSource)) { + return false; + } + SingletonTargetSource otherTargetSource = (SingletonTargetSource) other; + return this.target.equals(otherTargetSource.target); + } + + /** + * SingletonTargetSource uses the hash code of the target object. + */ + public int hashCode() { + return this.target.hashCode(); + } + + public String toString() { + return "SingletonTargetSource for target object [" + ObjectUtils.identityToString(this.target) + "]"; + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/ThreadLocalTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/ThreadLocalTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/ThreadLocalTargetSource.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,138 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.springframework.aop.IntroductionAdvisor; +import org.springframework.aop.support.DefaultIntroductionAdvisor; +import org.springframework.aop.support.DelegatingIntroductionInterceptor; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.DisposableBean; + +/** + * Alternative to an object pool. This TargetSource uses a threading model in which + * every thread has its own copy of the target. There's no contention for targets. + * Target object creation is kept to a minimum on the running server. + * + *

    Application code is written as to a normal pool; callers can't assume they + * will be dealing with the same instance in invocations in different threads. + * However, state can be relied on during the operations of a single thread: + * for example, if one caller makes repeated calls on the AOP proxy. + * + *

    Cleanup of thread-bound objects is performed on BeanFactory destruction, + * calling their DisposableBean.destroy() method if available. + * Be aware that many thread-bound objects can be around until the application + * actually shuts down. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + * @see ThreadLocalTargetSourceStats + * @see org.springframework.beans.factory.DisposableBean#destroy() + */ +public class ThreadLocalTargetSource extends AbstractPrototypeBasedTargetSource + implements ThreadLocalTargetSourceStats, DisposableBean { + + /** + * ThreadLocal holding the target associated with the current + * thread. Unlike most ThreadLocals, which are static, this variable + * is meant to be per thread per instance of the ThreadLocalTargetSource class. + */ + private final ThreadLocal targetInThread = new ThreadLocal() { + public String toString() { + return "Thread-local instance of bean '" + getTargetBeanName() + "'"; + } + }; + + /** + * Set of managed targets, enabling us to keep track of the targets we've created. + */ + private final Set targetSet = Collections.synchronizedSet(new HashSet()); + + private int invocationCount; + + private int hitCount; + + + /** + * Implementation of abstract getTarget() method. + * We look for a target held in a ThreadLocal. If we don't find one, + * we create one and bind it to the thread. No synchronization is required. + */ + public Object getTarget() throws BeansException { + ++this.invocationCount; + Object target = this.targetInThread.get(); + if (target == null) { + if (logger.isDebugEnabled()) { + logger.debug("No target for prototype '" + getTargetBeanName() + "' bound to thread: " + + "creating one and binding it to thread '" + Thread.currentThread().getName() + "'"); + } + // Associate target with ThreadLocal. + target = newPrototypeInstance(); + this.targetInThread.set(target); + this.targetSet.add(target); + } + else { + ++this.hitCount; + } + return target; + } + + /** + * Dispose of targets if necessary; clear ThreadLocal. + * @see #destroyPrototypeInstance + */ + public void destroy() { + logger.debug("Destroying ThreadLocalTargetSource bindings"); + synchronized (this.targetSet) { + for (Iterator it = this.targetSet.iterator(); it.hasNext(); ) { + destroyPrototypeInstance(it.next()); + } + this.targetSet.clear(); + } + // Clear ThreadLocal, just in case. + this.targetInThread.set(null); + } + + + public int getInvocationCount() { + return this.invocationCount; + } + + public int getHitCount() { + return this.hitCount; + } + + public int getObjectCount() { + return this.targetSet.size(); + } + + + /** + * Return an introduction advisor mixin that allows the AOP proxy to be + * cast to ThreadLocalInvokerStats. + */ + public IntroductionAdvisor getStatsMixin() { + DelegatingIntroductionInterceptor dii = new DelegatingIntroductionInterceptor(this); + return new DefaultIntroductionAdvisor(dii, ThreadLocalTargetSourceStats.class); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/ThreadLocalTargetSourceStats.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/ThreadLocalTargetSourceStats.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/ThreadLocalTargetSourceStats.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target; + +/** + * Statistics for a ThreadLocal TargetSource. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public interface ThreadLocalTargetSourceStats { + + /** + * Return the number of client invocations. + */ + int getInvocationCount(); + + /** + * Return the number of hits that were satisfied by a thread-bound object. + */ + int getHitCount(); + + /** + * Return the number of thread-bound objects created. + */ + int getObjectCount(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/package.html 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,15 @@ + + + +This package contains implementations of the org.springframework.aop.TargetSource interface. +
    +The simplest implementation is the SingletonTargetSource, used by default in the AOP framework +to wrap a single target instance. This is normally appropriate. + +
    +Other provided implementations include pooling implementations, that provide a target +from a pool for each request, ensuring a single threaded programming model; and a +"prototype" implementation, that uses a new target instance for each invocation. + + + Index: 3rdParty_sources/spring/org/springframework/aop/target/dynamic/AbstractRefreshableTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/dynamic/AbstractRefreshableTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/dynamic/AbstractRefreshableTargetSource.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,151 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target.dynamic; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.aop.TargetSource; + +/** + * Abstract {@link org.springframework.aop.TargetSource} implementation that + * wraps a refreshable target object. Subclasses can determine whether a + * refresh is required, and need to provide fresh target objects. + * + *

    Implements the {@link Refreshable} interface in order to allow for + * explicit control over the refresh status. + * + * @author Rod Johnson + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + * @see #requiresRefresh() + * @see #freshTarget() + */ +public abstract class AbstractRefreshableTargetSource implements TargetSource, Refreshable { + + /** Logger available to subclasses */ + protected Log logger = LogFactory.getLog(getClass()); + + protected Object targetObject; + + private long refreshCheckDelay = -1; + + private long lastRefreshCheck = -1; + + private long lastRefreshTime = -1; + + private long refreshCount = 0; + + + /** + * Set the delay between refresh checks, in milliseconds. + * Default is -1, indicating no refresh checks at all. + *

    Note that an actual refresh will only happen when + * {@link #requiresRefresh()} returns true. + */ + public void setRefreshCheckDelay(long refreshCheckDelay) { + this.refreshCheckDelay = refreshCheckDelay; + } + + + public synchronized Class getTargetClass() { + if (this.targetObject == null) { + refresh(); + } + return this.targetObject.getClass(); + } + + /** + * Not static. + */ + public boolean isStatic() { + return false; + } + + public final synchronized Object getTarget() { + if ((refreshCheckDelayElapsed() && requiresRefresh()) || this.targetObject == null) { + refresh(); + } + return this.targetObject; + } + + /** + * No need to release target. + */ + public void releaseTarget(Object object) { + } + + + public final synchronized void refresh() { + logger.debug("Attempting to refresh target"); + + this.targetObject = freshTarget(); + this.refreshCount++; + this.lastRefreshTime = System.currentTimeMillis(); + + logger.debug("Target refreshed successfully"); + } + + public synchronized long getRefreshCount() { + return this.refreshCount; + } + + public synchronized long getLastRefreshTime() { + return this.lastRefreshTime; + } + + + private boolean refreshCheckDelayElapsed() { + if (this.refreshCheckDelay < 0) { + return false; + } + + long currentTimeMillis = System.currentTimeMillis(); + + if (this.lastRefreshCheck < 0 || currentTimeMillis - this.lastRefreshCheck > this.refreshCheckDelay) { + // Going to perform a refresh check - update the timestamp. + this.lastRefreshCheck = currentTimeMillis; + logger.debug("Refresh check delay elapsed - checking whether refresh is required"); + return true; + } + + return false; + } + + + /** + * Determine whether a refresh is required. + * Invoked for each refresh check, after the refresh check delay has elapsed. + *

    The default implementation always returns true, triggering + * a refresh every time the delay has elapsed. To be overridden by subclasses + * with an appropriate check of the underlying target resource. + * @return whether a refresh is required + */ + protected boolean requiresRefresh() { + return true; + } + + /** + * Obtain a fresh target object. + *

    Only invoked if a refresh check has found that a refresh is required + * (that is, {@link #requiresRefresh()} has returned true). + * @return the fresh target object + */ + protected abstract Object freshTarget(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/dynamic/BeanFactoryRefreshableTargetSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/dynamic/BeanFactoryRefreshableTargetSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/dynamic/BeanFactoryRefreshableTargetSource.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,79 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target.dynamic; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.util.Assert; + +/** + * Refreshable TargetSource that fetches fresh target beans from a BeanFactory. + * + *

    Can be subclassed to override requiresRefresh() to suppress + * unnecessary refreshes. By default, a refresh will be performed every time + * the "refreshCheckDelay" has elapsed. + * + * @author Rob Harrop + * @author Rod Johnson + * @author Juergen Hoeller + * @author Mark Fisher + * @since 2.0 + * @see org.springframework.beans.factory.BeanFactory + * @see #requiresRefresh() + * @see #setRefreshCheckDelay + */ +public class BeanFactoryRefreshableTargetSource extends AbstractRefreshableTargetSource { + + private final BeanFactory beanFactory; + + private final String beanName; + + + /** + * Create a new BeanFactoryRefreshableTargetSource for the given + * bean factory and bean name. + *

    Note that the passed-in BeanFactory should have an appropriate + * bean definition set up for the given bean name. + * @param beanFactory the BeanFactory to fetch beans from + * @param beanName the name of the target bean + */ + public BeanFactoryRefreshableTargetSource(BeanFactory beanFactory, String beanName) { + Assert.notNull(beanFactory, "BeanFactory is required"); + Assert.notNull(beanName, "Bean name is required"); + this.beanFactory = beanFactory; + this.beanName = beanName; + } + + + /** + * Retrieve a fresh target object. + */ + protected final Object freshTarget() { + return this.obtainFreshBean(this.beanFactory, this.beanName); + } + + /** + * A template method that subclasses may override to provide a + * fresh target object for the given bean factory and bean name. + *

    This default implementation fetches a new target bean + * instance from the bean factory. + * @see org.springframework.beans.factory.BeanFactory#getBean + */ + protected Object obtainFreshBean(BeanFactory beanFactory, String beanName) { + return beanFactory.getBean(beanName); + } + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/dynamic/Refreshable.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/dynamic/Refreshable.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/dynamic/Refreshable.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.aop.target.dynamic; + +/** + * Interface to be implemented by dynamic target objects, + * which support reloading and optionally polling for updates. + * + * @author Rod Johnson + * @author Rob Harrop + * @since 2.0 + */ +public interface Refreshable { + + /** + * Refresh the underlying target object. + */ + void refresh(); + + /** + * Return the number of actual refreshes since startup. + */ + long getRefreshCount(); + + /** + * Return the last time an actual refresh happened (as timestamp). + */ + long getLastRefreshTime(); + +} Index: 3rdParty_sources/spring/org/springframework/aop/target/dynamic/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/aop/target/dynamic/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/aop/target/dynamic/package.html 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,7 @@ + + + +Support for AOP-based refreshing of target objects. + + + Index: 3rdParty_sources/spring/org/springframework/beans/AbstractPropertyAccessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/AbstractPropertyAccessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/AbstractPropertyAccessor.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,140 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +/** + * Abstract implementation of the {@link PropertyAccessor} interface. + * Provides base implementations of all convenience methods, with the + * implementation of actual property access left to subclasses. + * + * @author Juergen Hoeller + * @since 2.0 + * @see #getPropertyValue + * @see #setPropertyValue + */ +public abstract class AbstractPropertyAccessor extends PropertyEditorRegistrySupport + implements ConfigurablePropertyAccessor { + + private boolean extractOldValueForEditor = false; + + + public void setExtractOldValueForEditor(boolean extractOldValueForEditor) { + this.extractOldValueForEditor = extractOldValueForEditor; + } + + public boolean isExtractOldValueForEditor() { + return this.extractOldValueForEditor; + } + + + public void setPropertyValue(PropertyValue pv) throws BeansException { + setPropertyValue(pv.getName(), pv.getValue()); + } + + public void setPropertyValues(Map map) throws BeansException { + setPropertyValues(new MutablePropertyValues(map)); + } + + public void setPropertyValues(PropertyValues pvs) throws BeansException { + setPropertyValues(pvs, false, false); + } + + public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown) throws BeansException { + setPropertyValues(pvs, ignoreUnknown, false); + } + + public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid) + throws BeansException { + + List propertyAccessExceptions = null; + List propertyValues = (pvs instanceof MutablePropertyValues ? + ((MutablePropertyValues) pvs).getPropertyValueList() : Arrays.asList(pvs.getPropertyValues())); + for (Iterator it = propertyValues.iterator(); it.hasNext();) { + PropertyValue pv = (PropertyValue) it.next(); + try { + // This method may throw any BeansException, which won't be caught + // here, if there is a critical failure such as no matching field. + // We can attempt to deal only with less serious exceptions. + setPropertyValue(pv); + } + catch (NotWritablePropertyException ex) { + if (!ignoreUnknown) { + throw ex; + } + // Otherwise, just ignore it and continue... + } + catch (NullValueInNestedPathException ex) { + if (!ignoreInvalid) { + throw ex; + } + // Otherwise, just ignore it and continue... + } + catch (PropertyAccessException ex) { + if (propertyAccessExceptions == null) { + propertyAccessExceptions = new LinkedList(); + } + propertyAccessExceptions.add(ex); + } + } + + // If we encountered individual exceptions, throw the composite exception. + if (propertyAccessExceptions != null) { + PropertyAccessException[] paeArray = (PropertyAccessException[]) + propertyAccessExceptions.toArray(new PropertyAccessException[propertyAccessExceptions.size()]); + throw new PropertyBatchUpdateException(paeArray); + } + } + + public Object convertIfNecessary(Object value, Class requiredType) throws TypeMismatchException { + return convertIfNecessary(value, requiredType, null); + } + + + // Redefined with public visibility. + public Class getPropertyType(String propertyPath) { + return null; + } + + /** + * Actually get the value of a property. + * @param propertyName name of the property to get the value of + * @return the value of the property + * @throws InvalidPropertyException if there is no such property or + * if the property isn't readable + * @throws PropertyAccessException if the property was valid but the + * accessor method failed + */ + public abstract Object getPropertyValue(String propertyName) throws BeansException; + + /** + * Actually set a property value. + * @param propertyName name of the property to set value of + * @param value the new value + * @throws InvalidPropertyException if there is no such property or + * if the property isn't writable + * @throws PropertyAccessException if the property was valid but the + * accessor method failed or a type mismatch occured + */ + public abstract void setPropertyValue(String propertyName, Object value) throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/BeanInstantiationException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/BeanInstantiationException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/BeanInstantiationException.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Exception thrown when instantiation of a bean failed. + * Carries the offending bean class. + * + * @author Juergen Hoeller + * @since 1.2.8 + */ +public class BeanInstantiationException extends FatalBeanException { + + private Class beanClass; + + + /** + * Create a new BeanInstantiationException. + * @param beanClass the offending bean class + * @param msg the detail message + */ + public BeanInstantiationException(Class beanClass, String msg) { + this(beanClass, msg, null); + } + + /** + * Create a new BeanInstantiationException. + * @param beanClass the offending bean class + * @param msg the detail message + * @param cause the root cause + */ + public BeanInstantiationException(Class beanClass, String msg, Throwable cause) { + super("Could not instantiate bean class [" + beanClass.getName() + "]: " + msg, cause); + this.beanClass = beanClass; + } + + /** + * Return the offending bean class. + */ + public Class getBeanClass() { + return beanClass; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/BeanMetadataAttribute.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/BeanMetadataAttribute.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/BeanMetadataAttribute.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,98 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + +/** + * Holder for a key-value style attribute that is part of a bean definition. + * Keeps track of the definition source in addition to the key-value pair. + * + * @author Juergen Hoeller + * @since 2.5 + */ +public class BeanMetadataAttribute implements BeanMetadataElement { + + private final String name; + + private final Object value; + + private Object source; + + + /** + * Create a new AttributeValue instance. + * @param name the name of the attribute (never null) + * @param value the value of the attribute (possibly before type conversion) + */ + public BeanMetadataAttribute(String name, Object value) { + Assert.notNull(name, "Name must not be null"); + this.name = name; + this.value = value; + } + + + /** + * Return the name of the attribute. + */ + public String getName() { + return this.name; + } + + /** + * Return the value of the attribute. + */ + public Object getValue() { + return this.value; + } + + /** + * Set the configuration source Object for this metadata element. + *

    The exact type of the object will depend on the configuration mechanism used. + */ + public void setSource(Object source) { + this.source = source; + } + + public Object getSource() { + return this.source; + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof BeanMetadataAttribute)) { + return false; + } + BeanMetadataAttribute otherMa = (BeanMetadataAttribute) other; + return (this.name.equals(otherMa.name) && + ObjectUtils.nullSafeEquals(this.value, otherMa.value) && + ObjectUtils.nullSafeEquals(this.source, otherMa.source)); + } + + public int hashCode() { + return this.name.hashCode() * 29 + ObjectUtils.nullSafeHashCode(this.value); + } + + public String toString() { + return "metadata attribute '" + this.name + "'"; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/BeanMetadataAttributeAccessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/BeanMetadataAttributeAccessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/BeanMetadataAttributeAccessor.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,79 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import org.springframework.core.AttributeAccessorSupport; + +/** + * Extension of {@link org.springframework.core.AttributeAccessorSupport}, + * holding attributes as {@link BeanMetadataAttribute} objects in order + * to keep track of the definition source. + * + * @author Juergen Hoeller + * @since 2.5 + */ +public class BeanMetadataAttributeAccessor extends AttributeAccessorSupport implements BeanMetadataElement { + + private Object source; + + + /** + * Set the configuration source Object for this metadata element. + *

    The exact type of the object will depend on the configuration mechanism used. + */ + public void setSource(Object source) { + this.source = source; + } + + public Object getSource() { + return this.source; + } + + + /** + * Add the given BeanMetadataAttribute to this accessor's set of attributes. + * @param attribute the BeanMetadataAttribute object to register + */ + public void addMetadataAttribute(BeanMetadataAttribute attribute) { + super.setAttribute(attribute.getName(), attribute); + } + + /** + * Look up the given BeanMetadataAttribute in this accessor's set of attributes. + * @param name the name of the attribute + * @return the corresponding BeanMetadataAttribute object, + * or null if no such attribute defined + */ + public BeanMetadataAttribute getMetadataAttribute(String name) { + return (BeanMetadataAttribute) super.getAttribute(name); + } + + public void setAttribute(String name, Object value) { + super.setAttribute(name, new BeanMetadataAttribute(name, value)); + } + + public Object getAttribute(String name) { + BeanMetadataAttribute attribute = (BeanMetadataAttribute) super.getAttribute(name); + return (attribute != null ? attribute.getValue() : null); + } + + public Object removeAttribute(String name) { + BeanMetadataAttribute attribute = (BeanMetadataAttribute) super.removeAttribute(name); + return (attribute != null ? attribute.getValue() : null); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/BeanMetadataElement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/BeanMetadataElement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/BeanMetadataElement.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Interface to be implemented by bean metadata elements + * that carry a configuration source object. + * + * @author Juergen Hoeller + * @since 2.0 + */ +public interface BeanMetadataElement { + + /** + * Return the configuration source Object for this metadata element + * (may be null). + */ + Object getSource(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/BeanUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/BeanUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/BeanUtils.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,598 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyDescriptor; +import java.beans.PropertyEditor; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.net.URI; +import java.net.URL; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.WeakHashMap; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.core.MethodParameter; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; + +/** + * Static convenience methods for JavaBeans: for instantiating beans, + * checking bean property types, copying bean properties, etc. + * + *

    Mainly for use within the framework, but to some degree also + * useful for application classes. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + */ +public abstract class BeanUtils { + + private static final Log logger = LogFactory.getLog(BeanUtils.class); + + private static final Map unknownEditorTypes = Collections.synchronizedMap(new WeakHashMap()); + + + /** + * Convenience method to instantiate a class using its no-arg constructor. + * As this method doesn't try to load classes by name, it should avoid + * class-loading issues. + *

    Note that this method tries to set the constructor accessible + * if given a non-accessible (that is, non-public) constructor. + * @param clazz class to instantiate + * @return the new instance + * @throws BeanInstantiationException if the bean cannot be instantiated + */ + public static Object instantiateClass(Class clazz) throws BeanInstantiationException { + Assert.notNull(clazz, "Class must not be null"); + if (clazz.isInterface()) { + throw new BeanInstantiationException(clazz, "Specified class is an interface"); + } + try { + return instantiateClass(clazz.getDeclaredConstructor((Class[]) null), null); + } + catch (NoSuchMethodException ex) { + throw new BeanInstantiationException(clazz, "No default constructor found", ex); + } + } + + /** + * Convenience method to instantiate a class using the given constructor. + * As this method doesn't try to load classes by name, it should avoid + * class-loading issues. + *

    Note that this method tries to set the constructor accessible + * if given a non-accessible (that is, non-public) constructor. + * @param ctor the constructor to instantiate + * @param args the constructor arguments to apply + * @return the new instance + * @throws BeanInstantiationException if the bean cannot be instantiated + */ + public static Object instantiateClass(Constructor ctor, Object[] args) throws BeanInstantiationException { + Assert.notNull(ctor, "Constructor must not be null"); + try { + ReflectionUtils.makeAccessible(ctor); + return ctor.newInstance(args); + } + catch (InstantiationException ex) { + throw new BeanInstantiationException(ctor.getDeclaringClass(), + "Is it an abstract class?", ex); + } + catch (IllegalAccessException ex) { + throw new BeanInstantiationException(ctor.getDeclaringClass(), + "Has the class definition changed? Is the constructor accessible?", ex); + } + catch (IllegalArgumentException ex) { + throw new BeanInstantiationException(ctor.getDeclaringClass(), + "Illegal arguments for constructor", ex); + } + catch (InvocationTargetException ex) { + throw new BeanInstantiationException(ctor.getDeclaringClass(), + "Constructor threw exception", ex.getTargetException()); + } + } + + /** + * Find a method with the given method name and the given parameter types, + * declared on the given class or one of its superclasses. Prefers public methods, + * but will return a protected, package access, or private method too. + *

    Checks Class.getMethod first, falling back to + * findDeclaredMethod. This allows to find public methods + * without issues even in environments with restricted Java security settings. + * @param clazz the class to check + * @param methodName the name of the method to find + * @param paramTypes the parameter types of the method to find + * @return the Method object, or null if not found + * @see java.lang.Class#getMethod + * @see #findDeclaredMethod + */ + public static Method findMethod(Class clazz, String methodName, Class[] paramTypes) { + try { + return clazz.getMethod(methodName, paramTypes); + } + catch (NoSuchMethodException ex) { + return findDeclaredMethod(clazz, methodName, paramTypes); + } + } + + /** + * Find a method with the given method name and the given parameter types, + * declared on the given class or one of its superclasses. Will return a public, + * protected, package access, or private method. + *

    Checks Class.getDeclaredMethod, cascading upwards to all superclasses. + * @param clazz the class to check + * @param methodName the name of the method to find + * @param paramTypes the parameter types of the method to find + * @return the Method object, or null if not found + * @see java.lang.Class#getDeclaredMethod + */ + public static Method findDeclaredMethod(Class clazz, String methodName, Class[] paramTypes) { + try { + return clazz.getDeclaredMethod(methodName, paramTypes); + } + catch (NoSuchMethodException ex) { + if (clazz.getSuperclass() != null) { + return findDeclaredMethod(clazz.getSuperclass(), methodName, paramTypes); + } + return null; + } + } + + /** + * Find a method with the given method name and minimal parameters (best case: none), + * declared on the given class or one of its superclasses. Prefers public methods, + * but will return a protected, package access, or private method too. + *

    Checks Class.getMethods first, falling back to + * findDeclaredMethodWithMinimalParameters. This allows to find public + * methods without issues even in environments with restricted Java security settings. + * @param clazz the class to check + * @param methodName the name of the method to find + * @return the Method object, or null if not found + * @throws IllegalArgumentException if methods of the given name were found but + * could not be resolved to a unique method with minimal parameters + * @see java.lang.Class#getMethods + * @see #findDeclaredMethodWithMinimalParameters + */ + public static Method findMethodWithMinimalParameters(Class clazz, String methodName) + throws IllegalArgumentException { + + Method targetMethod = doFindMethodWithMinimalParameters(clazz.getDeclaredMethods(), methodName); + if (targetMethod == null) { + return findDeclaredMethodWithMinimalParameters(clazz, methodName); + } + return targetMethod; + } + + /** + * Find a method with the given method name and minimal parameters (best case: none), + * declared on the given class or one of its superclasses. Will return a public, + * protected, package access, or private method. + *

    Checks Class.getDeclaredMethods, cascading upwards to all superclasses. + * @param clazz the class to check + * @param methodName the name of the method to find + * @return the Method object, or null if not found + * @throws IllegalArgumentException if methods of the given name were found but + * could not be resolved to a unique method with minimal parameters + * @see java.lang.Class#getDeclaredMethods + */ + public static Method findDeclaredMethodWithMinimalParameters(Class clazz, String methodName) + throws IllegalArgumentException { + + Method targetMethod = doFindMethodWithMinimalParameters(clazz.getDeclaredMethods(), methodName); + if (targetMethod == null && clazz.getSuperclass() != null) { + return findDeclaredMethodWithMinimalParameters(clazz.getSuperclass(), methodName); + } + return targetMethod; + } + + /** + * Find a method with the given method name and minimal parameters (best case: none) + * in the given list of methods. + * @param methods the methods to check + * @param methodName the name of the method to find + * @return the Method object, or null if not found + * @throws IllegalArgumentException if methods of the given name were found but + * could not be resolved to a unique method with minimal parameters + */ + private static Method doFindMethodWithMinimalParameters(Method[] methods, String methodName) + throws IllegalArgumentException { + + Method targetMethod = null; + int numMethodsFoundWithCurrentMinimumArgs = 0; + for (int i = 0; i < methods.length; i++) { + if (methods[i].getName().equals(methodName)) { + int numParams = methods[i].getParameterTypes().length; + if (targetMethod == null || + numParams < targetMethod.getParameterTypes().length) { + targetMethod = methods[i]; + numMethodsFoundWithCurrentMinimumArgs = 1; + } + else { + if (targetMethod.getParameterTypes().length == numParams) { + // Additional candidate with same length. + numMethodsFoundWithCurrentMinimumArgs++; + } + } + } + } + if (numMethodsFoundWithCurrentMinimumArgs > 1) { + throw new IllegalArgumentException("Cannot resolve method '" + methodName + + "' to a unique method. Attempted to resolve to overloaded method with " + + "the least number of parameters, but there were " + + numMethodsFoundWithCurrentMinimumArgs + " candidates."); + } + return targetMethod; + } + + /** + * Parse a method signature in the form methodName[([arg_list])], + * where arg_list is an optional, comma-separated list of fully-qualified + * type names, and attempts to resolve that signature against the supplied Class. + *

    When not supplying an argument list (methodName) the method whose name + * matches and has the least number of parameters will be returned. When supplying an + * argument type list, only the method whose name and argument types match will be returned. + *

    Note then that methodName and methodName() are not + * resolved in the same way. The signature methodName means the method called + * methodName with the least number of arguments, whereas methodName() + * means the method called methodName with exactly 0 arguments. + *

    If no method can be found, then null is returned. + * @param signature the method signature as String representation + * @param clazz the class to resolve the method signature against + * @return the resolved Method + * @see #findMethod + * @see #findMethodWithMinimalParameters + */ + public static Method resolveSignature(String signature, Class clazz) { + Assert.hasText(signature, "'signature' must not be empty"); + Assert.notNull(clazz, "Class must not be null"); + + int firstParen = signature.indexOf("("); + int lastParen = signature.indexOf(")"); + + if (firstParen > -1 && lastParen == -1) { + throw new IllegalArgumentException("Invalid method signature '" + signature + + "': expected closing ')' for args list"); + } + else if (lastParen > -1 && firstParen == -1) { + throw new IllegalArgumentException("Invalid method signature '" + signature + + "': expected opening '(' for args list"); + } + else if (firstParen == -1 && lastParen == -1) { + return findMethodWithMinimalParameters(clazz, signature); + } + else { + String methodName = signature.substring(0, firstParen); + String[] parameterTypeNames = + StringUtils.commaDelimitedListToStringArray(signature.substring(firstParen + 1, lastParen)); + Class[] parameterTypes = new Class[parameterTypeNames.length]; + for (int i = 0; i < parameterTypeNames.length; i++) { + String parameterTypeName = parameterTypeNames[i].trim(); + try { + parameterTypes[i] = ClassUtils.forName(parameterTypeName, clazz.getClassLoader()); + } + catch (Throwable ex) { + throw new IllegalArgumentException("Invalid method signature: unable to resolve type [" + + parameterTypeName + "] for argument " + i + ". Root cause: " + ex); + } + } + return findMethod(clazz, methodName, parameterTypes); + } + } + + + /** + * Retrieve the JavaBeans PropertyDescriptors of a given class. + * @param clazz the Class to retrieve the PropertyDescriptors for + * @return an array of PropertyDescriptors for the given class + * @throws BeansException if PropertyDescriptor look fails + */ + public static PropertyDescriptor[] getPropertyDescriptors(Class clazz) throws BeansException { + CachedIntrospectionResults cr = CachedIntrospectionResults.forClass(clazz); + return cr.getBeanInfo().getPropertyDescriptors(); + } + + /** + * Retrieve the JavaBeans PropertyDescriptors for the given property. + * @param clazz the Class to retrieve the PropertyDescriptor for + * @param propertyName the name of the property + * @return the corresponding PropertyDescriptor, or null if none + * @throws BeansException if PropertyDescriptor lookup fails + */ + public static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) + throws BeansException { + + CachedIntrospectionResults cr = CachedIntrospectionResults.forClass(clazz); + return cr.getPropertyDescriptor(propertyName); + } + + /** + * Find a JavaBeans PropertyDescriptor for the given method, + * with the method either being the read method or the write method for + * that bean property. + * @param method the method to find a corresponding PropertyDescriptor for + * @return the corresponding PropertyDescriptor, or null if none + * @throws BeansException if PropertyDescriptor lookup fails + */ + public static PropertyDescriptor findPropertyForMethod(Method method) throws BeansException { + Assert.notNull(method, "Method must not be null"); + PropertyDescriptor[] pds = getPropertyDescriptors(method.getDeclaringClass()); + for (int i = 0; i < pds.length; i++) { + PropertyDescriptor pd = pds[i]; + if (method.equals(pd.getReadMethod()) || method.equals(pd.getWriteMethod())) { + return pd; + } + } + return null; + } + + /** + * Find a JavaBeans PropertyEditor following the 'Editor' suffix convention + * (e.g. "mypackage.MyDomainClass" -> "mypackage.MyDomainClassEditor"). + *

    Compatible to the standard JavaBeans convention as implemented by + * {@link java.beans.PropertyEditorManager} but isolated from the latter's + * registered default editors for primitive types. + * @param targetType the type to find an editor for + * @return the corresponding editor, or null if none found + */ + public static PropertyEditor findEditorByConvention(Class targetType) { + if (targetType == null || targetType.isArray() || unknownEditorTypes.containsKey(targetType)) { + return null; + } + ClassLoader cl = targetType.getClassLoader(); + if (cl == null) { + cl = ClassLoader.getSystemClassLoader(); + if (cl == null) { + return null; + } + } + String editorName = targetType.getName() + "Editor"; + try { + Class editorClass = cl.loadClass(editorName); + if (!PropertyEditor.class.isAssignableFrom(editorClass)) { + logger.warn("Editor class [" + editorName + + "] does not implement [java.beans.PropertyEditor] interface"); + unknownEditorTypes.put(targetType, Boolean.TRUE); + return null; + } + return (PropertyEditor) instantiateClass(editorClass); + } + catch (ClassNotFoundException ex) { + if (logger.isDebugEnabled()) { + logger.debug("No property editor [" + editorName + "] found for type " + + targetType.getName() + " according to 'Editor' suffix convention"); + } + unknownEditorTypes.put(targetType, Boolean.TRUE); + return null; + } + } + + /** + * Determine the bean property type for the given property from the + * given classes/interfaces, if possible. + * @param propertyName the name of the bean property + * @param beanClasses the classes to check against + * @return the property type, or Object.class as fallback + */ + public static Class findPropertyType(String propertyName, Class[] beanClasses) { + if (beanClasses != null) { + for (int i = 0; i < beanClasses.length; i++) { + PropertyDescriptor pd = getPropertyDescriptor(beanClasses[i], propertyName); + if (pd != null) { + return pd.getPropertyType(); + } + } + } + return Object.class; + } + + /** + * Obtain a new MethodParameter object for the write method of the + * specified property. + * @param pd the PropertyDescriptor for the property + * @return a corresponding MethodParameter object + */ + public static MethodParameter getWriteMethodParameter(PropertyDescriptor pd) { + if (pd instanceof GenericTypeAwarePropertyDescriptor) { + return new MethodParameter( + ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodParameter()); + } + else { + return new MethodParameter(pd.getWriteMethod(), 0); + } + } + + /** + * Check if the given type represents a "simple" property: + * a primitive, a String or other CharSequence, a Number, a Date, + * a URI, a URL, a Locale, a Class, or a corresponding array. + *

    Used to determine properties to check for a "simple" dependency-check. + * @param clazz the type to check + * @return whether the given type represents a "simple" property + * @see org.springframework.beans.factory.support.RootBeanDefinition#DEPENDENCY_CHECK_SIMPLE + * @see org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#checkDependencies + */ + public static boolean isSimpleProperty(Class clazz) { + Assert.notNull(clazz, "Class must not be null"); + return isSimpleValueType(clazz) || (clazz.isArray() && isSimpleValueType(clazz.getComponentType())); + } + + /** + * Check if the given type represents a "simple" value type: + * a primitive, a String or other CharSequence, a Number, a Date, + * a URI, a URL, a Locale or a Class. + * @param clazz the type to check + * @return whether the given type represents a "simple" value type + */ + public static boolean isSimpleValueType(Class clazz) { + return ClassUtils.isPrimitiveOrWrapper(clazz) || CharSequence.class.isAssignableFrom(clazz) || + Number.class.isAssignableFrom(clazz) || Date.class.isAssignableFrom(clazz) || + clazz.equals(URI.class) || clazz.equals(URL.class) || + clazz.equals(Locale.class) || clazz.equals(Class.class); + } + + /** + * Determine if the given target type is assignable from the given value + * type, assuming setting by reflection. Considers primitive wrapper + * classes as assignable to the corresponding primitive types. + * @param targetType the target type + * @param valueType the value type that should be assigned to the target type + * @return if the target type is assignable from the value type + * @deprecated as of Spring 2.0, in favor of ClassUtils.isAssignable + * @see org.springframework.util.ClassUtils#isAssignable(Class, Class) + */ + public static boolean isAssignable(Class targetType, Class valueType) { + return ClassUtils.isAssignable(targetType, valueType); + } + + /** + * Determine if the given type is assignable from the given value, + * assuming setting by reflection. Considers primitive wrapper classes + * as assignable to the corresponding primitive types. + * @param type the target type + * @param value the value that should be assigned to the type + * @return if the type is assignable from the value + * @deprecated as of Spring 2.0, in favor of ClassUtils.isAssignableValue + * @see org.springframework.util.ClassUtils#isAssignableValue(Class, Object) + */ + public static boolean isAssignable(Class type, Object value) { + return ClassUtils.isAssignableValue(type, value); + } + + + /** + * Copy the property values of the given source bean into the target bean. + *

    Note: The source and target classes do not have to match or even be derived + * from each other, as long as the properties match. Any bean properties that the + * source bean exposes but the target bean does not will silently be ignored. + *

    This is just a convenience method. For more complex transfer needs, + * consider using a full BeanWrapper. + * @param source the source bean + * @param target the target bean + * @throws BeansException if the copying failed + * @see BeanWrapper + */ + public static void copyProperties(Object source, Object target) throws BeansException { + copyProperties(source, target, null, null); + } + + /** + * Copy the property values of the given source bean into the given target bean, + * only setting properties defined in the given "editable" class (or interface). + *

    Note: The source and target classes do not have to match or even be derived + * from each other, as long as the properties match. Any bean properties that the + * source bean exposes but the target bean does not will silently be ignored. + *

    This is just a convenience method. For more complex transfer needs, + * consider using a full BeanWrapper. + * @param source the source bean + * @param target the target bean + * @param editable the class (or interface) to restrict property setting to + * @throws BeansException if the copying failed + * @see BeanWrapper + */ + public static void copyProperties(Object source, Object target, Class editable) + throws BeansException { + + copyProperties(source, target, editable, null); + } + + /** + * Copy the property values of the given source bean into the given target bean, + * ignoring the given "ignoreProperties". + *

    Note: The source and target classes do not have to match or even be derived + * from each other, as long as the properties match. Any bean properties that the + * source bean exposes but the target bean does not will silently be ignored. + *

    This is just a convenience method. For more complex transfer needs, + * consider using a full BeanWrapper. + * @param source the source bean + * @param target the target bean + * @param ignoreProperties array of property names to ignore + * @throws BeansException if the copying failed + * @see BeanWrapper + */ + public static void copyProperties(Object source, Object target, String[] ignoreProperties) + throws BeansException { + + copyProperties(source, target, null, ignoreProperties); + } + + /** + * Copy the property values of the given source bean into the given target bean. + *

    Note: The source and target classes do not have to match or even be derived + * from each other, as long as the properties match. Any bean properties that the + * source bean exposes but the target bean does not will silently be ignored. + * @param source the source bean + * @param target the target bean + * @param editable the class (or interface) to restrict property setting to + * @param ignoreProperties array of property names to ignore + * @throws BeansException if the copying failed + * @see BeanWrapper + */ + private static void copyProperties(Object source, Object target, Class editable, String[] ignoreProperties) + throws BeansException { + + Assert.notNull(source, "Source must not be null"); + Assert.notNull(target, "Target must not be null"); + + Class actualEditable = target.getClass(); + if (editable != null) { + if (!editable.isInstance(target)) { + throw new IllegalArgumentException("Target class [" + target.getClass().getName() + + "] not assignable to Editable class [" + editable.getName() + "]"); + } + actualEditable = editable; + } + PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); + List ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null; + + for (int i = 0; i < targetPds.length; i++) { + PropertyDescriptor targetPd = targetPds[i]; + if (targetPd.getWriteMethod() != null && + (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) { + PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); + if (sourcePd != null && sourcePd.getReadMethod() != null) { + try { + Method readMethod = sourcePd.getReadMethod(); + if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { + readMethod.setAccessible(true); + } + Object value = readMethod.invoke(source, new Object[0]); + Method writeMethod = targetPd.getWriteMethod(); + if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { + writeMethod.setAccessible(true); + } + writeMethod.invoke(target, new Object[] {value}); + } + catch (Throwable ex) { + throw new FatalBeanException("Could not copy properties from source to target", ex); + } + } + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/BeanWrapper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/BeanWrapper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/BeanWrapper.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,93 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyDescriptor; + +/** + * The central interface of Spring's low-level JavaBeans infrastructure. + * + *

    Typically not used directly but rather implicitly via a + * {@link org.springframework.beans.factory.BeanFactory} or a + * {@link org.springframework.validation.DataBinder}. + * + *

    Provides operations to analyze and manipulate standard JavaBeans: + * the ability to get and set property values (individually or in bulk), + * get property descriptors, and query the readability/writability of properties. + * + *

    This interface supports nested properties enabling the setting + * of properties on subproperties to an unlimited depth. + * A BeanWrapper instance can be used repeatedly, with its + * {@link #setWrappedInstance(Object) target object} (the wrapped JavaBean + * instance) changing as required. + * + *

    A BeanWrapper's default for the "extractOldValueForEditor" setting + * is "false", to avoid side effects caused by getter method invocations. + * Turn this to "true" to expose present property values to custom editors. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 13 April 2001 + * @see #setExtractOldValueForEditor + * @see PropertyAccessor + * @see PropertyEditorRegistry + * @see PropertyAccessorFactory#forBeanPropertyAccess + * @see org.springframework.beans.factory.BeanFactory + * @see org.springframework.validation.BeanPropertyBindingResult + * @see org.springframework.validation.DataBinder#initBeanPropertyAccess() + */ +public interface BeanWrapper extends ConfigurablePropertyAccessor { + + /** + * Change the wrapped JavaBean object. + * @param obj the bean instance to wrap + * @deprecated as of Spring 2.5, + * in favor of recreating a BeanWrapper per target instance + */ + void setWrappedInstance(Object obj); + + /** + * Return the bean instance wrapped by this object, if any. + * @return the bean instance, or null if none set + */ + Object getWrappedInstance(); + + /** + * Return the type of the wrapped JavaBean object. + * @return the type of the wrapped bean instance, + * or null if no wrapped object has been set + */ + Class getWrappedClass(); + + /** + * Obtain the PropertyDescriptors for the wrapped object + * (as determined by standard JavaBeans introspection). + * @return the PropertyDescriptors for the wrapped object + */ + PropertyDescriptor[] getPropertyDescriptors(); + + /** + * Obtain the property descriptor for a specific property + * of the wrapped object. + * @param propertyName the property to obtain the descriptor for + * (may be a nested path, but no indexed/mapped property) + * @return the property descriptor for the specified property + * @throws InvalidPropertyException if there is no such property + */ + PropertyDescriptor getPropertyDescriptor(String propertyName) throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/BeanWrapperImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/BeanWrapperImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/BeanWrapperImpl.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,891 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyChangeEvent; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.core.GenericCollectionTypeResolver; +import org.springframework.core.JdkVersion; +import org.springframework.core.MethodParameter; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +/** + * Default {@link BeanWrapper} implementation that should be sufficient + * for all typical use cases. Caches introspection results for efficiency. + * + *

    Note: Auto-registers default property editors from the + * org.springframework.beans.propertyeditors package, which apply + * in addition to the JDK's standard PropertyEditors. Applications can call + * the {@link #registerCustomEditor(Class, java.beans.PropertyEditor)} method + * to register an editor for a particular instance (i.e. they are not shared + * across the application). See the base class + * {@link PropertyEditorRegistrySupport} for details. + * + *

    BeanWrapperImpl will convert collection and array values + * to the corresponding target collections or arrays, if necessary. Custom + * property editors that deal with collections or arrays can either be + * written via PropertyEditor's setValue, or against a + * comma-delimited String via setAsText, as String arrays are + * converted in such a format if the array itself is not assignable. + * + *

    NOTE: As of Spring 2.5, this is - for almost all purposes - an + * internal class. It is just public in order to allow for access from + * other framework packages. For standard application access purposes, use the + * {@link PropertyAccessorFactory#forBeanPropertyAccess} factory method instead. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + * @since 15 April 2001 + * @see #registerCustomEditor + * @see #setPropertyValues + * @see #setPropertyValue + * @see #getPropertyValue + * @see #getPropertyType + * @see BeanWrapper + * @see PropertyEditorRegistrySupport + */ +public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWrapper { + + /** + * We'll create a lot of these objects, so we don't want a new logger every time. + */ + private static final Log logger = LogFactory.getLog(BeanWrapperImpl.class); + + + /** The wrapped object */ + private Object object; + + private String nestedPath = ""; + + private Object rootObject; + + private TypeConverterDelegate typeConverterDelegate; + + /** + * Cached introspections results for this object, to prevent encountering + * the cost of JavaBeans introspection every time. + */ + private CachedIntrospectionResults cachedIntrospectionResults; + + /** + * Map with cached nested BeanWrappers: nested path -> BeanWrapper instance. + */ + private Map nestedBeanWrappers; + + + /** + * Create new empty BeanWrapperImpl. Wrapped instance needs to be set afterwards. + * Registers default editors. + * @see #setWrappedInstance + */ + public BeanWrapperImpl() { + this(true); + } + + /** + * Create new empty BeanWrapperImpl. Wrapped instance needs to be set afterwards. + * @param registerDefaultEditors whether to register default editors + * (can be suppressed if the BeanWrapper won't need any type conversion) + * @see #setWrappedInstance + */ + public BeanWrapperImpl(boolean registerDefaultEditors) { + if (registerDefaultEditors) { + registerDefaultEditors(); + } + this.typeConverterDelegate = new TypeConverterDelegate(this); + } + + /** + * Create new BeanWrapperImpl for the given object. + * @param object object wrapped by this BeanWrapper + */ + public BeanWrapperImpl(Object object) { + registerDefaultEditors(); + setWrappedInstance(object); + } + + /** + * Create new BeanWrapperImpl, wrapping a new instance of the specified class. + * @param clazz class to instantiate and wrap + */ + public BeanWrapperImpl(Class clazz) { + registerDefaultEditors(); + setWrappedInstance(BeanUtils.instantiateClass(clazz)); + } + + /** + * Create new BeanWrapperImpl for the given object, + * registering a nested path that the object is in. + * @param object object wrapped by this BeanWrapper + * @param nestedPath the nested path of the object + * @param rootObject the root object at the top of the path + */ + public BeanWrapperImpl(Object object, String nestedPath, Object rootObject) { + registerDefaultEditors(); + setWrappedInstance(object, nestedPath, rootObject); + } + + /** + * Create new BeanWrapperImpl for the given object, + * registering a nested path that the object is in. + * @param object object wrapped by this BeanWrapper + * @param nestedPath the nested path of the object + * @param superBw the containing BeanWrapper (must not be null) + */ + private BeanWrapperImpl(Object object, String nestedPath, BeanWrapperImpl superBw) { + setWrappedInstance(object, nestedPath, superBw.getWrappedInstance()); + setExtractOldValueForEditor(superBw.isExtractOldValueForEditor()); + } + + + //--------------------------------------------------------------------- + // Implementation of BeanWrapper interface + //--------------------------------------------------------------------- + + /** + * Switch the target object, replacing the cached introspection results only + * if the class of the new object is different to that of the replaced object. + * @param object the new target object + */ + public void setWrappedInstance(Object object) { + setWrappedInstance(object, "", null); + } + + /** + * Switch the target object, replacing the cached introspection results only + * if the class of the new object is different to that of the replaced object. + * @param object the new target object + * @param nestedPath the nested path of the object + * @param rootObject the root object at the top of the path + */ + public void setWrappedInstance(Object object, String nestedPath, Object rootObject) { + Assert.notNull(object, "Bean object must not be null"); + this.object = object; + this.nestedPath = (nestedPath != null ? nestedPath : ""); + this.rootObject = (!"".equals(this.nestedPath) ? rootObject : object); + this.nestedBeanWrappers = null; + this.typeConverterDelegate = new TypeConverterDelegate(this, object); + setIntrospectionClass(object.getClass()); + } + + public final Object getWrappedInstance() { + return this.object; + } + + public final Class getWrappedClass() { + return (this.object != null ? this.object.getClass() : null); + } + + /** + * Return the nested path of the object wrapped by this BeanWrapper. + */ + public final String getNestedPath() { + return this.nestedPath; + } + + /** + * Return the root object at the top of the path of this BeanWrapper. + * @see #getNestedPath + */ + public final Object getRootInstance() { + return this.rootObject; + } + + /** + * Return the class of the root object at the top of the path of this BeanWrapper. + * @see #getNestedPath + */ + public final Class getRootClass() { + return (this.rootObject != null ? this.rootObject.getClass() : null); + } + + /** + * Set the class to introspect. + * Needs to be called when the target object changes. + * @param clazz the class to introspect + */ + protected void setIntrospectionClass(Class clazz) { + if (this.cachedIntrospectionResults != null && + !clazz.equals(this.cachedIntrospectionResults.getBeanClass())) { + this.cachedIntrospectionResults = null; + } + } + + /** + * Obtain a lazily initializted CachedIntrospectionResults instance + * for the wrapped object. + */ + private CachedIntrospectionResults getCachedIntrospectionResults() { + Assert.state(this.object != null, "BeanWrapper does not hold a bean instance"); + if (this.cachedIntrospectionResults == null) { + this.cachedIntrospectionResults = CachedIntrospectionResults.forClass(getWrappedClass()); + } + return this.cachedIntrospectionResults; + } + + + public PropertyDescriptor[] getPropertyDescriptors() { + return getCachedIntrospectionResults().getBeanInfo().getPropertyDescriptors(); + } + + public PropertyDescriptor getPropertyDescriptor(String propertyName) throws BeansException { + PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); + if (pd == null) { + throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, + "No property '" + propertyName + "' found"); + } + return pd; + } + + /** + * Internal version of {@link #getPropertyDescriptor}: + * Returns null if not found rather than throwing an exception. + * @param propertyName the property to obtain the descriptor for + * @return the property descriptor for the specified property, + * or null if not found + * @throws BeansException in case of introspection failure + */ + protected PropertyDescriptor getPropertyDescriptorInternal(String propertyName) throws BeansException { + Assert.notNull(propertyName, "Property name must not be null"); + BeanWrapperImpl nestedBw = getBeanWrapperForPropertyPath(propertyName); + return nestedBw.getCachedIntrospectionResults().getPropertyDescriptor(getFinalPath(nestedBw, propertyName)); + } + + public Class getPropertyType(String propertyName) throws BeansException { + try { + PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); + if (pd != null) { + return pd.getPropertyType(); + } + else { + // Maybe an indexed/mapped property... + Object value = getPropertyValue(propertyName); + if (value != null) { + return value.getClass(); + } + // Check to see if there is a custom editor, + // which might give an indication on the desired target type. + Class editorType = guessPropertyTypeFromEditors(propertyName); + if (editorType != null) { + return editorType; + } + } + } + catch (InvalidPropertyException ex) { + // Consider as not determinable. + } + return null; + } + + public boolean isReadableProperty(String propertyName) { + try { + PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); + if (pd != null) { + if (pd.getReadMethod() != null) { + return true; + } + } + else { + // Maybe an indexed/mapped property... + getPropertyValue(propertyName); + return true; + } + } + catch (InvalidPropertyException ex) { + // Cannot be evaluated, so can't be readable. + } + return false; + } + + public boolean isWritableProperty(String propertyName) { + try { + PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); + if (pd != null) { + if (pd.getWriteMethod() != null) { + return true; + } + } + else { + // Maybe an indexed/mapped property... + getPropertyValue(propertyName); + return true; + } + } + catch (InvalidPropertyException ex) { + // Cannot be evaluated, so can't be writable. + } + return false; + } + + /** + * @deprecated in favor of convertIfNecessary + * @see #convertIfNecessary(Object, Class) + */ + public Object doTypeConversionIfNecessary(Object value, Class requiredType) throws TypeMismatchException { + return convertIfNecessary(value, requiredType, null); + } + + public Object convertIfNecessary( + Object value, Class requiredType, MethodParameter methodParam) throws TypeMismatchException { + try { + return this.typeConverterDelegate.convertIfNecessary(value, requiredType, methodParam); + } + catch (IllegalArgumentException ex) { + throw new TypeMismatchException(value, requiredType, ex); + } + } + + /** + * Convert the given value for the specified property to the latter's type. + *

    This method is only intended for optimizations in a BeanFactory. + * Use the convertIfNecessary methods for programmatic conversion. + * @param value the value to convert + * @param propertyName the target property + * (note that nested or indexed properties are not supported here) + * @return the new value, possibly the result of type conversion + * @throws TypeMismatchException if type conversion failed + */ + public Object convertForProperty(Object value, String propertyName) throws TypeMismatchException { + PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(propertyName); + if (pd == null) { + throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, + "No property '" + propertyName + "' found"); + } + try { + return this.typeConverterDelegate.convertIfNecessary(null, value, pd); + } + catch (IllegalArgumentException ex) { + PropertyChangeEvent pce = + new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, null, value); + throw new TypeMismatchException(pce, pd.getPropertyType(), ex); + } + } + + + //--------------------------------------------------------------------- + // Implementation methods + //--------------------------------------------------------------------- + + /** + * Get the last component of the path. Also works if not nested. + * @param bw BeanWrapper to work on + * @param nestedPath property path we know is nested + * @return last component of the path (the property on the target bean) + */ + private String getFinalPath(BeanWrapper bw, String nestedPath) { + if (bw == this) { + return nestedPath; + } + return nestedPath.substring(PropertyAccessorUtils.getLastNestedPropertySeparatorIndex(nestedPath) + 1); + } + + /** + * Recursively navigate to return a BeanWrapper for the nested property path. + * @param propertyPath property property path, which may be nested + * @return a BeanWrapper for the target bean + */ + protected BeanWrapperImpl getBeanWrapperForPropertyPath(String propertyPath) { + int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath); + // Handle nested properties recursively. + if (pos > -1) { + String nestedProperty = propertyPath.substring(0, pos); + String nestedPath = propertyPath.substring(pos + 1); + BeanWrapperImpl nestedBw = getNestedBeanWrapper(nestedProperty); + return nestedBw.getBeanWrapperForPropertyPath(nestedPath); + } + else { + return this; + } + } + + /** + * Retrieve a BeanWrapper for the given nested property. + * Create a new one if not found in the cache. + *

    Note: Caching nested BeanWrappers is necessary now, + * to keep registered custom editors for nested properties. + * @param nestedProperty property to create the BeanWrapper for + * @return the BeanWrapper instance, either cached or newly created + */ + private BeanWrapperImpl getNestedBeanWrapper(String nestedProperty) { + if (this.nestedBeanWrappers == null) { + this.nestedBeanWrappers = new HashMap(); + } + // Get value of bean property. + PropertyTokenHolder tokens = getPropertyNameTokens(nestedProperty); + String canonicalName = tokens.canonicalName; + Object propertyValue = getPropertyValue(tokens); + if (propertyValue == null) { + throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + canonicalName); + } + + // Lookup cached sub-BeanWrapper, create new one if not found. + BeanWrapperImpl nestedBw = (BeanWrapperImpl) this.nestedBeanWrappers.get(canonicalName); + if (nestedBw == null || nestedBw.getWrappedInstance() != propertyValue) { + if (logger.isTraceEnabled()) { + logger.trace("Creating new nested BeanWrapper for property '" + canonicalName + "'"); + } + nestedBw = newNestedBeanWrapper(propertyValue, this.nestedPath + canonicalName + NESTED_PROPERTY_SEPARATOR); + // Inherit all type-specific PropertyEditors. + copyDefaultEditorsTo(nestedBw); + copyCustomEditorsTo(nestedBw, canonicalName); + this.nestedBeanWrappers.put(canonicalName, nestedBw); + } + else { + if (logger.isTraceEnabled()) { + logger.trace("Using cached nested BeanWrapper for property '" + canonicalName + "'"); + } + } + return nestedBw; + } + + /** + * Create a new nested BeanWrapper instance. + *

    Default implementation creates a BeanWrapperImpl instance. + * Can be overridden in subclasses to create a BeanWrapperImpl subclass. + * @param object object wrapped by this BeanWrapper + * @param nestedPath the nested path of the object + * @return the nested BeanWrapper instance + */ + protected BeanWrapperImpl newNestedBeanWrapper(Object object, String nestedPath) { + return new BeanWrapperImpl(object, nestedPath, this); + } + + /** + * Parse the given property name into the corresponding property name tokens. + * @param propertyName the property name to parse + * @return representation of the parsed property tokens + */ + private PropertyTokenHolder getPropertyNameTokens(String propertyName) { + PropertyTokenHolder tokens = new PropertyTokenHolder(); + String actualName = null; + List keys = new ArrayList(2); + int searchIndex = 0; + while (searchIndex != -1) { + int keyStart = propertyName.indexOf(PROPERTY_KEY_PREFIX, searchIndex); + searchIndex = -1; + if (keyStart != -1) { + int keyEnd = propertyName.indexOf(PROPERTY_KEY_SUFFIX, keyStart + PROPERTY_KEY_PREFIX.length()); + if (keyEnd != -1) { + if (actualName == null) { + actualName = propertyName.substring(0, keyStart); + } + String key = propertyName.substring(keyStart + PROPERTY_KEY_PREFIX.length(), keyEnd); + if ((key.startsWith("'") && key.endsWith("'")) || (key.startsWith("\"") && key.endsWith("\""))) { + key = key.substring(1, key.length() - 1); + } + keys.add(key); + searchIndex = keyEnd + PROPERTY_KEY_SUFFIX.length(); + } + } + } + tokens.actualName = (actualName != null ? actualName : propertyName); + tokens.canonicalName = tokens.actualName; + if (!keys.isEmpty()) { + tokens.canonicalName += + PROPERTY_KEY_PREFIX + + StringUtils.collectionToDelimitedString(keys, PROPERTY_KEY_SUFFIX + PROPERTY_KEY_PREFIX) + + PROPERTY_KEY_SUFFIX; + tokens.keys = StringUtils.toStringArray(keys); + } + return tokens; + } + + + //--------------------------------------------------------------------- + // Implementation of PropertyAccessor interface + //--------------------------------------------------------------------- + + public Object getPropertyValue(String propertyName) throws BeansException { + BeanWrapperImpl nestedBw = getBeanWrapperForPropertyPath(propertyName); + PropertyTokenHolder tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName)); + return nestedBw.getPropertyValue(tokens); + } + + private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException { + String propertyName = tokens.canonicalName; + String actualName = tokens.actualName; + PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); + if (pd == null || pd.getReadMethod() == null) { + throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName); + } + Method readMethod = pd.getReadMethod(); + try { + if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { + readMethod.setAccessible(true); + } + Object value = readMethod.invoke(this.object, (Object[]) null); + if (tokens.keys != null) { + // apply indexes and map keys + for (int i = 0; i < tokens.keys.length; i++) { + String key = tokens.keys[i]; + if (value == null) { + throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, + "Cannot access indexed value of property referenced in indexed " + + "property path '" + propertyName + "': returned null"); + } + else if (value.getClass().isArray()) { + value = Array.get(value, Integer.parseInt(key)); + } + else if (value instanceof List) { + List list = (List) value; + value = list.get(Integer.parseInt(key)); + } + else if (value instanceof Set) { + // Apply index to Iterator in case of a Set. + Set set = (Set) value; + int index = Integer.parseInt(key); + if (index < 0 || index >= set.size()) { + throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, + "Cannot get element with index " + index + " from Set of size " + + set.size() + ", accessed using property path '" + propertyName + "'"); + } + Iterator it = set.iterator(); + for (int j = 0; it.hasNext(); j++) { + Object elem = it.next(); + if (j == index) { + value = elem; + break; + } + } + } + else if (value instanceof Map) { + Map map = (Map) value; + Class mapKeyType = null; + if (JdkVersion.isAtLeastJava15()) { + mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), i + 1); + } + // IMPORTANT: Do not pass full property name in here - property editors + // must not kick in for map keys but rather only for map values. + Object convertedMapKey = this.typeConverterDelegate.convertIfNecessary(key, mapKeyType); + // Pass full property name and old value in here, since we want full + // conversion ability for map values. + value = map.get(convertedMapKey); + } + else { + throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, + "Property referenced in indexed property path '" + propertyName + + "' is neither an array nor a List nor a Set nor a Map; returned value was [" + value + "]"); + } + } + } + return value; + } + catch (InvocationTargetException ex) { + throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, + "Getter for property '" + actualName + "' threw exception", ex); + } + catch (IllegalAccessException ex) { + throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, + "Illegal attempt to get property '" + actualName + "' threw exception", ex); + } + catch (IndexOutOfBoundsException ex) { + throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, + "Index of out of bounds in property path '" + propertyName + "'", ex); + } + catch (NumberFormatException ex) { + throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, + "Invalid index in property path '" + propertyName + "'", ex); + } + } + + public void setPropertyValue(String propertyName, Object value) throws BeansException { + BeanWrapperImpl nestedBw = null; + try { + nestedBw = getBeanWrapperForPropertyPath(propertyName); + } + catch (NotReadablePropertyException ex) { + throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, + "Nested property in path '" + propertyName + "' does not exist", ex); + } + PropertyTokenHolder tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName)); + nestedBw.setPropertyValue(tokens, new PropertyValue(propertyName, value)); + } + + public void setPropertyValue(PropertyValue pv) throws BeansException { + PropertyTokenHolder tokens = (PropertyTokenHolder) pv.resolvedTokens; + if (tokens == null) { + String propertyName = pv.getName(); + BeanWrapperImpl nestedBw = null; + try { + nestedBw = getBeanWrapperForPropertyPath(propertyName); + } + catch (NotReadablePropertyException ex) { + throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, + "Nested property in path '" + propertyName + "' does not exist", ex); + } + tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName)); + if (nestedBw == this) { + pv.getOriginalPropertyValue().resolvedTokens = tokens; + } + nestedBw.setPropertyValue(tokens, pv); + } + else { + setPropertyValue(tokens, pv); + } + } + + private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException { + String propertyName = tokens.canonicalName; + String actualName = tokens.actualName; + + if (tokens.keys != null) { + // Apply indexes and map keys: fetch value for all keys but the last one. + PropertyTokenHolder getterTokens = new PropertyTokenHolder(); + getterTokens.canonicalName = tokens.canonicalName; + getterTokens.actualName = tokens.actualName; + getterTokens.keys = new String[tokens.keys.length - 1]; + System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1); + Object propValue = null; + try { + propValue = getPropertyValue(getterTokens); + } + catch (NotReadablePropertyException ex) { + throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, + "Cannot access indexed value in property referenced " + + "in indexed property path '" + propertyName + "'", ex); + } + // Set value for last key. + String key = tokens.keys[tokens.keys.length - 1]; + if (propValue == null) { + throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, + "Cannot access indexed value in property referenced " + + "in indexed property path '" + propertyName + "': returned null"); + } + else if (propValue.getClass().isArray()) { + Class requiredType = propValue.getClass().getComponentType(); + int arrayIndex = Integer.parseInt(key); + Object oldValue = null; + try { + if (isExtractOldValueForEditor()) { + oldValue = Array.get(propValue, arrayIndex); + } + Object convertedValue = this.typeConverterDelegate.convertIfNecessary( + propertyName, oldValue, pv.getValue(), requiredType); + Array.set(propValue, Integer.parseInt(key), convertedValue); + } + catch (IllegalArgumentException ex) { + PropertyChangeEvent pce = + new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); + throw new TypeMismatchException(pce, requiredType, ex); + } + catch (IndexOutOfBoundsException ex) { + throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, + "Invalid array index in property path '" + propertyName + "'", ex); + } + } + else if (propValue instanceof List) { + PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); + Class requiredType = null; + if (JdkVersion.isAtLeastJava15()) { + requiredType = GenericCollectionTypeResolver.getCollectionReturnType( + pd.getReadMethod(), tokens.keys.length); + } + List list = (List) propValue; + int index = Integer.parseInt(key); + Object oldValue = null; + if (isExtractOldValueForEditor() && index < list.size()) { + oldValue = list.get(index); + } + try { + Object convertedValue = this.typeConverterDelegate.convertIfNecessary( + propertyName, oldValue, pv.getValue(), requiredType); + if (index < list.size()) { + list.set(index, convertedValue); + } + else if (index >= list.size()) { + for (int i = list.size(); i < index; i++) { + try { + list.add(null); + } + catch (NullPointerException ex) { + throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, + "Cannot set element with index " + index + " in List of size " + + list.size() + ", accessed using property path '" + propertyName + + "': List does not support filling up gaps with null elements"); + } + } + list.add(convertedValue); + } + } + catch (IllegalArgumentException ex) { + PropertyChangeEvent pce = + new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); + throw new TypeMismatchException(pce, requiredType, ex); + } + } + else if (propValue instanceof Map) { + PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); + Class mapKeyType = null; + Class mapValueType = null; + if (JdkVersion.isAtLeastJava15()) { + mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType( + pd.getReadMethod(), tokens.keys.length); + mapValueType = GenericCollectionTypeResolver.getMapValueReturnType( + pd.getReadMethod(), tokens.keys.length); + } + Map map = (Map) propValue; + Object convertedMapKey = null; + Object convertedMapValue = null; + try { + // IMPORTANT: Do not pass full property name in here - property editors + // must not kick in for map keys but rather only for map values. + convertedMapKey = this.typeConverterDelegate.convertIfNecessary(key, mapKeyType); + } + catch (IllegalArgumentException ex) { + PropertyChangeEvent pce = + new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, null, pv.getValue()); + throw new TypeMismatchException(pce, mapKeyType, ex); + } + Object oldValue = null; + if (isExtractOldValueForEditor()) { + oldValue = map.get(convertedMapKey); + } + try { + // Pass full property name and old value in here, since we want full + // conversion ability for map values. + convertedMapValue = this.typeConverterDelegate.convertIfNecessary( + propertyName, oldValue, pv.getValue(), mapValueType, null, + new MethodParameter(pd.getReadMethod(), -1, tokens.keys.length + 1)); + } + catch (IllegalArgumentException ex) { + PropertyChangeEvent pce = + new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); + throw new TypeMismatchException(pce, mapValueType, ex); + } + map.put(convertedMapKey, convertedMapValue); + } + else { + throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, + "Property referenced in indexed property path '" + propertyName + + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]"); + } + } + + else { + PropertyDescriptor pd = pv.resolvedDescriptor; + if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) { + pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); + if (pd == null || pd.getWriteMethod() == null) { + PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass()); + throw new NotWritablePropertyException( + getRootClass(), this.nestedPath + propertyName, + matches.buildErrorMessage(), matches.getPossibleMatches()); + } + pv.getOriginalPropertyValue().resolvedDescriptor = pd; + } + + Object oldValue = null; + try { + Object originalValue = pv.getValue(); + Object valueToApply = originalValue; + if (!Boolean.FALSE.equals(pv.conversionNecessary)) { + if (pv.isConverted()) { + valueToApply = pv.getConvertedValue(); + } + else { + if (isExtractOldValueForEditor() && pd.getReadMethod() != null) { + Method readMethod = pd.getReadMethod(); + if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { + readMethod.setAccessible(true); + } + try { + oldValue = readMethod.invoke(this.object, new Object[0]); + } + catch (Exception ex) { + if (logger.isDebugEnabled()) { + logger.debug("Could not read previous value of property '" + + this.nestedPath + propertyName + "'", ex); + } + } + } + valueToApply = this.typeConverterDelegate.convertIfNecessary(oldValue, originalValue, pd); + } + pv.getOriginalPropertyValue().conversionNecessary = Boolean.valueOf(valueToApply != originalValue); + } + Method writeMethod = pd.getWriteMethod(); + if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { + writeMethod.setAccessible(true); + } + writeMethod.invoke(this.object, new Object[] {valueToApply}); + } + catch (InvocationTargetException ex) { + PropertyChangeEvent propertyChangeEvent = + new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); + if (ex.getTargetException() instanceof ClassCastException) { + throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException()); + } + else { + throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException()); + } + } + catch (IllegalArgumentException ex) { + PropertyChangeEvent pce = + new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); + throw new TypeMismatchException(pce, pd.getPropertyType(), ex); + } + catch (IllegalAccessException ex) { + PropertyChangeEvent pce = + new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); + throw new MethodInvocationException(pce, ex); + } + } + } + + + public String toString() { + StringBuffer sb = new StringBuffer(getClass().getName()); + if (this.object != null) { + sb.append(": wrapping object [").append(ObjectUtils.identityToString(this.object)).append("]"); + } + else { + sb.append(": no wrapped object set"); + } + return sb.toString(); + } + + + //--------------------------------------------------------------------- + // Inner class for internal use + //--------------------------------------------------------------------- + + private static class PropertyTokenHolder { + + public String canonicalName; + + public String actualName; + + public String[] keys; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/BeansException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/BeansException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/BeansException.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import org.springframework.core.NestedRuntimeException; +import org.springframework.util.ObjectUtils; + +/** + * Abstract superclass for all exceptions thrown in the beans package + * and subpackages. + * + *

    Note that this is a runtime (unchecked) exception. Beans exceptions + * are usually fatal; there is no reason for them to be checked. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public abstract class BeansException extends NestedRuntimeException { + + /** + * Create a new BeansException with the specified message. + * @param msg the detail message + */ + public BeansException(String msg) { + super(msg); + } + + /** + * Create a new BeansException with the specified message + * and root cause. + * @param msg the detail message + * @param cause the root cause + */ + public BeansException(String msg, Throwable cause) { + super(msg, cause); + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof BeansException)) { + return false; + } + BeansException otherBe = (BeansException) other; + return (getMessage().equals(otherBe.getMessage()) && + ObjectUtils.nullSafeEquals(getCause(), otherBe.getCause())); + } + + public int hashCode() { + return getMessage().hashCode(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/CachedIntrospectionResults.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/CachedIntrospectionResults.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/CachedIntrospectionResults.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,273 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; +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.WeakHashMap; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.core.JdkVersion; +import org.springframework.util.ClassUtils; + +/** + * Internal class that caches JavaBeans {@link java.beans.PropertyDescriptor} + * information for a Java class. Not intended for direct use by application code. + * + *

    Necessary for own caching of descriptors within the application's + * ClassLoader, rather than rely on the JDK's system-wide BeanInfo cache + * (in order to avoid leaks on ClassLoader shutdown). + * + *

    Information is cached statically, so we don't need to create new + * objects of this class for every JavaBean we manipulate. Hence, this class + * implements the factory design pattern, using a private constructor and + * a static {@link #forClass(Class)} factory method to obtain instances. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 05 May 2001 + * @see #acceptClassLoader(ClassLoader) + * @see #clearClassLoader(ClassLoader) + * @see #forClass(Class) + */ +public class CachedIntrospectionResults { + + private static final Log logger = LogFactory.getLog(CachedIntrospectionResults.class); + + /** + * Set of ClassLoaders that this CachedIntrospectionResults class will always + * accept classes from, even if the classes do not qualify as cache-safe. + */ + static final Set acceptedClassLoaders = Collections.synchronizedSet(new HashSet()); + + /** + * Map keyed by class containing CachedIntrospectionResults. + * Needs to be a WeakHashMap with WeakReferences as values to allow + * for proper garbage collection in case of multiple class loaders. + */ + static final Map classCache = Collections.synchronizedMap(new WeakHashMap()); + + + /** + * Accept the given ClassLoader as cache-safe, even if its classes would + * not qualify as cache-safe in this CachedIntrospectionResults class. + *

    This configuration method is only relevant in scenarios where the Spring + * classes reside in a 'common' ClassLoader (e.g. the system ClassLoader) + * whose lifecycle is not coupled to the application. In such a scenario, + * CachedIntrospectionResults would by default not cache any of the application's + * classes, since they would create a leak in the common ClassLoader. + *

    Any acceptClassLoader call at application startup should + * be paired with a {@link #clearClassLoader} call at application shutdown. + * @param classLoader the ClassLoader to accept + */ + public static void acceptClassLoader(ClassLoader classLoader) { + if (classLoader != null) { + acceptedClassLoaders.add(classLoader); + } + } + + /** + * Clear the introspection cache for the given ClassLoader, removing the + * introspection results for all classes underneath that ClassLoader, + * and deregistering the ClassLoader (and any of its children) from the + * acceptance list. + * @param classLoader the ClassLoader to clear the cache for + */ + public static void clearClassLoader(ClassLoader classLoader) { + if (classLoader == null) { + return; + } + synchronized (classCache) { + for (Iterator it = classCache.keySet().iterator(); it.hasNext();) { + Class beanClass = (Class) it.next(); + if (isUnderneathClassLoader(beanClass.getClassLoader(), classLoader)) { + it.remove(); + } + } + } + synchronized (acceptedClassLoaders) { + for (Iterator it = acceptedClassLoaders.iterator(); it.hasNext();) { + ClassLoader registeredLoader = (ClassLoader) it.next(); + if (isUnderneathClassLoader(registeredLoader, classLoader)) { + it.remove(); + } + } + } + } + + /** + * Create CachedIntrospectionResults for the given bean class. + *

    We don't want to use synchronization here. Object references are atomic, + * so we can live with doing the occasional unnecessary lookup at startup only. + * @param beanClass the bean class to analyze + * @return the corresponding CachedIntrospectionResults + * @throws BeansException in case of introspection failure + */ + static CachedIntrospectionResults forClass(Class beanClass) throws BeansException { + CachedIntrospectionResults results = null; + Object value = classCache.get(beanClass); + if (value instanceof Reference) { + Reference ref = (Reference) value; + results = (CachedIntrospectionResults) ref.get(); + } + else { + results = (CachedIntrospectionResults) value; + } + if (results == null) { + // can throw BeansException + results = new CachedIntrospectionResults(beanClass); + if (ClassUtils.isCacheSafe(beanClass, CachedIntrospectionResults.class.getClassLoader()) || + isClassLoaderAccepted(beanClass.getClassLoader())) { + classCache.put(beanClass, results); + } + else { + if (logger.isDebugEnabled()) { + logger.debug("Not strongly caching class [" + beanClass.getName() + "] because it is not cache-safe"); + } + classCache.put(beanClass, new WeakReference(results)); + } + } + return results; + } + + /** + * Check whether this CachedIntrospectionResults class is configured + * to accept the given ClassLoader. + * @param classLoader the ClassLoader to check + * @return whether the given ClassLoader is accepted + * @see #acceptClassLoader + */ + private static boolean isClassLoaderAccepted(ClassLoader classLoader) { + // Iterate over array copy in order to avoid synchronization for the entire + // ClassLoader check (avoiding a synchronized acceptedClassLoaders Iterator). + Object[] acceptedLoaderArray = acceptedClassLoaders.toArray(); + for (int i = 0; i < acceptedLoaderArray.length; i++) { + ClassLoader registeredLoader = (ClassLoader) acceptedLoaderArray[i]; + if (isUnderneathClassLoader(classLoader, registeredLoader)) { + return true; + } + } + return false; + } + + /** + * Check whether the given ClassLoader is underneath the given parent, + * that is, whether the parent is within the candidate's hierarchy. + * @param candidate the candidate ClassLoader to check + * @param parent the parent ClassLoader to check for + */ + private static boolean isUnderneathClassLoader(ClassLoader candidate, ClassLoader parent) { + if (candidate == null) { + return false; + } + if (candidate == parent) { + return true; + } + ClassLoader classLoaderToCheck = candidate; + while (classLoaderToCheck != null) { + classLoaderToCheck = classLoaderToCheck.getParent(); + if (classLoaderToCheck == parent) { + return true; + } + } + return false; + } + + + /** The BeanInfo object for the introspected bean class */ + private final BeanInfo beanInfo; + + /** PropertyDescriptor objects keyed by property name String */ + private final Map propertyDescriptorCache; + + + /** + * Create a new CachedIntrospectionResults instance for the given class. + * @param beanClass the bean class to analyze + * @throws BeansException in case of introspection failure + */ + private CachedIntrospectionResults(Class beanClass) throws BeansException { + try { + if (logger.isTraceEnabled()) { + logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]"); + } + this.beanInfo = Introspector.getBeanInfo(beanClass); + + // Immediately remove class from Introspector cache, to allow for proper + // garbage collection on class loader shutdown - we cache it here anyway, + // in a GC-friendly manner. In contrast to CachedIntrospectionResults, + // Introspector does not use WeakReferences as values of its WeakHashMap! + Class classToFlush = beanClass; + do { + Introspector.flushFromCaches(classToFlush); + classToFlush = classToFlush.getSuperclass(); + } + while (classToFlush != null); + + if (logger.isTraceEnabled()) { + logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]"); + } + this.propertyDescriptorCache = new HashMap(); + + // This call is slow so we do it once. + PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors(); + for (int i = 0; i < pds.length; i++) { + PropertyDescriptor pd = pds[i]; + if (logger.isTraceEnabled()) { + logger.trace("Found bean property '" + pd.getName() + "'" + + (pd.getPropertyType() != null ? + " of type [" + pd.getPropertyType().getName() + "]" : "") + + (pd.getPropertyEditorClass() != null ? + "; editor [" + pd.getPropertyEditorClass().getName() + "]" : "")); + } + if (JdkVersion.isAtLeastJava15()) { + pd = new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), + pd.getReadMethod(), pd.getWriteMethod(), pd.getPropertyEditorClass()); + } + this.propertyDescriptorCache.put(pd.getName(), pd); + } + } + catch (IntrospectionException ex) { + throw new FatalBeanException("Cannot get BeanInfo for object of class [" + beanClass.getName() + "]", ex); + } + } + + BeanInfo getBeanInfo() { + return this.beanInfo; + } + + Class getBeanClass() { + return this.beanInfo.getBeanDescriptor().getBeanClass(); + } + + PropertyDescriptor getPropertyDescriptor(String propertyName) { + return (PropertyDescriptor) this.propertyDescriptorCache.get(propertyName); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/ConfigurablePropertyAccessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/ConfigurablePropertyAccessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/ConfigurablePropertyAccessor.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Interface that encapsulates configuration methods for a PropertyAccessor. + * Also extends the PropertyEditorRegistry interface, which defines methods + * for PropertyEditor management. + * + *

    Serves as base interface for {@link BeanWrapper}. + * + * @author Juergen Hoeller + * @since 2.0 + * @see BeanWrapper + */ +public interface ConfigurablePropertyAccessor extends PropertyAccessor, PropertyEditorRegistry, TypeConverter { + + /** + * Set whether to extract the old property value when applying a + * property editor to a new value for a property. + */ + void setExtractOldValueForEditor(boolean extractOldValueForEditor); + + /** + * Return whether to extract the old property value when applying a + * property editor to a new value for a property. + */ + boolean isExtractOldValueForEditor(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/DirectFieldAccessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/DirectFieldAccessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/DirectFieldAccessor.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,136 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyChangeEvent; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + +import org.springframework.core.MethodParameter; +import org.springframework.util.Assert; +import org.springframework.util.ReflectionUtils; + +/** + * {@link PropertyAccessor} implementation that directly accesses instance fields. + * Allows for direct binding to fields instead of going through JavaBean setters. + * + *

    This implementation just supports fields in the actual target object. + * It is not able to traverse nested fields. + * + *

    A DirectFieldAccessor's default for the "extractOldValueForEditor" setting + * is "true", since a field can always be read without side effects. + * + * @author Juergen Hoeller + * @since 2.0 + * @see #setExtractOldValueForEditor + * @see BeanWrapper + * @see org.springframework.validation.DirectFieldBindingResult + * @see org.springframework.validation.DataBinder#initDirectFieldAccess() + */ +public class DirectFieldAccessor extends AbstractPropertyAccessor { + + private final Object target; + + private final Map fieldMap = new HashMap(); + + private final TypeConverterDelegate typeConverterDelegate; + + + /** + * Create a new DirectFieldAccessor for the given target object. + * @param target the target object to access + */ + public DirectFieldAccessor(Object target) { + Assert.notNull(target, "Target object must not be null"); + this.target = target; + ReflectionUtils.doWithFields(this.target.getClass(), new ReflectionUtils.FieldCallback() { + public void doWith(Field field) { + fieldMap.put(field.getName(), field); + } + }); + this.typeConverterDelegate = new TypeConverterDelegate(this, target); + registerDefaultEditors(); + setExtractOldValueForEditor(true); + } + + + public boolean isReadableProperty(String propertyName) throws BeansException { + return this.fieldMap.containsKey(propertyName); + } + + public boolean isWritableProperty(String propertyName) throws BeansException { + return this.fieldMap.containsKey(propertyName); + } + + public Class getPropertyType(String propertyName) throws BeansException { + Field field = (Field) this.fieldMap.get(propertyName); + if (field != null) { + return field.getType(); + } + return null; + } + + public Object getPropertyValue(String propertyName) throws BeansException { + Field field = (Field) this.fieldMap.get(propertyName); + if (field == null) { + throw new NotReadablePropertyException( + this.target.getClass(), propertyName, "Field '" + propertyName + "' does not exist"); + } + try { + ReflectionUtils.makeAccessible(field); + return field.get(this.target); + } + catch (IllegalAccessException ex) { + throw new InvalidPropertyException(this.target.getClass(), propertyName, "Field is not accessible", ex); + } + } + + public void setPropertyValue(String propertyName, Object newValue) throws BeansException { + Field field = (Field) this.fieldMap.get(propertyName); + if (field == null) { + throw new NotWritablePropertyException( + this.target.getClass(), propertyName, "Field '" + propertyName + "' does not exist"); + } + Object oldValue = null; + try { + ReflectionUtils.makeAccessible(field); + oldValue = field.get(this.target); + Object convertedValue = + this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue, newValue, field.getType()); + field.set(this.target, convertedValue); + } + catch (IllegalAccessException ex) { + throw new InvalidPropertyException(this.target.getClass(), propertyName, "Field is not accessible", ex); + } + catch (IllegalArgumentException ex) { + PropertyChangeEvent pce = new PropertyChangeEvent(this.target, propertyName, oldValue, newValue); + throw new TypeMismatchException(pce, field.getType(), ex); + } + } + + public Object convertIfNecessary( + Object value, Class requiredType, MethodParameter methodParam) throws TypeMismatchException { + try { + return this.typeConverterDelegate.convertIfNecessary(value, requiredType, methodParam); + } + catch (IllegalArgumentException ex) { + throw new TypeMismatchException(value, requiredType, ex); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/FatalBeanException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/FatalBeanException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/FatalBeanException.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Thrown on an unrecoverable problem encountered in the + * beans packages or sub-packages, e.g. bad class or field. + * + * @author Rod Johnson + */ +public class FatalBeanException extends BeansException { + + /** + * Create a new FatalBeanException with the specified message. + * @param msg the detail message + */ + public FatalBeanException(String msg) { + super(msg); + } + + /** + * Create a new FatalBeanException with the specified message + * and root cause. + * @param msg the detail message + * @param cause the root cause + */ + public FatalBeanException(String msg, Throwable cause) { + super(msg, cause); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/GenericTypeAwarePropertyDescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/GenericTypeAwarePropertyDescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/GenericTypeAwarePropertyDescriptor.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,114 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.IntrospectionException; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Method; + +import org.springframework.core.BridgeMethodResolver; +import org.springframework.core.GenericTypeResolver; +import org.springframework.core.MethodParameter; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +/** + * Extension of the standard JavaBeans PropertyDescriptor class, + * overriding getPropertyType() such that a generically + * declared type will be resolved against the containing bean class. + * + * @author Juergen Hoeller + * @since 2.5.2 + */ +class GenericTypeAwarePropertyDescriptor extends PropertyDescriptor { + + private final Class beanClass; + + private final Method readMethod; + + private final Method writeMethod; + + private final Class propertyEditorClass; + + private Class propertyType; + + private MethodParameter writeMethodParameter; + + + public GenericTypeAwarePropertyDescriptor(Class beanClass, String propertyName, + Method readMethod, Method writeMethod, Class propertyEditorClass) + throws IntrospectionException { + + super(propertyName, null, null); + this.beanClass = beanClass; + Method readMethodToUse = BridgeMethodResolver.findBridgedMethod(readMethod); + Method writeMethodToUse = BridgeMethodResolver.findBridgedMethod(writeMethod); + if (writeMethodToUse == null && readMethodToUse != null) { + // Fallback: Original JavaBeans introspection might not have found matching setter + // method due to lack of bridge method resolution, in case of the getter using a + // covariant return type whereas the setter is defined for the concrete property type. + writeMethodToUse = ClassUtils.getMethodIfAvailable(this.beanClass, + "set" + StringUtils.capitalize(getName()), new Class[] {readMethodToUse.getReturnType()}); + } + this.readMethod = readMethodToUse; + this.writeMethod = writeMethodToUse; + this.propertyEditorClass = propertyEditorClass; + } + + + public Method getReadMethod() { + return this.readMethod; + } + + public Method getWriteMethod() { + return this.writeMethod; + } + + public Class getPropertyEditorClass() { + return this.propertyEditorClass; + } + + public synchronized Class getPropertyType() { + if (this.propertyType == null) { + if (this.readMethod != null) { + this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass); + } + else { + MethodParameter writeMethodParam = getWriteMethodParameter(); + if (writeMethodParam != null) { + this.propertyType = writeMethodParam.getParameterType(); + } + else { + this.propertyType = super.getPropertyType(); + } + } + } + return this.propertyType; + } + + public synchronized MethodParameter getWriteMethodParameter() { + if (this.writeMethod == null) { + return null; + } + if (this.writeMethodParameter == null) { + this.writeMethodParameter = new MethodParameter(this.writeMethod, 0); + GenericTypeResolver.resolveParameterType(this.writeMethodParameter, this.beanClass); + } + return this.writeMethodParameter; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/InvalidPropertyException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/InvalidPropertyException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/InvalidPropertyException.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Exception thrown when referring to an invalid bean property. + * Carries the offending bean class and property name. + * + * @author Juergen Hoeller + * @since 1.0.2 + */ +public class InvalidPropertyException extends FatalBeanException { + + private Class beanClass; + + private String propertyName; + + + /** + * Create a new InvalidPropertyException. + * @param beanClass the offending bean class + * @param propertyName the offending property + * @param msg the detail message + */ + public InvalidPropertyException(Class beanClass, String propertyName, String msg) { + this(beanClass, propertyName, msg, null); + } + + /** + * Create a new InvalidPropertyException. + * @param beanClass the offending bean class + * @param propertyName the offending property + * @param msg the detail message + * @param cause the root cause + */ + public InvalidPropertyException(Class beanClass, String propertyName, String msg, Throwable cause) { + super("Invalid property '" + propertyName + "' of bean class [" + beanClass.getName() + "]: " + msg, cause); + this.beanClass = beanClass; + this.propertyName = propertyName; + } + + /** + * Return the offending bean class. + */ + public Class getBeanClass() { + return beanClass; + } + + /** + * Return the name of the offending property. + */ + public String getPropertyName() { + return propertyName; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/Mergeable.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/Mergeable.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/Mergeable.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Interface representing an object whose value set can be merged with + * that of a parent object. + * + * @author Rob Harrop + * @since 2.0 + * @see org.springframework.beans.factory.support.ManagedSet + * @see org.springframework.beans.factory.support.ManagedList + * @see org.springframework.beans.factory.support.ManagedMap + * @see org.springframework.beans.factory.support.ManagedProperties + */ +public interface Mergeable { + + /** + * Is merging enabled for this particular instance? + */ + boolean isMergeEnabled(); + + /** + * Merge the current value set with that of the supplied object. + *

    The supplied object is considered the parent, and values in + * the callee's value set must override those of the supplied object. + * @param parent the object to merge with + * @return the result of the merge operation + * @throws IllegalArgumentException if the supplied parent is null + * @exception IllegalStateException if merging is not enabled for this instance + * (i.e. mergeEnabled equals false). + */ + Object merge(Object parent); + +} Index: 3rdParty_sources/spring/org/springframework/beans/MethodInvocationException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/MethodInvocationException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/MethodInvocationException.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyChangeEvent; + +/** + * Thrown when a bean property getter or setter method throws an exception, + * analogous to an InvocationTargetException. + * + * @author Rod Johnson + */ +public class MethodInvocationException extends PropertyAccessException { + + /** + * Error code that a method invocation error will be registered with. + */ + public static final String ERROR_CODE = "methodInvocation"; + + + /** + * Create a new MethodInvocationException. + * @param propertyChangeEvent PropertyChangeEvent that resulted in an exception + * @param cause the Throwable raised by the invoked method + */ + public MethodInvocationException(PropertyChangeEvent propertyChangeEvent, Throwable cause) { + super(propertyChangeEvent, "Property '" + propertyChangeEvent.getPropertyName() + "' threw exception", cause); + } + + public String getErrorCode() { + return ERROR_CODE; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/MutablePropertyValues.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/MutablePropertyValues.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/MutablePropertyValues.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,350 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.springframework.util.StringUtils; + +/** + * Default implementation of the {@link PropertyValues} interface. + * Allows simple manipulation of properties, and provides constructors + * to support deep copy and construction from a Map. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + * @since 13 May 2001 + */ +public class MutablePropertyValues implements PropertyValues, Serializable { + + /** List of PropertyValue objects */ + private final List propertyValueList; + + private Set processedProperties; + + private volatile boolean converted = false; + + + /** + * Creates a new empty MutablePropertyValues object. + * Property values can be added with the addPropertyValue methods. + * @see #addPropertyValue(PropertyValue) + * @see #addPropertyValue(String, Object) + */ + public MutablePropertyValues() { + this.propertyValueList = new ArrayList(); + } + + /** + * Deep copy constructor. Guarantees PropertyValue references + * are independent, although it can't deep copy objects currently + * referenced by individual PropertyValue objects. + * @param original the PropertyValues to copy + * @see #addPropertyValues(PropertyValues) + */ + public MutablePropertyValues(PropertyValues original) { + // We can optimize this because it's all new: + // There is no replacement of existing property values. + if (original != null) { + PropertyValue[] pvs = original.getPropertyValues(); + this.propertyValueList = new ArrayList(pvs.length); + for (int i = 0; i < pvs.length; i++) { + PropertyValue newPv = new PropertyValue(pvs[i]); + this.propertyValueList.add(newPv); + } + } + else { + this.propertyValueList = new ArrayList(0); + } + } + + /** + * Construct a new MutablePropertyValues object from a Map. + * @param original Map with property values keyed by property name Strings + * @see #addPropertyValues(Map) + */ + public MutablePropertyValues(Map original) { + // We can optimize this because it's all new: + // There is no replacement of existing property values. + if (original != null) { + this.propertyValueList = new ArrayList(original.size()); + Iterator it = original.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + PropertyValue newPv = new PropertyValue((String) entry.getKey(), entry.getValue()); + this.propertyValueList.add(newPv); + } + } + else { + this.propertyValueList = new ArrayList(0); + } + } + + /** + * Construct a new MutablePropertyValues object using the given List of + * PropertyValue objects as-is. + *

    This is a constructor for advanced usage scenarios. + * It is not intended for typical programmatic use. + * @param propertyValueList List of PropertyValue objects + */ + public MutablePropertyValues(List propertyValueList) { + this.propertyValueList = (propertyValueList != null ? propertyValueList : new ArrayList()); + } + + + /** + * Return the underlying List of PropertyValue objects in its raw form. + * The returned List can be modified directly, although this is not recommended. + *

    This is an accessor for optimized access to all PropertyValue objects. + * It is not intended for typical programmatic use. + */ + public List getPropertyValueList() { + return this.propertyValueList; + } + + /** + * Copy all given PropertyValues into this object. Guarantees PropertyValue + * references are independent, although it can't deep copy objects currently + * referenced by individual PropertyValue objects. + * @param other the PropertyValues to copy + * @return this object to allow creating objects, adding multiple PropertyValues + * in a single statement + */ + public MutablePropertyValues addPropertyValues(PropertyValues other) { + if (other != null) { + PropertyValue[] pvs = other.getPropertyValues(); + for (int i = 0; i < pvs.length; i++) { + PropertyValue newPv = new PropertyValue(pvs[i]); + addPropertyValue(newPv); + } + } + return this; + } + + /** + * Add all property values from the given Map. + * @param other Map with property values keyed by property name, + * which must be a String + * @return this object to allow creating objects, adding multiple + * PropertyValues in a single statement + */ + public MutablePropertyValues addPropertyValues(Map other) { + if (other != null) { + Iterator it = other.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + PropertyValue newPv = new PropertyValue((String) entry.getKey(), entry.getValue()); + addPropertyValue(newPv); + } + } + return this; + } + + /** + * Add a PropertyValue object, replacing any existing one + * for the corresponding property. + * @param pv PropertyValue object to add + * @return this object to allow creating objects, adding multiple + * PropertyValues in a single statement + */ + public MutablePropertyValues addPropertyValue(PropertyValue pv) { + for (int i = 0; i < this.propertyValueList.size(); i++) { + PropertyValue currentPv = (PropertyValue) this.propertyValueList.get(i); + if (currentPv.getName().equals(pv.getName())) { + pv = mergeIfRequired(pv, currentPv); + setPropertyValueAt(pv, i); + return this; + } + } + this.propertyValueList.add(pv); + return this; + } + + /** + * Overloaded version of addPropertyValue that takes + * a property name and a property value. + * @param propertyName name of the property + * @param propertyValue value of the property + * @see #addPropertyValue(PropertyValue) + */ + public void addPropertyValue(String propertyName, Object propertyValue) { + addPropertyValue(new PropertyValue(propertyName, propertyValue)); + } + + /** + * Modify a PropertyValue object held in this object. + * Indexed from 0. + */ + public void setPropertyValueAt(PropertyValue pv, int i) { + this.propertyValueList.set(i, pv); + } + + /** + * Merges the value of the supplied 'new' {@link PropertyValue} with that of + * the current {@link PropertyValue} if merging is supported and enabled. + * @see Mergeable + */ + private PropertyValue mergeIfRequired(PropertyValue newPv, PropertyValue currentPv) { + Object value = newPv.getValue(); + if (value instanceof Mergeable) { + Mergeable mergeable = (Mergeable) value; + if (mergeable.isMergeEnabled()) { + Object merged = mergeable.merge(currentPv.getValue()); + return new PropertyValue(newPv.getName(), merged); + } + } + return newPv; + } + + /** + * Overloaded version of removePropertyValue that takes a property name. + * @param propertyName name of the property + * @see #removePropertyValue(PropertyValue) + */ + public void removePropertyValue(String propertyName) { + removePropertyValue(getPropertyValue(propertyName)); + } + + /** + * Remove the given PropertyValue, if contained. + * @param pv the PropertyValue to remove + */ + public void removePropertyValue(PropertyValue pv) { + this.propertyValueList.remove(pv); + } + + /** + * Clear this holder, removing all PropertyValues. + */ + public void clear() { + this.propertyValueList.clear(); + } + + + public PropertyValue[] getPropertyValues() { + return (PropertyValue[]) + this.propertyValueList.toArray(new PropertyValue[this.propertyValueList.size()]); + } + + public PropertyValue getPropertyValue(String propertyName) { + for (int i = 0; i < this.propertyValueList.size(); i++) { + PropertyValue pv = (PropertyValue) this.propertyValueList.get(i); + if (pv.getName().equals(propertyName)) { + return pv; + } + } + return null; + } + + /** + * Register the specified property as "processed" in the sense + * of some processor calling the corresponding setter method + * outside of the PropertyValue(s) mechanism. + *

    This will lead to true being returned from + * a {@link #contains} call for the specified property. + * @param propertyName the name of the property. + */ + public void registerProcessedProperty(String propertyName) { + if (this.processedProperties == null) { + this.processedProperties = new HashSet(); + } + this.processedProperties.add(propertyName); + } + + public boolean contains(String propertyName) { + return (getPropertyValue(propertyName) != null || + (this.processedProperties != null && this.processedProperties.contains(propertyName))); + } + + public boolean isEmpty() { + return this.propertyValueList.isEmpty(); + } + + public int size() { + return this.propertyValueList.size(); + } + + public PropertyValues changesSince(PropertyValues old) { + MutablePropertyValues changes = new MutablePropertyValues(); + if (old == this) { + return changes; + } + + // for each property value in the new set + for (Iterator it = this.propertyValueList.iterator(); it.hasNext();) { + PropertyValue newPv = (PropertyValue) it.next(); + // if there wasn't an old one, add it + PropertyValue pvOld = old.getPropertyValue(newPv.getName()); + if (pvOld == null) { + changes.addPropertyValue(newPv); + } + else if (!pvOld.equals(newPv)) { + // it's changed + changes.addPropertyValue(newPv); + } + } + return changes; + } + + + /** + * Mark this holder as containing converted values only + * (i.e. no runtime resolution needed anymore). + */ + public void setConverted() { + this.converted = true; + } + + /** + * Return whether this holder contains converted values only (true), + * or whether the values still need to be converted (false). + */ + public boolean isConverted() { + return this.converted; + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof MutablePropertyValues)) { + return false; + } + MutablePropertyValues that = (MutablePropertyValues) other; + return this.propertyValueList.equals(that.propertyValueList); + } + + public int hashCode() { + return this.propertyValueList.hashCode(); + } + + public String toString() { + PropertyValue[] pvs = getPropertyValues(); + StringBuffer sb = new StringBuffer("PropertyValues: length=" + pvs.length + "; "); + sb.append(StringUtils.arrayToDelimitedString(pvs, "; ")); + return sb.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/NotReadablePropertyException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/NotReadablePropertyException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/NotReadablePropertyException.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Exception thrown on an attempt to get the value of a property + * that isn't readable, because there's no getter method. + * + * @author Juergen Hoeller + * @since 1.0.2 + */ +public class NotReadablePropertyException extends InvalidPropertyException { + + /** + * Create a new NotReadablePropertyException. + * @param beanClass the offending bean class + * @param propertyName the offending property + */ + public NotReadablePropertyException(Class beanClass, String propertyName) { + super(beanClass, propertyName, + "Bean property '" + propertyName + "' is not readable or has an invalid getter method: " + + "Does the return type of the getter match the parameter type of the setter?"); + } + + /** + * Create a new NotReadablePropertyException. + * @param beanClass the offending bean class + * @param propertyName the offending property + * @param msg the detail message + */ + public NotReadablePropertyException(Class beanClass, String propertyName, String msg) { + super(beanClass, propertyName, msg); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/NotWritablePropertyException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/NotWritablePropertyException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/NotWritablePropertyException.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,86 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Exception thrown on an attempt to set the value of a property that + * is not writable (typically because there is no setter method). + * + * @author Rod Johnson + * @author Alef Arendsen + * @author Arjen Poutsma + */ +public class NotWritablePropertyException extends InvalidPropertyException { + + private String[] possibleMatches = null; + + + /** + * Create a new NotWritablePropertyException. + * @param beanClass the offending bean class + * @param propertyName the offending property name + */ + public NotWritablePropertyException(Class beanClass, String propertyName) { + super(beanClass, propertyName, + "Bean property '" + propertyName + "' is not writable or has an invalid setter method: " + + "Does the return type of the getter match the parameter type of the setter?"); + } + + /** + * Create a new NotWritablePropertyException. + * @param beanClass the offending bean class + * @param propertyName the offending property name + * @param msg the detail message + */ + public NotWritablePropertyException(Class beanClass, String propertyName, String msg) { + super(beanClass, propertyName, msg); + } + + /** + * Create a new NotWritablePropertyException. + * @param beanClass the offending bean class + * @param propertyName the offending property name + * @param msg the detail message + * @param cause the root cause + */ + public NotWritablePropertyException(Class beanClass, String propertyName, String msg, Throwable cause) { + super(beanClass, propertyName, msg, cause); + } + + /** + * Create a new NotWritablePropertyException. + * @param beanClass the offending bean class + * @param propertyName the offending property name + * @param msg the detail message + * @param possibleMatches suggestions for actual bean property names + * that closely match the invalid property name + */ + public NotWritablePropertyException(Class beanClass, String propertyName, String msg, String[] possibleMatches) { + super(beanClass, propertyName, msg); + this.possibleMatches = possibleMatches; + } + + + /** + * Return suggestions for actual bean property names that closely match + * the invalid property name, if any. + */ + public String[] getPossibleMatches() { + return this.possibleMatches; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/NullValueInNestedPathException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/NullValueInNestedPathException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/NullValueInNestedPathException.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Exception thrown when navigation of a valid nested property + * path encounters a NullPointerException. + * + *

    For example, navigating "spouse.age" could fail because the + * spouse property of the target object has a null value. + * + * @author Rod Johnson + */ +public class NullValueInNestedPathException extends InvalidPropertyException { + + /** + * Create a new NullValueInNestedPathException. + * @param beanClass the offending bean class + * @param propertyName the offending property + */ + public NullValueInNestedPathException(Class beanClass, String propertyName) { + super(beanClass, propertyName, "Value of nested property '" + propertyName + "' is null"); + } + + /** + * Create a new NullValueInNestedPathException. + * @param beanClass the offending bean class + * @param propertyName the offending property + * @param msg the detail message + */ + public NullValueInNestedPathException(Class beanClass, String propertyName, String msg) { + super(beanClass, propertyName, msg); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/PropertyAccessException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/PropertyAccessException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/PropertyAccessException.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyChangeEvent; + +import org.springframework.core.ErrorCoded; + +/** + * Superclass for exceptions related to a property access, + * such as type mismatch or invocation target exception. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public abstract class PropertyAccessException extends BeansException implements ErrorCoded { + + private transient PropertyChangeEvent propertyChangeEvent; + + + /** + * Create a new PropertyAccessException. + * @param propertyChangeEvent the PropertyChangeEvent that resulted in the problem + * @param msg the detail message + * @param cause the root cause + */ + public PropertyAccessException(PropertyChangeEvent propertyChangeEvent, String msg, Throwable cause) { + super(msg, cause); + this.propertyChangeEvent = propertyChangeEvent; + } + + /** + * Create a new PropertyAccessException without PropertyChangeEvent. + * @param msg the detail message + * @param cause the root cause + */ + public PropertyAccessException(String msg, Throwable cause) { + super(msg, cause); + } + + + /** + * Return the PropertyChangeEvent that resulted in the problem. + * May be null; only available if an actual bean property + * was affected. + */ + public PropertyChangeEvent getPropertyChangeEvent() { + return this.propertyChangeEvent; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/PropertyAccessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/PropertyAccessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/PropertyAccessor.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,204 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.util.Map; + +/** + * Common interface for classes that can access named properties + * (such as bean properties of an object or fields in an object) + * Serves as base interface for {@link BeanWrapper}. + * + * @author Juergen Hoeller + * @since 1.1 + * @see BeanWrapper + * @see PropertyAccessorFactory#forBeanPropertyAccess + * @see PropertyAccessorFactory#forDirectFieldAccess + */ +public interface PropertyAccessor { + + /** + * Path separator for nested properties. + * Follows normal Java conventions: getFoo().getBar() would be "foo.bar". + */ + String NESTED_PROPERTY_SEPARATOR = "."; + char NESTED_PROPERTY_SEPARATOR_CHAR = '.'; + + /** + * Marker that indicates the start of a property key for an + * indexed or mapped property like "person.addresses[0]". + */ + String PROPERTY_KEY_PREFIX = "["; + char PROPERTY_KEY_PREFIX_CHAR = '['; + + /** + * Marker that indicates the end of a property key for an + * indexed or mapped property like "person.addresses[0]". + */ + String PROPERTY_KEY_SUFFIX = "]"; + char PROPERTY_KEY_SUFFIX_CHAR = ']'; + + + /** + * Determine whether the specified property is readable. + *

    Returns false if the property doesn't exist. + * @param propertyName the property to check + * (may be a nested path and/or an indexed/mapped property) + * @return whether the property is readable + */ + boolean isReadableProperty(String propertyName); + + /** + * Determine whether the specified property is writable. + *

    Returns false if the property doesn't exist. + * @param propertyName the property to check + * (may be a nested path and/or an indexed/mapped property) + * @return whether the property is writable + */ + boolean isWritableProperty(String propertyName); + + /** + * Determine the property type for the specified property, + * either checking the property descriptor or checking the value + * in case of an indexed or mapped element. + * @param propertyName the property to check + * (may be a nested path and/or an indexed/mapped property) + * @return the property type for the particular property, + * or null if not determinable + * @throws InvalidPropertyException if there is no such property or + * if the property isn't readable + * @throws PropertyAccessException if the property was valid but the + * accessor method failed + */ + Class getPropertyType(String propertyName) throws BeansException; + + /** + * Get the current value of the specified property. + * @param propertyName the name of the property to get the value of + * (may be a nested path and/or an indexed/mapped property) + * @return the value of the property + * @throws InvalidPropertyException if there is no such property or + * if the property isn't readable + * @throws PropertyAccessException if the property was valid but the + * accessor method failed + */ + Object getPropertyValue(String propertyName) throws BeansException; + + /** + * Set the specified value as current property value. + * @param propertyName the name of the property to set the value of + * (may be a nested path and/or an indexed/mapped property) + * @param value the new value + * @throws InvalidPropertyException if there is no such property or + * if the property isn't writable + * @throws PropertyAccessException if the property was valid but the + * accessor method failed or a type mismatch occured + */ + void setPropertyValue(String propertyName, Object value) throws BeansException; + + /** + * Set the specified value as current property value. + * @param pv an object containing the new property value + * @throws InvalidPropertyException if there is no such property or + * if the property isn't writable + * @throws PropertyAccessException if the property was valid but the + * accessor method failed or a type mismatch occured + */ + void setPropertyValue(PropertyValue pv) throws BeansException; + + /** + * Perform a batch update from a Map. + *

    Bulk updates from PropertyValues are more powerful: This method is + * provided for convenience. Behavior will be identical to that of + * the {@link #setPropertyValues(PropertyValues)} method. + * @param map Map to take properties from. Contains property value objects, + * keyed by property name + * @throws InvalidPropertyException if there is no such property or + * if the property isn't writable + * @throws PropertyBatchUpdateException if one or more PropertyAccessExceptions + * occured for specific properties during the batch update. This exception bundles + * all individual PropertyAccessExceptions. All other properties will have been + * successfully updated. + */ + void setPropertyValues(Map map) throws BeansException; + + /** + * The preferred way to perform a batch update. + *

    Note that performing a batch update differs from performing a single update, + * in that an implementation of this class will continue to update properties + * if a recoverable error (such as a type mismatch, but not an + * invalid field name or the like) is encountered, throwing a + * {@link PropertyBatchUpdateException} containing all the individual errors. + * This exception can be examined later to see all binding errors. + * Properties that were successfully updated remain changed. + *

    Does not allow unknown fields or invalid fields. + * @param pvs PropertyValues to set on the target object + * @throws InvalidPropertyException if there is no such property or + * if the property isn't writable + * @throws PropertyBatchUpdateException if one or more PropertyAccessExceptions + * occured for specific properties during the batch update. This exception bundles + * all individual PropertyAccessExceptions. All other properties will have been + * successfully updated. + * @see #setPropertyValues(PropertyValues, boolean, boolean) + */ + void setPropertyValues(PropertyValues pvs) throws BeansException; + + /** + * Perform a batch update with more control over behavior. + *

    Note that performing a batch update differs from performing a single update, + * in that an implementation of this class will continue to update properties + * if a recoverable error (such as a type mismatch, but not an + * invalid field name or the like) is encountered, throwing a + * {@link PropertyBatchUpdateException} containing all the individual errors. + * This exception can be examined later to see all binding errors. + * Properties that were successfully updated remain changed. + * @param pvs PropertyValues to set on the target object + * @param ignoreUnknown should we ignore unknown properties (not found in the bean) + * @throws InvalidPropertyException if there is no such property or + * if the property isn't writable + * @throws PropertyBatchUpdateException if one or more PropertyAccessExceptions + * occured for specific properties during the batch update. This exception bundles + * all individual PropertyAccessExceptions. All other properties will have been + * successfully updated. + * @see #setPropertyValues(PropertyValues, boolean, boolean) + */ + void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown) + throws BeansException; + + /** + * Perform a batch update with full control over behavior. + *

    Note that performing a batch update differs from performing a single update, + * in that an implementation of this class will continue to update properties + * if a recoverable error (such as a type mismatch, but not an + * invalid field name or the like) is encountered, throwing a + * {@link PropertyBatchUpdateException} containing all the individual errors. + * This exception can be examined later to see all binding errors. + * Properties that were successfully updated remain changed. + * @param pvs PropertyValues to set on the target object + * @param ignoreUnknown should we ignore unknown properties (not found in the bean) + * @param ignoreInvalid should we ignore invalid properties (found but not accessible) + * @throws InvalidPropertyException if there is no such property or + * if the property isn't writable + * @throws PropertyBatchUpdateException if one or more PropertyAccessExceptions + * occured for specific properties during the batch update. This exception bundles + * all individual PropertyAccessExceptions. All other properties will have been + * successfully updated. + */ + void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid) + throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/PropertyAccessorFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/PropertyAccessorFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/PropertyAccessorFactory.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Simple factory facade for obtaining {@link PropertyAccessor} instances, + * in particular for {@link BeanWrapper} instances. Conceals the actual + * target implementation classes and their extended public signature. + * + * @author Juergen Hoeller + * @since 2.5.2 + */ +public abstract class PropertyAccessorFactory { + + /** + * Obtain a BeanWrapper for the given target object, + * accessing properties in JavaBeans style. + * @param target the target object to wrap + * @return the property accessor + * @see BeanWrapperImpl + */ + public static BeanWrapper forBeanPropertyAccess(Object target) { + return new BeanWrapperImpl(target); + } + + /** + * Obtain a PropertyAccessor for the given target object, + * accessing properties in direct field style. + * @param target the target object to wrap + * @return the property accessor + * @see DirectFieldAccessor + */ + public static ConfigurablePropertyAccessor forDirectFieldAccess(Object target) { + return new DirectFieldAccessor(target); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/PropertyAccessorUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/PropertyAccessorUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/PropertyAccessorUtils.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,184 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Utility methods for classes that perform bean property access + * according to the {@link PropertyAccessor} interface. + * + * @author Juergen Hoeller + * @since 1.2.6 + */ +public abstract class PropertyAccessorUtils { + + /** + * Return the actual property name for the given property path. + * @param propertyPath the property path to determine the property name + * for (can include property keys, for example for specifying a map entry) + * @return the actual property name, without any key elements + */ + public static String getPropertyName(String propertyPath) { + int separatorIndex = propertyPath.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR); + return (separatorIndex != -1 ? propertyPath.substring(0, separatorIndex) : propertyPath); + } + + /** + * Check whether the given property path indicates an indexed or nested property. + * @param propertyPath the property path to check + * @return whether the path indicates an indexed or nested property + */ + public static boolean isNestedOrIndexedProperty(String propertyPath) { + if (propertyPath == null) { + return false; + } + for (int i = 0; i < propertyPath.length(); i++) { + char ch = propertyPath.charAt(i); + if (ch == PropertyAccessor.NESTED_PROPERTY_SEPARATOR_CHAR || + ch == PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR) { + return true; + } + } + return false; + } + + /** + * Determine the first nested property separator in the + * given property path, ignoring dots in keys (like "map[my.key]"). + * @param propertyPath the property path to check + * @return the index of the nested property separator, or -1 if none + */ + public static int getFirstNestedPropertySeparatorIndex(String propertyPath) { + return getNestedPropertySeparatorIndex(propertyPath, false); + } + + /** + * Determine the first nested property separator in the + * given property path, ignoring dots in keys (like "map[my.key]"). + * @param propertyPath the property path to check + * @return the index of the nested property separator, or -1 if none + */ + public static int getLastNestedPropertySeparatorIndex(String propertyPath) { + return getNestedPropertySeparatorIndex(propertyPath, true); + } + + /** + * Determine the first (or last) nested property separator in the + * given property path, ignoring dots in keys (like "map[my.key]"). + * @param propertyPath the property path to check + * @param last whether to return the last separator rather than the first + * @return the index of the nested property separator, or -1 if none + */ + private static int getNestedPropertySeparatorIndex(String propertyPath, boolean last) { + boolean inKey = false; + int length = propertyPath.length(); + int i = (last ? length - 1 : 0); + while (last ? i >= 0 : i < length) { + switch (propertyPath.charAt(i)) { + case PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR: + case PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR: + inKey = !inKey; + break; + case PropertyAccessor.NESTED_PROPERTY_SEPARATOR_CHAR: + if (!inKey) { + return i; + } + } + if (last) { + i--; + } + else { + i++; + } + } + return -1; + } + + /** + * Determine whether the given registered path matches the given property path, + * either indicating the property itself or an indexed element of the property. + * @param propertyPath the property path (typically without index) + * @param registeredPath the registered path (potentially with index) + * @return whether the paths match + */ + public static boolean matchesProperty(String registeredPath, String propertyPath) { + if (!registeredPath.startsWith(propertyPath)) { + return false; + } + if (registeredPath.length() == propertyPath.length()) { + return true; + } + if (registeredPath.charAt(propertyPath.length()) != PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR) { + return false; + } + return (registeredPath.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR, propertyPath.length() + 1) == + registeredPath.length() - 1); + } + + /** + * Determine the canonical name for the given property path. + * Removes surrounding quotes from map keys:
    + * map['key'] -> map[key]
    + * map["key"] -> map[key] + * @param propertyName the bean property path + * @return the canonical representation of the property path + */ + public static String canonicalPropertyName(String propertyName) { + if (propertyName == null) { + return ""; + } + + StringBuffer buf = new StringBuffer(propertyName); + int searchIndex = 0; + while (searchIndex != -1) { + int keyStart = buf.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX, searchIndex); + searchIndex = -1; + if (keyStart != -1) { + int keyEnd = buf.indexOf( + PropertyAccessor.PROPERTY_KEY_SUFFIX, keyStart + PropertyAccessor.PROPERTY_KEY_PREFIX.length()); + if (keyEnd != -1) { + String key = buf.substring(keyStart + PropertyAccessor.PROPERTY_KEY_PREFIX.length(), keyEnd); + if ((key.startsWith("'") && key.endsWith("'")) || (key.startsWith("\"") && key.endsWith("\""))) { + buf.delete(keyStart + 1, keyStart + 2); + buf.delete(keyEnd - 2, keyEnd - 1); + keyEnd = keyEnd - 2; + } + searchIndex = keyEnd + PropertyAccessor.PROPERTY_KEY_SUFFIX.length(); + } + } + } + return buf.toString(); + } + + /** + * Determine the canonical names for the given property paths. + * @param propertyNames the bean property paths (as array) + * @return the canonical representation of the property paths + * (as array of the same size) + * @see #canonicalPropertyName(String) + */ + public static String[] canonicalPropertyNames(String[] propertyNames) { + if (propertyNames == null) { + return null; + } + String[] result = new String[propertyNames.length]; + for (int i = 0; i < propertyNames.length; i++) { + result[i] = canonicalPropertyName(propertyNames[i]); + } + return result; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/PropertyBatchUpdateException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/PropertyBatchUpdateException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/PropertyBatchUpdateException.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,143 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.io.PrintStream; +import java.io.PrintWriter; + +import org.springframework.util.Assert; + +/** + * Combined exception, composed of individual PropertyAccessException instances. + * An object of this class is created at the beginning of the binding + * process, and errors added to it as necessary. + * + *

    The binding process continues when it encounters application-level + * PropertyAccessExceptions, applying those changes that can be applied + * and storing rejected changes in an object of this class. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 18 April 2001 + */ +public class PropertyBatchUpdateException extends BeansException { + + /** List of PropertyAccessException objects */ + private PropertyAccessException[] propertyAccessExceptions; + + + /** + * Create a new PropertyBatchUpdateException. + * @param propertyAccessExceptions the List of PropertyAccessExceptions + */ + public PropertyBatchUpdateException(PropertyAccessException[] propertyAccessExceptions) { + super(null); + Assert.notEmpty(propertyAccessExceptions, "At least 1 PropertyAccessException required"); + this.propertyAccessExceptions = propertyAccessExceptions; + } + + + /** + * If this returns 0, no errors were encountered during binding. + */ + public final int getExceptionCount() { + return this.propertyAccessExceptions.length; + } + + /** + * Return an array of the propertyAccessExceptions stored in this object. + * Will return the empty array (not null) if there were no errors. + */ + public final PropertyAccessException[] getPropertyAccessExceptions() { + return this.propertyAccessExceptions; + } + + /** + * Return the exception for this field, or null if there isn't one. + */ + public PropertyAccessException getPropertyAccessException(String propertyName) { + for (int i = 0; i < this.propertyAccessExceptions.length; i++) { + PropertyAccessException pae = this.propertyAccessExceptions[i]; + if (propertyName.equals(pae.getPropertyChangeEvent().getPropertyName())) { + return pae; + } + } + return null; + } + + + public String getMessage() { + StringBuffer sb = new StringBuffer("Failed properties: "); + for (int i = 0; i < this.propertyAccessExceptions.length; i++) { + sb.append(this.propertyAccessExceptions[i].getMessage()); + if (i < this.propertyAccessExceptions.length - 1) { + sb.append("; "); + } + } + return sb.toString(); + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append(getClass().getName()).append("; nested PropertyAccessExceptions ("); + sb.append(getExceptionCount()).append(") are:"); + for (int i = 0; i < this.propertyAccessExceptions.length; i++) { + sb.append('\n').append("PropertyAccessException ").append(i + 1).append(": "); + sb.append(this.propertyAccessExceptions[i]); + } + return sb.toString(); + } + + public void printStackTrace(PrintStream ps) { + synchronized (ps) { + ps.println(getClass().getName() + "; nested PropertyAccessException details (" + + getExceptionCount() + ") are:"); + for (int i = 0; i < this.propertyAccessExceptions.length; i++) { + ps.println("PropertyAccessException " + (i + 1) + ":"); + this.propertyAccessExceptions[i].printStackTrace(ps); + } + } + } + + public void printStackTrace(PrintWriter pw) { + synchronized (pw) { + pw.println(getClass().getName() + "; nested PropertyAccessException details (" + + getExceptionCount() + ") are:"); + for (int i = 0; i < this.propertyAccessExceptions.length; i++) { + pw.println("PropertyAccessException " + (i + 1) + ":"); + this.propertyAccessExceptions[i].printStackTrace(pw); + } + } + } + + public boolean contains(Class exType) { + if (exType == null) { + return false; + } + if (exType.isInstance(this)) { + return true; + } + for (int i = 0; i < this.propertyAccessExceptions.length; i++) { + PropertyAccessException pae = this.propertyAccessExceptions[i]; + if (pae.contains(exType)) { + return true; + } + } + return false; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/PropertyEditorRegistrar.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/PropertyEditorRegistrar.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/PropertyEditorRegistrar.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Interface for strategies that register custom + * {@link java.beans.PropertyEditor property editors} with a + * {@link org.springframework.beans.PropertyEditorRegistry property editor registry}. + * + *

    This is particularly useful when you need to use the same set of + * property editors in several different situations: write a corresponding + * registrar and reuse that in each case. + * + * @author Juergen Hoeller + * @since 1.2.6 + * @see PropertyEditorRegistry + * @see java.beans.PropertyEditor + */ +public interface PropertyEditorRegistrar { + + /** + * Register custom {@link java.beans.PropertyEditor PropertyEditors} with + * the given PropertyEditorRegistry. + *

    The passed-in registry will usually be a {@link BeanWrapper} or a + * {@link org.springframework.validation.DataBinder DataBinder}. + *

    It is expected that implementations will create brand new + * PropertyEditors instances for each invocation of this + * method (since PropertyEditors are not threadsafe). + * @param registry the PropertyEditorRegistry to register the + * custom PropertyEditors with + */ + void registerCustomEditors(PropertyEditorRegistry registry); + +} Index: 3rdParty_sources/spring/org/springframework/beans/PropertyEditorRegistry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/PropertyEditorRegistry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/PropertyEditorRegistry.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,79 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyEditor; + +/** + * Encapsulates methods for registering JavaBeans {@link PropertyEditor PropertyEditors}. + * This is the central interface that a {@link PropertyEditorRegistrar} operates on. + * + *

    Extended by {@link BeanWrapper}; implemented by {@link BeanWrapperImpl} + * and {@link org.springframework.validation.DataBinder}. + * + * @author Juergen Hoeller + * @since 1.2.6 + * @see java.beans.PropertyEditor + * @see PropertyEditorRegistrar + * @see BeanWrapper + * @see org.springframework.validation.DataBinder + */ +public interface PropertyEditorRegistry { + + /** + * Register the given custom property editor for all properties of the given type. + * @param requiredType the type of the property + * @param propertyEditor the editor to register + */ + void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor); + + /** + * Register the given custom property editor for the given type and + * property, or for all properties of the given type. + *

    If the property path denotes an array or Collection property, + * the editor will get applied either to the array/Collection itself + * (the {@link PropertyEditor} has to create an array or Collection value) or + * to each element (the PropertyEditor has to create the element type), + * depending on the specified required type. + *

    Note: Only one single registered custom editor per property path + * is supported. In the case of a Collection/array, do not register an editor + * for both the Collection/array and each element on the same property. + *

    For example, if you wanted to register an editor for "items[n].quantity" + * (for all values n), you would use "items.quantity" as the value of the + * 'propertyPath' argument to this method. + * @param requiredType the type of the property. This may be null + * if a property is given but should be specified in any case, in particular in + * case of a Collection - making clear whether the editor is supposed to apply + * to the entire Collection itself or to each of its entries. So as a general rule: + * Do not specify null here in case of a Collection/array! + * @param propertyPath the path of the property (name or nested path), or + * null if registering an editor for all properties of the given type + * @param propertyEditor editor to register + */ + void registerCustomEditor(Class requiredType, String propertyPath, PropertyEditor propertyEditor); + + /** + * Find a custom property editor for the given type and property. + * @param requiredType the type of the property (can be null if a property + * is given but should be specified in any case for consistency checking) + * @param propertyPath the path of the property (name or nested path), or + * null if looking for an editor for all properties of the given type + * @return the registered editor, or null if none + */ + PropertyEditor findCustomEditor(Class requiredType, String propertyPath); + +} Index: 3rdParty_sources/spring/org/springframework/beans/PropertyEditorRegistrySupport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/PropertyEditorRegistrySupport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/PropertyEditorRegistrySupport.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,539 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyEditor; +import java.io.File; +import java.io.InputStream; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.URI; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.regex.Pattern; + +import org.springframework.beans.propertyeditors.ByteArrayPropertyEditor; +import org.springframework.beans.propertyeditors.CharArrayPropertyEditor; +import org.springframework.beans.propertyeditors.CharacterEditor; +import org.springframework.beans.propertyeditors.CharsetEditor; +import org.springframework.beans.propertyeditors.ClassArrayEditor; +import org.springframework.beans.propertyeditors.ClassEditor; +import org.springframework.beans.propertyeditors.CustomBooleanEditor; +import org.springframework.beans.propertyeditors.CustomCollectionEditor; +import org.springframework.beans.propertyeditors.CustomMapEditor; +import org.springframework.beans.propertyeditors.CustomNumberEditor; +import org.springframework.beans.propertyeditors.FileEditor; +import org.springframework.beans.propertyeditors.InputStreamEditor; +import org.springframework.beans.propertyeditors.LocaleEditor; +import org.springframework.beans.propertyeditors.PatternEditor; +import org.springframework.beans.propertyeditors.PropertiesEditor; +import org.springframework.beans.propertyeditors.StringArrayPropertyEditor; +import org.springframework.beans.propertyeditors.URIEditor; +import org.springframework.beans.propertyeditors.URLEditor; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.ResourceArrayPropertyEditor; +import org.springframework.util.ClassUtils; + +/** + * Base implementation of the {@link PropertyEditorRegistry} interface. + * Provides management of default editors and custom editors. + * Mainly serves as base class for {@link BeanWrapperImpl}. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @since 1.2.6 + * @see java.beans.PropertyEditorManager + * @see java.beans.PropertyEditorSupport#setAsText + * @see java.beans.PropertyEditorSupport#setValue + */ +public class PropertyEditorRegistrySupport implements PropertyEditorRegistry { + + private boolean defaultEditorsActive = false; + + private boolean configValueEditorsActive = false; + + private boolean propertySpecificEditorsRegistered = false; + + private Map defaultEditors; + + private Map customEditors; + + private Set sharedEditors; + + private Map customEditorCache; + + + //--------------------------------------------------------------------- + // Management of default editors + //--------------------------------------------------------------------- + + /** + * Activate the default editors for this registry instance, + * allowing for lazily registering default editors when needed. + */ + protected void registerDefaultEditors() { + this.defaultEditorsActive = true; + } + + /** + * Activate config value editors which are only intended for configuration purposes, + * such as {@link org.springframework.beans.propertyeditors.StringArrayPropertyEditor}. + *

    Those editors are not registered by default simply because they are in + * general inappropriate for data binding purposes. Of course, you may register + * them individually in any case, through {@link #registerCustomEditor}. + */ + public void useConfigValueEditors() { + this.configValueEditorsActive = true; + } + + /** + * Retrieve the default editor for the given property type, if any. + *

    Lazily registers the default editors, if they are active. + * @param requiredType type of the property + * @return the default editor, or null if none found + * @see #registerDefaultEditors + */ + public PropertyEditor getDefaultEditor(Class requiredType) { + if (!this.defaultEditorsActive) { + return null; + } + if (this.defaultEditors == null) { + doRegisterDefaultEditors(); + } + return (PropertyEditor) this.defaultEditors.get(requiredType); + } + + /** + * Actually register the default editors for this registry instance. + * @see org.springframework.beans.propertyeditors.ByteArrayPropertyEditor + * @see org.springframework.beans.propertyeditors.ClassEditor + * @see org.springframework.beans.propertyeditors.CharacterEditor + * @see org.springframework.beans.propertyeditors.CustomBooleanEditor + * @see org.springframework.beans.propertyeditors.CustomNumberEditor + * @see org.springframework.beans.propertyeditors.CustomCollectionEditor + * @see org.springframework.beans.propertyeditors.CustomMapEditor + * @see org.springframework.beans.propertyeditors.FileEditor + * @see org.springframework.beans.propertyeditors.InputStreamEditor + * @see org.springframework.jndi.JndiTemplateEditor + * @see org.springframework.beans.propertyeditors.LocaleEditor + * @see org.springframework.beans.propertyeditors.PropertiesEditor + * @see org.springframework.beans.PropertyValuesEditor + * @see org.springframework.core.io.support.ResourceArrayPropertyEditor + * @see org.springframework.core.io.ResourceEditor + * @see org.springframework.transaction.interceptor.TransactionAttributeEditor + * @see org.springframework.transaction.interceptor.TransactionAttributeSourceEditor + * @see org.springframework.beans.propertyeditors.URLEditor + */ + private void doRegisterDefaultEditors() { + this.defaultEditors = new HashMap(64); + + // Simple editors, without parameterization capabilities. + // The JDK does not contain a default editor for any of these target types. + this.defaultEditors.put(Charset.class, new CharsetEditor()); + this.defaultEditors.put(Class.class, new ClassEditor()); + this.defaultEditors.put(Class[].class, new ClassArrayEditor()); + this.defaultEditors.put(File.class, new FileEditor()); + this.defaultEditors.put(InputStream.class, new InputStreamEditor()); + this.defaultEditors.put(Locale.class, new LocaleEditor()); + this.defaultEditors.put(Pattern.class, new PatternEditor()); + this.defaultEditors.put(Properties.class, new PropertiesEditor()); + this.defaultEditors.put(Resource[].class, new ResourceArrayPropertyEditor()); + this.defaultEditors.put(URI.class, new URIEditor()); + this.defaultEditors.put(URL.class, new URLEditor()); + + // Default instances of collection editors. + // Can be overridden by registering custom instances of those as custom editors. + this.defaultEditors.put(Collection.class, new CustomCollectionEditor(Collection.class)); + this.defaultEditors.put(Set.class, new CustomCollectionEditor(Set.class)); + this.defaultEditors.put(SortedSet.class, new CustomCollectionEditor(SortedSet.class)); + this.defaultEditors.put(List.class, new CustomCollectionEditor(List.class)); + this.defaultEditors.put(SortedMap.class, new CustomMapEditor(SortedMap.class)); + + // Default editors for primitive arrays. + this.defaultEditors.put(byte[].class, new ByteArrayPropertyEditor()); + this.defaultEditors.put(char[].class, new CharArrayPropertyEditor()); + + // The JDK does not contain a default editor for char! + this.defaultEditors.put(char.class, new CharacterEditor(false)); + this.defaultEditors.put(Character.class, new CharacterEditor(true)); + + // Spring's CustomBooleanEditor accepts more flag values than the JDK's default editor. + this.defaultEditors.put(boolean.class, new CustomBooleanEditor(false)); + this.defaultEditors.put(Boolean.class, new CustomBooleanEditor(true)); + + // The JDK does not contain default editors for number wrapper types! + // Override JDK primitive number editors with our own CustomNumberEditor. + this.defaultEditors.put(byte.class, new CustomNumberEditor(Byte.class, false)); + this.defaultEditors.put(Byte.class, new CustomNumberEditor(Byte.class, true)); + this.defaultEditors.put(short.class, new CustomNumberEditor(Short.class, false)); + this.defaultEditors.put(Short.class, new CustomNumberEditor(Short.class, true)); + this.defaultEditors.put(int.class, new CustomNumberEditor(Integer.class, false)); + this.defaultEditors.put(Integer.class, new CustomNumberEditor(Integer.class, true)); + this.defaultEditors.put(long.class, new CustomNumberEditor(Long.class, false)); + this.defaultEditors.put(Long.class, new CustomNumberEditor(Long.class, true)); + this.defaultEditors.put(float.class, new CustomNumberEditor(Float.class, false)); + this.defaultEditors.put(Float.class, new CustomNumberEditor(Float.class, true)); + this.defaultEditors.put(double.class, new CustomNumberEditor(Double.class, false)); + this.defaultEditors.put(Double.class, new CustomNumberEditor(Double.class, true)); + this.defaultEditors.put(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, true)); + this.defaultEditors.put(BigInteger.class, new CustomNumberEditor(BigInteger.class, true)); + + // Only register config value editors if explicitly requested. + if (this.configValueEditorsActive) { + StringArrayPropertyEditor sae = new StringArrayPropertyEditor(); + this.defaultEditors.put(String[].class, sae); + this.defaultEditors.put(short[].class, sae); + this.defaultEditors.put(int[].class, sae); + this.defaultEditors.put(long[].class, sae); + } + } + + /** + * Copy the default editors registered in this instance to the given target registry. + * @param target the target registry to copy to + */ + protected void copyDefaultEditorsTo(PropertyEditorRegistrySupport target) { + target.defaultEditors = this.defaultEditors; + target.defaultEditorsActive = this.defaultEditorsActive; + target.configValueEditorsActive = this.configValueEditorsActive; + } + + + //--------------------------------------------------------------------- + // Management of custom editors + //--------------------------------------------------------------------- + + public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { + registerCustomEditor(requiredType, null, propertyEditor); + } + + public void registerCustomEditor(Class requiredType, String propertyPath, PropertyEditor propertyEditor) { + if (requiredType == null && propertyPath == null) { + throw new IllegalArgumentException("Either requiredType or propertyPath is required"); + } + if (this.customEditors == null) { + this.customEditors = new LinkedHashMap(16); + } + if (propertyPath != null) { + this.customEditors.put(propertyPath, new CustomEditorHolder(propertyEditor, requiredType)); + this.propertySpecificEditorsRegistered = true; + } + else { + this.customEditors.put(requiredType, propertyEditor); + this.customEditorCache = null; + } + } + + /** + * Register the given custom property editor for all properties + * of the given type, indicating that the given instance is a + * shared editor that might be used concurrently. + * @param requiredType the type of the property + * @param propertyEditor the shared editor to register + */ + public void registerSharedEditor(Class requiredType, PropertyEditor propertyEditor) { + registerCustomEditor(requiredType, null, propertyEditor); + if (this.sharedEditors == null) { + this.sharedEditors = new HashSet(); + } + this.sharedEditors.add(propertyEditor); + } + + /** + * Check whether the given editor instance is a shared editor, that is, + * whether the given editor instance might be used concurrently. + * @param propertyEditor the editor instance to check + * @return whether the editor is a shared instance + */ + public boolean isSharedEditor(PropertyEditor propertyEditor) { + return (this.sharedEditors != null && this.sharedEditors.contains(propertyEditor)); + } + + public PropertyEditor findCustomEditor(Class requiredType, String propertyPath) { + if (this.customEditors == null) { + return null; + } + Class requiredTypeToUse = requiredType; + if (propertyPath != null) { + if (this.propertySpecificEditorsRegistered) { + // Check property-specific editor first. + PropertyEditor editor = getCustomEditor(propertyPath, requiredType); + if (editor == null) { + List strippedPaths = new LinkedList(); + addStrippedPropertyPaths(strippedPaths, "", propertyPath); + for (Iterator it = strippedPaths.iterator(); it.hasNext() && editor == null;) { + String strippedPath = (String) it.next(); + editor = getCustomEditor(strippedPath, requiredType); + } + } + if (editor != null) { + return editor; + } + } + if (requiredType == null) { + requiredTypeToUse = getPropertyType(propertyPath); + } + } + // No property-specific editor -> check type-specific editor. + return getCustomEditor(requiredTypeToUse); + } + + /** + * Determine whether this registry contains a custom editor + * for the specified array/collection element. + * @param elementType the target type of the element + * (can be null if not known) + * @param propertyPath the property path (typically of the array/collection; + * can be null if not known) + * @return whether a matching custom editor has been found + */ + public boolean hasCustomEditorForElement(Class elementType, String propertyPath) { + if (this.customEditors == null) { + return false; + } + if (propertyPath != null && this.propertySpecificEditorsRegistered) { + for (Iterator it = this.customEditors.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + if (entry.getKey() instanceof String) { + String regPath = (String) entry.getKey(); + if (PropertyAccessorUtils.matchesProperty(regPath, propertyPath)) { + CustomEditorHolder editorHolder = (CustomEditorHolder) entry.getValue(); + if (editorHolder.getPropertyEditor(elementType) != null) { + return true; + } + } + } + } + } + // No property-specific editor -> check type-specific editor. + return (elementType != null && this.customEditors.containsKey(elementType)); + } + + /** + * Determine the property type for the given property path. + *

    Called by {@link #findCustomEditor} if no required type has been specified, + * to be able to find a type-specific editor even if just given a property path. + *

    The default implementation always returns null. + * BeanWrapperImpl overrides this with the standard getPropertyType + * method as defined by the BeanWrapper interface. + * @param propertyPath the property path to determine the type for + * @return the type of the property, or null if not determinable + * @see BeanWrapper#getPropertyType(String) + */ + protected Class getPropertyType(String propertyPath) { + return null; + } + + /** + * Get custom editor that has been registered for the given property. + * @param propertyName the property path to look for + * @param requiredType the type to look for + * @return the custom editor, or null if none specific for this property + */ + private PropertyEditor getCustomEditor(String propertyName, Class requiredType) { + CustomEditorHolder holder = (CustomEditorHolder) this.customEditors.get(propertyName); + return (holder != null ? holder.getPropertyEditor(requiredType) : null); + } + + /** + * Get custom editor for the given type. If no direct match found, + * try custom editor for superclass (which will in any case be able + * to render a value as String via getAsText). + * @param requiredType the type to look for + * @return the custom editor, or null if none found for this type + * @see java.beans.PropertyEditor#getAsText() + */ + private PropertyEditor getCustomEditor(Class requiredType) { + if (requiredType == null) { + return null; + } + // Check directly registered editor for type. + PropertyEditor editor = (PropertyEditor) this.customEditors.get(requiredType); + if (editor == null) { + // Check cached editor for type, registered for superclass or interface. + if (this.customEditorCache != null) { + editor = (PropertyEditor) this.customEditorCache.get(requiredType); + } + if (editor == null) { + // Find editor for superclass or interface. + for (Iterator it = this.customEditors.keySet().iterator(); it.hasNext() && editor == null;) { + Object key = it.next(); + if (key instanceof Class && ((Class) key).isAssignableFrom(requiredType)) { + editor = (PropertyEditor) this.customEditors.get(key); + // Cache editor for search type, to avoid the overhead + // of repeated assignable-from checks. + if (this.customEditorCache == null) { + this.customEditorCache = new HashMap(); + } + this.customEditorCache.put(requiredType, editor); + } + } + } + } + return editor; + } + + /** + * Guess the property type of the specified property from the registered + * custom editors (provided that they were registered for a specific type). + * @param propertyName the name of the property + * @return the property type, or null if not determinable + */ + protected Class guessPropertyTypeFromEditors(String propertyName) { + if (this.customEditors != null) { + CustomEditorHolder editorHolder = (CustomEditorHolder) this.customEditors.get(propertyName); + if (editorHolder == null) { + List strippedPaths = new LinkedList(); + addStrippedPropertyPaths(strippedPaths, "", propertyName); + for (Iterator it = strippedPaths.iterator(); it.hasNext() && editorHolder == null;) { + String strippedName = (String) it.next(); + editorHolder = (CustomEditorHolder) this.customEditors.get(strippedName); + } + } + if (editorHolder != null) { + return editorHolder.getRegisteredType(); + } + } + return null; + } + + /** + * Copy the custom editors registered in this instance to the given target registry. + * @param target the target registry to copy to + * @param nestedProperty the nested property path of the target registry, if any. + * If this is non-null, only editors registered for a path below this nested property + * will be copied. If this is null, all editors will be copied. + */ + protected void copyCustomEditorsTo(PropertyEditorRegistry target, String nestedProperty) { + String actualPropertyName = + (nestedProperty != null ? PropertyAccessorUtils.getPropertyName(nestedProperty) : null); + if (this.customEditors != null) { + for (Iterator it = this.customEditors.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + if (entry.getKey() instanceof Class) { + Class requiredType = (Class) entry.getKey(); + PropertyEditor editor = (PropertyEditor) entry.getValue(); + target.registerCustomEditor(requiredType, editor); + } + else if (entry.getKey() instanceof String) { + String editorPath = (String) entry.getKey(); + CustomEditorHolder editorHolder = (CustomEditorHolder) entry.getValue(); + if (nestedProperty != null) { + int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(editorPath); + if (pos != -1) { + String editorNestedProperty = editorPath.substring(0, pos); + String editorNestedPath = editorPath.substring(pos + 1); + if (editorNestedProperty.equals(nestedProperty) || editorNestedProperty.equals(actualPropertyName)) { + target.registerCustomEditor( + editorHolder.getRegisteredType(), editorNestedPath, editorHolder.getPropertyEditor()); + } + } + } + else { + target.registerCustomEditor( + editorHolder.getRegisteredType(), editorPath, editorHolder.getPropertyEditor()); + } + } + } + } + } + + + /** + * Add property paths with all variations of stripped keys and/or indexes. + * Invokes itself recursively with nested paths. + * @param strippedPaths the result list to add to + * @param nestedPath the current nested path + * @param propertyPath the property path to check for keys/indexes to strip + */ + private void addStrippedPropertyPaths(List strippedPaths, String nestedPath, String propertyPath) { + int startIndex = propertyPath.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR); + if (startIndex != -1) { + int endIndex = propertyPath.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR); + if (endIndex != -1) { + String prefix = propertyPath.substring(0, startIndex); + String key = propertyPath.substring(startIndex, endIndex + 1); + String suffix = propertyPath.substring(endIndex + 1, propertyPath.length()); + // Strip the first key. + strippedPaths.add(nestedPath + prefix + suffix); + // Search for further keys to strip, with the first key stripped. + addStrippedPropertyPaths(strippedPaths, nestedPath + prefix, suffix); + // Search for further keys to strip, with the first key not stripped. + addStrippedPropertyPaths(strippedPaths, nestedPath + prefix + key, suffix); + } + } + } + + + /** + * Holder for a registered custom editor with property name. + * Keeps the PropertyEditor itself plus the type it was registered for. + */ + private static class CustomEditorHolder { + + private final PropertyEditor propertyEditor; + + private final Class registeredType; + + private CustomEditorHolder(PropertyEditor propertyEditor, Class registeredType) { + this.propertyEditor = propertyEditor; + this.registeredType = registeredType; + } + + private PropertyEditor getPropertyEditor() { + return this.propertyEditor; + } + + private Class getRegisteredType() { + return this.registeredType; + } + + private PropertyEditor getPropertyEditor(Class requiredType) { + // Special case: If no required type specified, which usually only happens for + // Collection elements, or required type is not assignable to registered type, + // which usually only happens for generic properties of type Object - + // then return PropertyEditor if not registered for Collection or array type. + // (If not registered for Collection or array, it is assumed to be intended + // for elements.) + if (this.registeredType == null || + (requiredType != null && + (ClassUtils.isAssignable(this.registeredType, requiredType) || + ClassUtils.isAssignable(requiredType, this.registeredType))) || + (requiredType == null && + (!Collection.class.isAssignableFrom(this.registeredType) && !this.registeredType.isArray()))) { + return this.propertyEditor; + } + else { + return null; + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/PropertyMatches.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/PropertyMatches.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/PropertyMatches.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,186 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyDescriptor; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +/** + * Helper class for calculating bean property matches, according to. + * Used by BeanWrapperImpl to suggest alternatives for an invalid property name. + * + * @author Alef Arendsen + * @author Arjen Poutsma + * @author Juergen Hoeller + * @since 2.0 + * @see #forProperty(String, Class) + */ +final class PropertyMatches { + + //--------------------------------------------------------------------- + // Static section + //--------------------------------------------------------------------- + + /** Default maximum property distance: 2 */ + public static final int DEFAULT_MAX_DISTANCE = 2; + + + /** + * Create PropertyMatches for the given bean property. + * @param propertyName the name of the property to find possible matches for + * @param beanClass the bean class to search for matches + */ + public static PropertyMatches forProperty(String propertyName, Class beanClass) { + return forProperty(propertyName, beanClass, DEFAULT_MAX_DISTANCE); + } + + /** + * Create PropertyMatches for the given bean property. + * @param propertyName the name of the property to find possible matches for + * @param beanClass the bean class to search for matches + * @param maxDistance the maximum property distance allowed for matches + */ + public static PropertyMatches forProperty(String propertyName, Class beanClass, int maxDistance) { + return new PropertyMatches(propertyName, beanClass, maxDistance); + } + + + //--------------------------------------------------------------------- + // Instance section + //--------------------------------------------------------------------- + + private final String propertyName; + + private String[] possibleMatches; + + + /** + * Create a new PropertyMatches instance for the given property. + */ + private PropertyMatches(String propertyName, Class beanClass, int maxDistance) { + this.propertyName = propertyName; + this.possibleMatches = calculateMatches(BeanUtils.getPropertyDescriptors(beanClass), maxDistance); + } + + + /** + * Return the calculated possible matches. + */ + public String[] getPossibleMatches() { + return possibleMatches; + } + + /** + * Build an error message for the given invalid property name, + * indicating the possible property matches. + */ + public String buildErrorMessage() { + StringBuffer buf = new StringBuffer(); + buf.append("Bean property '"); + buf.append(this.propertyName); + buf.append("' is not writable or has an invalid setter method. "); + + if (ObjectUtils.isEmpty(this.possibleMatches)) { + buf.append("Does the parameter type of the setter match the return type of the getter?"); + } + else { + buf.append("Did you mean "); + for (int i = 0; i < this.possibleMatches.length; i++) { + buf.append('\''); + buf.append(this.possibleMatches[i]); + if (i < this.possibleMatches.length - 2) { + buf.append("', "); + } + else if (i == this.possibleMatches.length - 2){ + buf.append("', or "); + } + } + buf.append("'?"); + } + return buf.toString(); + } + + + /** + * Generate possible property alternatives for the given property and + * class. Internally uses the getStringDistance method, which + * in turn uses the Levenshtein algorithm to determine the distance between + * two Strings. + * @param propertyDescriptors the JavaBeans property descriptors to search + * @param maxDistance the maximum distance to accept + */ + private String[] calculateMatches(PropertyDescriptor[] propertyDescriptors, int maxDistance) { + List candidates = new ArrayList(); + for (int i = 0; i < propertyDescriptors.length; i++) { + if (propertyDescriptors[i].getWriteMethod() != null) { + String possibleAlternative = propertyDescriptors[i].getName(); + if (calculateStringDistance(this.propertyName, possibleAlternative) <= maxDistance) { + candidates.add(possibleAlternative); + } + } + } + Collections.sort(candidates); + return StringUtils.toStringArray(candidates); + } + + /** + * Calculate the distance between the given two Strings + * according to the Levenshtein algorithm. + * @param s1 the first String + * @param s2 the second String + * @return the distance value + */ + private int calculateStringDistance(String s1, String s2) { + if (s1.length() == 0) { + return s2.length(); + } + if (s2.length() == 0) { + return s1.length(); + } + int d[][] = new int[s1.length() + 1][s2.length() + 1]; + + for (int i = 0; i <= s1.length(); i++) { + d[i][0] = i; + } + for (int j = 0; j <= s2.length(); j++) { + d[0][j] = j; + } + + for (int i = 1; i <= s1.length(); i++) { + char s_i = s1.charAt(i - 1); + for (int j = 1; j <= s2.length(); j++) { + int cost; + char t_j = s2.charAt(j - 1); + if (s_i == t_j) { + cost = 0; + } else { + cost = 1; + } + d[i][j] = Math.min(Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1), + d[i - 1][j - 1] + cost); + } + } + + return d[s1.length()][s2.length()]; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/PropertyValue.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/PropertyValue.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/PropertyValue.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,184 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyDescriptor; +import java.io.Serializable; + +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + +/** + * Object to hold information and value for an individual bean property. + * Using an object here, rather than just storing all properties in + * a map keyed by property name, allows for more flexibility, and the + * ability to handle indexed properties etc in an optimized way. + * + *

    Note that the value doesn't need to be the final required type: + * A {@link BeanWrapper} implementation should handle any necessary conversion, + * as this object doesn't know anything about the objects it will be applied to. + * + * @author Rod Johnson + * @author Rob Harrop + * @author Juergen Hoeller + * @since 13 May 2001 + * @see PropertyValues + * @see BeanWrapper + */ +public class PropertyValue extends BeanMetadataAttributeAccessor implements Serializable { + + private final String name; + + private final Object value; + + private Object source; + + private boolean converted = false; + + private Object convertedValue; + + /** Package-visible field that indicates whether conversion is necessary */ + volatile Boolean conversionNecessary; + + /** Package-visible field for caching the resolved property path tokens */ + volatile Object resolvedTokens; + + /** Package-visible field for caching the resolved PropertyDescriptor */ + volatile PropertyDescriptor resolvedDescriptor; + + + /** + * Create a new PropertyValue instance. + * @param name the name of the property (never null) + * @param value the value of the property (possibly before type conversion) + */ + public PropertyValue(String name, Object value) { + this.name = name; + this.value = value; + } + + /** + * Copy constructor. + * @param original the PropertyValue to copy (never null) + */ + public PropertyValue(PropertyValue original) { + Assert.notNull(original, "Original must not be null"); + this.name = original.getName(); + this.value = original.getValue(); + this.source = original.getSource(); + this.conversionNecessary = original.conversionNecessary; + this.resolvedTokens = original.resolvedTokens; + this.resolvedDescriptor = original.resolvedDescriptor; + copyAttributesFrom(original); + } + + /** + * Constructor that exposes a new value for an original value holder. + * The original holder will be exposed as source of the new holder. + * @param original the PropertyValue to link to (never null) + * @param newValue the new value to apply + */ + public PropertyValue(PropertyValue original, Object newValue) { + Assert.notNull(original, "Original must not be null"); + this.name = original.getName(); + this.value = newValue; + this.source = original; + this.conversionNecessary = original.conversionNecessary; + this.resolvedTokens = original.resolvedTokens; + this.resolvedDescriptor = original.resolvedDescriptor; + copyAttributesFrom(original); + } + + + /** + * Return the name of the property. + */ + public String getName() { + return this.name; + } + + /** + * Return the value of the property. + *

    Note that type conversion will not have occurred here. + * It is the responsibility of the BeanWrapper implementation to + * perform type conversion. + */ + public Object getValue() { + return this.value; + } + + /** + * Return the original PropertyValue instance for this value holder. + * @return the original PropertyValue (either a source of this + * value holder or this value holder itself). + */ + public PropertyValue getOriginalPropertyValue() { + PropertyValue original = this; + while (original.source instanceof PropertyValue && original.source != original) { + original = (PropertyValue) original.source; + } + return original; + } + + /** + * Return whether this holder contains a converted value already (true), + * or whether the value still needs to be converted (false). + */ + public synchronized boolean isConverted() { + return this.converted; + } + + /** + * Set the converted value of the constructor argument, + * after processed type conversion. + */ + public synchronized void setConvertedValue(Object value) { + this.converted = true; + this.convertedValue = value; + } + + /** + * Return the converted value of the constructor argument, + * after processed type conversion. + */ + public synchronized Object getConvertedValue() { + return this.convertedValue; + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof PropertyValue)) { + return false; + } + PropertyValue otherPv = (PropertyValue) other; + return (this.name.equals(otherPv.name) && + ObjectUtils.nullSafeEquals(this.value, otherPv.value) && + ObjectUtils.nullSafeEquals(this.source, otherPv.source)); + } + + public int hashCode() { + return this.name.hashCode() * 29 + ObjectUtils.nullSafeHashCode(this.value); + } + + public String toString() { + return "bean property '" + this.name + "'"; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/PropertyValues.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/PropertyValues.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/PropertyValues.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +/** + * Holder containing one or more {@link PropertyValue} objects, + * typically comprising one update for a specific target bean. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 13 May 2001 + * @see PropertyValue + */ +public interface PropertyValues { + + /** + * Return an array of the PropertyValue objects held in this object. + */ + PropertyValue[] getPropertyValues(); + + /** + * Return the property value with the given name, if any. + * @param propertyName the name to search for + * @return the property value, or null + */ + PropertyValue getPropertyValue(String propertyName); + + /** + * Is there a property value (or other processing entry) for this property? + * @param propertyName the name of the property we're interested in + * @return whether there is a property value for this property + */ + boolean contains(String propertyName); + + /** + * Does this holder not contain any PropertyValue objects at all? + */ + boolean isEmpty(); + + /** + * Return the changes since the previous PropertyValues. + * Subclasses should also override equals. + * @param old old property values + * @return PropertyValues updated or new properties. + * Return empty PropertyValues if there are no changes. + * @see java.lang.Object#equals + */ + PropertyValues changesSince(PropertyValues old); + +} Index: 3rdParty_sources/spring/org/springframework/beans/PropertyValuesEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/PropertyValuesEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/PropertyValuesEditor.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyEditorSupport; +import java.util.Properties; + +import org.springframework.beans.propertyeditors.PropertiesEditor; + +/** + * {@link java.beans.PropertyEditor Editor} for a {@link PropertyValues} object. + * + *

    The required format is defined in the {@link java.util.Properties} + * documentation. Each property must be on a new line. + * + *

    The present implementation relies on a + * {@link org.springframework.beans.propertyeditors.PropertiesEditor} + * underneath. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public class PropertyValuesEditor extends PropertyEditorSupport { + + private final PropertiesEditor propertiesEditor = new PropertiesEditor(); + + public void setAsText(String text) throws IllegalArgumentException { + this.propertiesEditor.setAsText(text); + Properties props = (Properties) this.propertiesEditor.getValue(); + setValue(new MutablePropertyValues(props)); + } + +} + Index: 3rdParty_sources/spring/org/springframework/beans/SimpleTypeConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/SimpleTypeConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/SimpleTypeConverter.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import org.springframework.core.MethodParameter; + +/** + * Simple implementation of the TypeConverter interface that does not operate + * on any specific target object. This is an alternative to using a full-blown + * BeanWrapperImpl instance for arbitrary type conversion needs. + * + * @author Juergen Hoeller + * @since 2.0 + * @see BeanWrapperImpl + */ +public class SimpleTypeConverter extends PropertyEditorRegistrySupport implements TypeConverter { + + private final TypeConverterDelegate typeConverterDelegate = new TypeConverterDelegate(this); + + + public SimpleTypeConverter() { + registerDefaultEditors(); + } + + + public Object convertIfNecessary(Object value, Class requiredType) throws TypeMismatchException { + return convertIfNecessary(value, requiredType, null); + } + + public Object convertIfNecessary( + Object value, Class requiredType, MethodParameter methodParam) throws TypeMismatchException { + try { + return this.typeConverterDelegate.convertIfNecessary(value, requiredType, methodParam); + } + catch (IllegalArgumentException ex) { + throw new TypeMismatchException(value, requiredType, ex); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/TypeConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/TypeConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/TypeConverter.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import org.springframework.core.MethodParameter; + +/** + * Interface that defines type conversion methods. Typically (but not necessarily) + * implemented in conjunction with the PropertyEditorRegistry interface. + * + * @author Juergen Hoeller + * @since 2.0 + * @see PropertyEditorRegistry + * @see SimpleTypeConverter + * @see BeanWrapperImpl + */ +public interface TypeConverter { + + /** + * Convert the value to the required type (if necessary from a String). + *

    Conversions from String to any type will typically use the setAsText + * method of the PropertyEditor class. Note that a PropertyEditor must be registered + * for the given class for this to work; this is a standard JavaBeans API. + * A number of PropertyEditors are automatically registered. + * @param value the value to convert + * @param requiredType the type we must convert to + * (or null if not known, for example in case of a collection element) + * @return the new value, possibly the result of type conversion + * @throws TypeMismatchException if type conversion failed + * @see java.beans.PropertyEditor#setAsText(String) + * @see java.beans.PropertyEditor#getValue() + */ + Object convertIfNecessary(Object value, Class requiredType) throws TypeMismatchException; + + /** + * Convert the value to the required type (if necessary from a String). + *

    Conversions from String to any type will typically use the setAsText + * method of the PropertyEditor class. Note that a PropertyEditor must be registered + * for the given class for this to work; this is a standard JavaBeans API. + * A number of PropertyEditors are automatically registered. + * @param value the value to convert + * @param requiredType the type we must convert to + * (or null if not known, for example in case of a collection element) + * @param methodParam the method parameter that is the target of the conversion + * (for analysis of generic types; may be null) + * @return the new value, possibly the result of type conversion + * @throws TypeMismatchException if type conversion failed + * @see java.beans.PropertyEditor#setAsText(String) + * @see java.beans.PropertyEditor#getValue() + */ + Object convertIfNecessary(Object value, Class requiredType, MethodParameter methodParam) + throws TypeMismatchException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/TypeConverterDelegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/TypeConverterDelegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/TypeConverterDelegate.java 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,542 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyDescriptor; +import java.beans.PropertyEditor; +import java.beans.PropertyEditorManager; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.Map; +import java.util.WeakHashMap; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.core.CollectionFactory; +import org.springframework.core.GenericCollectionTypeResolver; +import org.springframework.core.JdkVersion; +import org.springframework.core.MethodParameter; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +/** + * Internal helper class for converting property values to target types. + * + *

    Works on a given {@link PropertyEditorRegistrySupport} instance. + * Used as a delegate by {@link BeanWrapperImpl} and {@link SimpleTypeConverter}. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @since 2.0 + * @see BeanWrapperImpl + * @see SimpleTypeConverter + */ +class TypeConverterDelegate { + + private static final Log logger = LogFactory.getLog(TypeConverterDelegate.class); + + private static final Map unknownEditorTypes = Collections.synchronizedMap(new WeakHashMap()); + + private final PropertyEditorRegistrySupport propertyEditorRegistry; + + private final Object targetObject; + + + /** + * Create a new TypeConverterDelegate for the given editor registry. + * @param propertyEditorRegistry the editor registry to use + */ + public TypeConverterDelegate(PropertyEditorRegistrySupport propertyEditorRegistry) { + this(propertyEditorRegistry, null); + } + + /** + * Create a new TypeConverterDelegate for the given editor registry and bean instance. + * @param propertyEditorRegistry the editor registry to use + * @param targetObject the target object to work on (as context that can be passed to editors) + */ + public TypeConverterDelegate(PropertyEditorRegistrySupport propertyEditorRegistry, Object targetObject) { + this.propertyEditorRegistry = propertyEditorRegistry; + this.targetObject = targetObject; + } + + + /** + * Convert the value to the specified required type. + * @param newValue the proposed new value + * @param requiredType the type we must convert to + * (or null if not known, for example in case of a collection element) + * @return the new value, possibly the result of type conversion + * @throws IllegalArgumentException if type conversion failed + */ + public Object convertIfNecessary(Object newValue, Class requiredType) throws IllegalArgumentException { + return convertIfNecessary(null, null, newValue, requiredType, null, null); + } + + /** + * Convert the value to the specified required type. + * @param newValue the proposed new value + * @param requiredType the type we must convert to + * (or null if not known, for example in case of a collection element) + * @param methodParam the method parameter that is the target of the conversion + * (may be null) + * @return the new value, possibly the result of type conversion + * @throws IllegalArgumentException if type conversion failed + */ + public Object convertIfNecessary(Object newValue, Class requiredType, MethodParameter methodParam) + throws IllegalArgumentException { + + return convertIfNecessary(null, null, newValue, requiredType, null, methodParam); + } + + /** + * Convert the value to the required type for the specified property. + * @param propertyName name of the property + * @param oldValue the previous value, if available (may be null) + * @param newValue the proposed new value + * @param requiredType the type we must convert to + * (or null if not known, for example in case of a collection element) + * @return the new value, possibly the result of type conversion + * @throws IllegalArgumentException if type conversion failed + */ + public Object convertIfNecessary( + String propertyName, Object oldValue, Object newValue, Class requiredType) + throws IllegalArgumentException { + + return convertIfNecessary(propertyName, oldValue, newValue, requiredType, null, null); + } + + /** + * Convert the value to the required type for the specified property. + * @param oldValue the previous value, if available (may be null) + * @param newValue the proposed new value + * @param descriptor the JavaBeans descriptor for the property + * @return the new value, possibly the result of type conversion + * @throws IllegalArgumentException if type conversion failed + */ + public Object convertIfNecessary(Object oldValue, Object newValue, PropertyDescriptor descriptor) + throws IllegalArgumentException { + + return convertIfNecessary( + descriptor.getName(), oldValue, newValue, descriptor.getPropertyType(), descriptor, + BeanUtils.getWriteMethodParameter(descriptor)); + } + + + /** + * Convert the value to the required type (if necessary from a String), + * for the specified property. + * @param propertyName name of the property + * @param oldValue the previous value, if available (may be null) + * @param newValue the proposed new value + * @param requiredType the type we must convert to + * (or null if not known, for example in case of a collection element) + * @param descriptor the JavaBeans descriptor for the property + * @param methodParam the method parameter that is the target of the conversion + * (may be null) + * @return the new value, possibly the result of type conversion + * @throws IllegalArgumentException if type conversion failed + */ + protected Object convertIfNecessary( + String propertyName, Object oldValue, Object newValue, Class requiredType, + PropertyDescriptor descriptor, MethodParameter methodParam) + throws IllegalArgumentException { + + Object convertedValue = newValue; + + // Custom editor for this type? + PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName); + + // Value not of required type? + if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) { + if (editor == null) { + editor = findDefaultEditor(requiredType, descriptor); + } + convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor); + } + + if (requiredType != null) { + // Try to apply some standard type conversion rules if appropriate. + + if (convertedValue != null) { + if (String.class.equals(requiredType) && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) { + // We can stringify any primitive value... + return convertedValue.toString(); + } + else if (requiredType.isArray()) { + // Array required -> apply appropriate conversion of elements. + return convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType()); + } + else if (convertedValue instanceof Collection && CollectionFactory.isApproximableCollectionType(requiredType)) { + // Convert elements to target type, if determined. + convertedValue = convertToTypedCollection((Collection) convertedValue, propertyName, methodParam); + } + else if (convertedValue instanceof Map && CollectionFactory.isApproximableMapType(requiredType)) { + // Convert keys and values to respective target type, if determined. + convertedValue = convertToTypedMap((Map) convertedValue, propertyName, methodParam); + } + else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) { + String strValue = ((String) convertedValue).trim(); + if (JdkVersion.isAtLeastJava15() && requiredType.isEnum() && "".equals(strValue)) { + // It's an empty enum identifier: reset the enum value to null. + return null; + } + // Try field lookup as fallback: for JDK 1.5 enum or custom enum + // with values defined as static fields. Resulting value still needs + // to be checked, hence we don't return it right away. + try { + Field enumField = requiredType.getField(strValue); + convertedValue = enumField.get(null); + } + catch (Throwable ex) { + if (logger.isTraceEnabled()) { + logger.trace("Field [" + convertedValue + "] isn't an enum value", ex); + } + } + } + } + + if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) { + // Definitely doesn't match: throw IllegalArgumentException. + StringBuffer msg = new StringBuffer(); + msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue)); + msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]"); + if (propertyName != null) { + msg.append(" for property '" + propertyName + "'"); + } + if (editor != null) { + msg.append(": PropertyEditor [" + editor.getClass().getName() + "] returned inappropriate value"); + } + else { + msg.append(": no matching editors or conversion strategy found"); + } + throw new IllegalArgumentException(msg.toString()); + } + } + + return convertedValue; + } + + /** + * Find a default editor for the given type. + * @param requiredType the type to find an editor for + * @param descriptor the JavaBeans descriptor for the property + * @return the corresponding editor, or null if none + */ + protected PropertyEditor findDefaultEditor(Class requiredType, PropertyDescriptor descriptor) { + PropertyEditor editor = null; + if (descriptor != null) { + if (JdkVersion.isAtLeastJava15()) { + editor = descriptor.createPropertyEditor(this.targetObject); + } + else { + Class editorClass = descriptor.getPropertyEditorClass(); + if (editorClass != null) { + editor = (PropertyEditor) BeanUtils.instantiateClass(editorClass); + } + } + } + if (editor == null && requiredType != null) { + // No custom editor -> check BeanWrapperImpl's default editors. + editor = (PropertyEditor) this.propertyEditorRegistry.getDefaultEditor(requiredType); + if (editor == null && !String.class.equals(requiredType)) { + // No BeanWrapper default editor -> check standard JavaBean editor. + editor = BeanUtils.findEditorByConvention(requiredType); + if (editor == null && !unknownEditorTypes.containsKey(requiredType)) { + // Deprecated global PropertyEditorManager fallback... + editor = PropertyEditorManager.findEditor(requiredType); + if (editor == null) { + // Regular case as of Spring 2.5 + unknownEditorTypes.put(requiredType, Boolean.TRUE); + } + else { + logger.warn("PropertyEditor [" + editor.getClass().getName() + + "] found through deprecated global PropertyEditorManager fallback - " + + "consider using a more isolated form of registration, e.g. on the BeanWrapper/BeanFactory!"); + } + } + } + } + return editor; + } + + /** + * Convert the value to the required type (if necessary from a String), + * using the given property editor. + * @param oldValue the previous value, if available (may be null) + * @param newValue the proposed new value + * @param requiredType the type we must convert to + * (or null if not known, for example in case of a collection element) + * @param editor the PropertyEditor to use + * @return the new value, possibly the result of type conversion + * @throws IllegalArgumentException if type conversion failed + */ + protected Object doConvertValue(Object oldValue, Object newValue, Class requiredType, PropertyEditor editor) { + Object convertedValue = newValue; + boolean sharedEditor = false; + + if (editor != null) { + sharedEditor = this.propertyEditorRegistry.isSharedEditor(editor); + } + + if (editor != null && !(convertedValue instanceof String)) { + // Not a String -> use PropertyEditor's setValue. + // With standard PropertyEditors, this will return the very same object; + // we just want to allow special PropertyEditors to override setValue + // for type conversion from non-String values to the required type. + try { + Object newConvertedValue = null; + if (sharedEditor) { + // Synchronized access to shared editor instance. + synchronized (editor) { + editor.setValue(convertedValue); + newConvertedValue = editor.getValue(); + } + } + else { + // Unsynchronized access to non-shared editor instance. + editor.setValue(convertedValue); + newConvertedValue = editor.getValue(); + } + if (newConvertedValue != convertedValue) { + convertedValue = newConvertedValue; + // Reset PropertyEditor: It already did a proper conversion. + // Don't use it again for a setAsText call. + editor = null; + } + } + catch (Exception ex) { + if (logger.isDebugEnabled()) { + logger.debug("PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call", ex); + } + // Swallow and proceed. + } + } + + if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) { + // Convert String array to a comma-separated String. + // Only applies if no PropertyEditor converted the String array before. + // The CSV String will be passed into a PropertyEditor's setAsText method, if any. + if (logger.isTraceEnabled()) { + logger.trace("Converting String array to comma-delimited String [" + convertedValue + "]"); + } + convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue); + } + + if (editor != null && convertedValue instanceof String) { + // Use PropertyEditor's setAsText in case of a String value. + if (logger.isTraceEnabled()) { + logger.trace("Converting String to [" + requiredType + "] using property editor [" + editor + "]"); + } + String newTextValue = (String) convertedValue; + if (sharedEditor) { + // Synchronized access to shared editor instance. + synchronized (editor) { + return doConvertTextValue(oldValue, newTextValue, editor); + } + } + else { + // Unsynchronized access to non-shared editor instance. + return doConvertTextValue(oldValue, newTextValue, editor); + } + } + + return convertedValue; + } + + /** + * Convert the given text value using the given property editor. + * @param oldValue the previous value, if available (may be null) + * @param newTextValue the proposed text value + * @param editor the PropertyEditor to use + * @return the converted value + */ + protected Object doConvertTextValue(Object oldValue, String newTextValue, PropertyEditor editor) { + try { + editor.setValue(oldValue); + } + catch (Exception ex) { + if (logger.isDebugEnabled()) { + logger.debug("PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call", ex); + } + // Swallow and proceed. + } + editor.setAsText(newTextValue); + return editor.getValue(); + } + + protected Object convertToTypedArray(Object input, String propertyName, Class componentType) { + if (input instanceof Collection) { + // Convert Collection elements to array elements. + Collection coll = (Collection) input; + Object result = Array.newInstance(componentType, coll.size()); + int i = 0; + for (Iterator it = coll.iterator(); it.hasNext(); i++) { + Object value = convertIfNecessary( + buildIndexedPropertyName(propertyName, i), null, it.next(), componentType); + Array.set(result, i, value); + } + return result; + } + else if (input.getClass().isArray()) { + // Convert array elements, if necessary. + if (componentType.equals(input.getClass().getComponentType()) && + !this.propertyEditorRegistry.hasCustomEditorForElement(componentType, propertyName)) { + return input; + } + int arrayLength = Array.getLength(input); + Object result = Array.newInstance(componentType, arrayLength); + for (int i = 0; i < arrayLength; i++) { + Object value = convertIfNecessary( + buildIndexedPropertyName(propertyName, i), null, Array.get(input, i), componentType); + Array.set(result, i, value); + } + return result; + } + else { + // A plain value: convert it to an array with a single component. + Object result = Array.newInstance(componentType, 1); + Object value = convertIfNecessary( + buildIndexedPropertyName(propertyName, 0), null, input, componentType); + Array.set(result, 0, value); + return result; + } + } + + protected Collection convertToTypedCollection( + Collection original, String propertyName, MethodParameter methodParam) { + + Class elementType = null; + if (methodParam != null && JdkVersion.isAtLeastJava15()) { + elementType = GenericCollectionTypeResolver.getCollectionParameterType(methodParam); + } + if (elementType == null && + !this.propertyEditorRegistry.hasCustomEditorForElement(null, propertyName)) { + return original; + } + + Collection convertedCopy = null; + Iterator it = null; + try { + it = original.iterator(); + if (it == null) { + if (logger.isDebugEnabled()) { + logger.debug("Collection of type [" + original.getClass().getName() + + "] returned null Iterator - injecting original Collection as-is"); + } + return original; + } + convertedCopy = CollectionFactory.createApproximateCollection(original, original.size()); + } + catch (Throwable ex) { + if (logger.isDebugEnabled()) { + logger.debug("Cannot access Collection of type [" + original.getClass().getName() + + "] - injecting original Collection as-is", ex); + } + return original; + } + boolean actuallyConverted = false; + int i = 0; + for (; it.hasNext(); i++) { + Object element = it.next(); + String indexedPropertyName = buildIndexedPropertyName(propertyName, i); + if (methodParam != null) { + methodParam.increaseNestingLevel(); + } + Object convertedElement = + convertIfNecessary(indexedPropertyName, null, element, elementType, null, methodParam); + if (methodParam != null) { + methodParam.decreaseNestingLevel(); + } + convertedCopy.add(convertedElement); + actuallyConverted = actuallyConverted || (element != convertedElement); + } + return (actuallyConverted ? convertedCopy : original); + } + + protected Map convertToTypedMap(Map original, String propertyName, MethodParameter methodParam) { + Class keyType = null; + Class valueType = null; + if (methodParam != null && JdkVersion.isAtLeastJava15()) { + keyType = GenericCollectionTypeResolver.getMapKeyParameterType(methodParam); + valueType = GenericCollectionTypeResolver.getMapValueParameterType(methodParam); + } + if (keyType == null && valueType == null && + !this.propertyEditorRegistry.hasCustomEditorForElement(null, propertyName)) { + return original; + } + + Map convertedCopy = null; + Iterator it = null; + try { + it = original.entrySet().iterator(); + if (it == null) { + if (logger.isDebugEnabled()) { + logger.debug("Map of type [" + original.getClass().getName() + + "] returned null Iterator - injecting original Map as-is"); + } + } + convertedCopy = CollectionFactory.createApproximateMap(original, original.size()); + } + catch (Throwable ex) { + if (logger.isDebugEnabled()) { + logger.debug("Cannot access Map of type [" + original.getClass().getName() + + "] - injecting original Map as-is", ex); + } + return original; + } + boolean actuallyConverted = false; + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + Object key = entry.getKey(); + Object value = entry.getValue(); + String keyedPropertyName = buildKeyedPropertyName(propertyName, key); + if (methodParam != null) { + methodParam.increaseNestingLevel(); + methodParam.setTypeIndexForCurrentLevel(0); + } + Object convertedKey = convertIfNecessary(keyedPropertyName, null, key, keyType, null, methodParam); + if (methodParam != null) { + methodParam.setTypeIndexForCurrentLevel(1); + } + Object convertedValue = convertIfNecessary(keyedPropertyName, null, value, valueType, null, methodParam); + if (methodParam != null) { + methodParam.decreaseNestingLevel(); + } + convertedCopy.put(convertedKey, convertedValue); + actuallyConverted = actuallyConverted || (key != convertedKey) || (value != convertedValue); + } + return (actuallyConverted ? convertedCopy : original); + } + + private String buildIndexedPropertyName(String propertyName, int index) { + return (propertyName != null ? + propertyName + PropertyAccessor.PROPERTY_KEY_PREFIX + index + PropertyAccessor.PROPERTY_KEY_SUFFIX : + null); + } + + private String buildKeyedPropertyName(String propertyName, Object key) { + return (propertyName != null ? + propertyName + PropertyAccessor.PROPERTY_KEY_PREFIX + key + PropertyAccessor.PROPERTY_KEY_SUFFIX : + null); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/TypeMismatchException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/TypeMismatchException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/TypeMismatchException.java 17 Aug 2012 15:11:39 -0000 1.1 @@ -0,0 +1,112 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans; + +import java.beans.PropertyChangeEvent; + +import org.springframework.util.ClassUtils; + +/** + * Exception thrown on a type mismatch when trying to set a bean property. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public class TypeMismatchException extends PropertyAccessException { + + /** + * Error code that a type mismatch error will be registered with. + */ + public static final String ERROR_CODE = "typeMismatch"; + + + private transient Object value; + + private Class requiredType; + + + /** + * Create a new TypeMismatchException. + * @param propertyChangeEvent the PropertyChangeEvent that resulted in the problem + * @param requiredType the required target type + */ + public TypeMismatchException(PropertyChangeEvent propertyChangeEvent, Class requiredType) { + this(propertyChangeEvent, requiredType, null); + } + + /** + * Create a new TypeMismatchException. + * @param propertyChangeEvent the PropertyChangeEvent that resulted in the problem + * @param requiredType the required target type (or null if not known) + * @param cause the root cause (may be null) + */ + public TypeMismatchException(PropertyChangeEvent propertyChangeEvent, Class requiredType, Throwable cause) { + super(propertyChangeEvent, + "Failed to convert property value of type [" + + ClassUtils.getDescriptiveType(propertyChangeEvent.getNewValue()) + "]" + + (requiredType != null ? + " to required type [" + ClassUtils.getQualifiedName(requiredType) + "]" : "") + + (propertyChangeEvent.getPropertyName() != null ? + " for property '" + propertyChangeEvent.getPropertyName() + "'" : ""), + cause); + this.value = propertyChangeEvent.getNewValue(); + this.requiredType = requiredType; + } + + /** + * Create a new TypeMismatchException without PropertyChangeEvent. + * @param value the offending value that couldn't be converted (may be null) + * @param requiredType the required target type (or null if not known) + */ + public TypeMismatchException(Object value, Class requiredType) { + this(value, requiredType, null); + } + + /** + * Create a new TypeMismatchException without PropertyChangeEvent. + * @param value the offending value that couldn't be converted (may be null) + * @param requiredType the required target type (or null if not known) + * @param cause the root cause (may be null) + */ + public TypeMismatchException(Object value, Class requiredType, Throwable cause) { + super("Failed to convert value of type [" + ClassUtils.getDescriptiveType(value) + "]" + + (requiredType != null ? " to required type [" + ClassUtils.getQualifiedName(requiredType) + "]" : ""), + cause); + this.value = value; + this.requiredType = requiredType; + } + + + /** + * Return the offending value (may be null) + */ + public Object getValue() { + return this.value; + } + + /** + * Return the required target type, if any. + */ + public Class getRequiredType() { + return this.requiredType; + } + + public String getErrorCode() { + return ERROR_CODE; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/package.html 17 Aug 2012 15:11:38 -0000 1.1 @@ -0,0 +1,15 @@ + + + +This package contains interfaces and classes for manipulating Java beans. +It is used by most other Spring packages. + +

    A BeanWrapper object may be used to set and get bean properties, +singly or in bulk. + +

    The classes in this package are discussed in Chapter 11 of +Expert One-On-One J2EE Design and Development +by Rod Johnson (Wrox, 2002). + + + Index: 3rdParty_sources/spring/org/springframework/beans/annotation/AnnotationBeanUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/annotation/AnnotationBeanUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/annotation/AnnotationBeanUtils.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.annotation; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import org.springframework.beans.BeanWrapper; +import org.springframework.beans.PropertyAccessorFactory; +import org.springframework.util.ReflectionUtils; + +/** + * General utility methods for working with annotations in JavaBeans style. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public abstract class AnnotationBeanUtils { + + /** + * Copy the properties of the supplied {@link Annotation} to the supplied target bean. + * Any properties defined in excludedProperties will not be copied. + * @see org.springframework.beans.BeanWrapper + */ + public static void copyPropertiesToBean(Annotation ann, Object bean, String... excludedProperties) { + Set excluded = new HashSet(Arrays.asList(excludedProperties)); + Method[] annotationProperties = ann.annotationType().getDeclaredMethods(); + BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean); + for (Method annotationProperty : annotationProperties) { + String propertyName = annotationProperty.getName(); + if ((!excluded.contains(propertyName)) && bw.isWritableProperty(propertyName)) { + Object value = ReflectionUtils.invokeMethod(annotationProperty, ann); + bw.setPropertyValue(propertyName, value); + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/annotation/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/annotation/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/annotation/package.html 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,7 @@ + + + +Support package for beans-style handling of Java 5 annotations. + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanClassLoaderAware.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanClassLoaderAware.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanClassLoaderAware.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +/** + * Callback that allows a bean to be aware of the bean + * {@link ClassLoader class loader}; that is, the class loader used by the + * present bean factory to load bean classes. + * + *

    This is mainly intended to be implemented by framework classes which + * have to pick up application classes by name despite themselves potentially + * being loaded from a shared class loader. + * + *

    For a list of all bean lifecycle methods, see the + * {@link BeanFactory BeanFactory javadocs}. + * + * @author Juergen Hoeller + * @since 2.0 + * @see BeanNameAware + * @see BeanFactoryAware + * @see InitializingBean + */ +public interface BeanClassLoaderAware { + + /** + * Callback that supplies the bean {@link ClassLoader class loader} to + * a bean instance. + *

    Invoked after the population of normal bean properties but + * before an initialization callback such as + * {@link org.springframework.beans.factory.InitializingBean InitializingBean's} + * {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()} + * method or a custom init-method. + * @param classLoader the owning class loader; may be null in + * which case a default ClassLoader must be used, for example + * the ClassLoader obtained via + * {@link org.springframework.util.ClassUtils#getDefaultClassLoader()} + */ + void setBeanClassLoader(ClassLoader classLoader); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanCreationException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanCreationException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanCreationException.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,203 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import java.io.PrintStream; +import java.io.PrintWriter; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import org.springframework.beans.FatalBeanException; +import org.springframework.core.NestedRuntimeException; + +/** + * Exception thrown when a BeanFactory encounters an error when + * attempting to create a bean from a bean definition. + * + * @author Juergen Hoeller + */ +public class BeanCreationException extends FatalBeanException { + + private String beanName; + + private String resourceDescription; + + private List relatedCauses; + + + /** + * Create a new BeanCreationException. + * @param msg the detail message + */ + public BeanCreationException(String msg) { + super(msg); + } + + /** + * Create a new BeanCreationException. + * @param msg the detail message + * @param cause the root cause + */ + public BeanCreationException(String msg, Throwable cause) { + super(msg, cause); + } + + /** + * Create a new BeanCreationException. + * @param beanName the name of the bean requested + * @param msg the detail message + */ + public BeanCreationException(String beanName, String msg) { + super("Error creating bean with name '" + beanName + "': " + msg); + this.beanName = beanName; + } + + /** + * Create a new BeanCreationException. + * @param beanName the name of the bean requested + * @param msg the detail message + * @param cause the root cause + */ + public BeanCreationException(String beanName, String msg, Throwable cause) { + this(beanName, msg); + initCause(cause); + } + + /** + * Create a new BeanCreationException. + * @param resourceDescription description of the resource + * that the bean definition came from + * @param beanName the name of the bean requested + * @param msg the detail message + */ + public BeanCreationException(String resourceDescription, String beanName, String msg) { + super("Error creating bean with name '" + beanName + "'" + + (resourceDescription != null ? " defined in " + resourceDescription : "") + ": " + msg); + this.resourceDescription = resourceDescription; + this.beanName = beanName; + } + + /** + * Create a new BeanCreationException. + * @param resourceDescription description of the resource + * that the bean definition came from + * @param beanName the name of the bean requested + * @param msg the detail message + * @param cause the root cause + */ + public BeanCreationException(String resourceDescription, String beanName, String msg, Throwable cause) { + this(resourceDescription, beanName, msg); + initCause(cause); + } + + + /** + * Return the name of the bean requested, if any. + */ + public String getBeanName() { + return this.beanName; + } + + /** + * Return the description of the resource that the bean + * definition came from, if any. + */ + public String getResourceDescription() { + return this.resourceDescription; + } + + /** + * Add a related cause to this bean creation exception, + * not being a direct cause of the failure but having occured + * earlier in the creation of the same bean instance. + * @param ex the related cause to add + */ + public void addRelatedCause(Throwable ex) { + if (this.relatedCauses == null) { + this.relatedCauses = new LinkedList(); + } + this.relatedCauses.add(ex); + } + + /** + * Return the related causes, if any. + * @return the array of related causes, or null if none + */ + public Throwable[] getRelatedCauses() { + if (this.relatedCauses == null) { + return null; + } + return (Throwable[]) this.relatedCauses.toArray(new Throwable[this.relatedCauses.size()]); + } + + + public String toString() { + StringBuffer sb = new StringBuffer(super.toString()); + if (this.relatedCauses != null) { + for (Iterator it = this.relatedCauses.iterator(); it.hasNext();) { + Throwable relatedCause = (Throwable) it.next(); + sb.append("\nRelated cause: "); + sb.append(relatedCause); + } + } + return sb.toString(); + } + + public void printStackTrace(PrintStream ps) { + synchronized (ps) { + super.printStackTrace(ps); + if (this.relatedCauses != null) { + for (Iterator it = this.relatedCauses.iterator(); it.hasNext();) { + Throwable relatedCause = (Throwable) it.next(); + ps.println("Related cause:"); + relatedCause.printStackTrace(ps); + } + } + } + } + + public void printStackTrace(PrintWriter pw) { + synchronized (pw) { + super.printStackTrace(pw); + if (this.relatedCauses != null) { + for (Iterator it = this.relatedCauses.iterator(); it.hasNext();) { + Throwable relatedCause = (Throwable) it.next(); + pw.println("Related cause:"); + relatedCause.printStackTrace(pw); + } + } + } + } + + public boolean contains(Class exClass) { + if (super.contains(exClass)) { + return true; + } + if (this.relatedCauses != null) { + for (Iterator it = this.relatedCauses.iterator(); it.hasNext();) { + Throwable relatedCause = (Throwable) it.next(); + if (relatedCause instanceof NestedRuntimeException && + ((NestedRuntimeException) relatedCause).contains(exClass)) { + return true; + } + } + } + return false; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanCreationNotAllowedException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanCreationNotAllowedException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanCreationNotAllowedException.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +/** + * Exception thrown in case of a bean being requested despite + * bean creation currently not being allowed (for example, during + * the shutdown phase of a bean factory). + * + * @author Juergen Hoeller + * @since 2.0 + */ +public class BeanCreationNotAllowedException extends BeanCreationException { + + /** + * Create a new BeanCreationNotAllowedException. + * @param beanName the name of the bean requested + * @param msg the detail message + */ + public BeanCreationNotAllowedException(String beanName, String msg) { + super(beanName, msg); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanCurrentlyInCreationException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanCurrentlyInCreationException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanCurrentlyInCreationException.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +/** + * Exception thrown in case of a reference to a bean that's currently in creation. + * Typically happens when constructor autowiring matches the currently constructed bean. + * + * @author Juergen Hoeller + * @since 1.1 + */ +public class BeanCurrentlyInCreationException extends BeanCreationException { + + /** + * Create a new BeanCurrentlyInCreationException, + * with a default error message that indicates a circular reference. + * @param beanName the name of the bean requested + */ + public BeanCurrentlyInCreationException(String beanName) { + super(beanName, + "Requested bean is currently in creation: Is there an unresolvable circular reference?"); + } + + /** + * Create a new BeanCurrentlyInCreationException. + * @param beanName the name of the bean requested + * @param msg the detail message + */ + public BeanCurrentlyInCreationException(String beanName, String msg) { + super(beanName, msg); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanDefinitionStoreException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanDefinitionStoreException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanDefinitionStoreException.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,115 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import org.springframework.beans.FatalBeanException; + +/** + * Exception thrown when a BeanFactory encounters an invalid bean definition: + * e.g. in case of incomplete or contradictory bean metadata. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + */ +public class BeanDefinitionStoreException extends FatalBeanException { + + private String resourceDescription; + + private String beanName; + + + /** + * Create a new BeanDefinitionStoreException. + * @param msg the detail message (used as exception message as-is) + */ + public BeanDefinitionStoreException(String msg) { + super(msg); + } + + /** + * Create a new BeanDefinitionStoreException. + * @param msg the detail message (used as exception message as-is) + * @param cause the root cause (may be null) + */ + public BeanDefinitionStoreException(String msg, Throwable cause) { + super(msg, cause); + } + + /** + * Create a new BeanDefinitionStoreException. + * @param resourceDescription description of the resource that the bean definition came from + * @param msg the detail message (used as exception message as-is) + */ + public BeanDefinitionStoreException(String resourceDescription, String msg) { + super(msg); + this.resourceDescription = resourceDescription; + } + + /** + * Create a new BeanDefinitionStoreException. + * @param resourceDescription description of the resource that the bean definition came from + * @param msg the detail message (used as exception message as-is) + * @param cause the root cause (may be null) + */ + public BeanDefinitionStoreException(String resourceDescription, String msg, Throwable cause) { + super(msg, cause); + this.resourceDescription = resourceDescription; + } + + /** + * Create a new BeanDefinitionStoreException. + * @param resourceDescription description of the resource that the bean definition came from + * @param beanName the name of the bean requested + * @param msg the detail message (appended to an introductory message that indicates + * the resource and the name of the bean) + */ + public BeanDefinitionStoreException(String resourceDescription, String beanName, String msg) { + this(resourceDescription, beanName, msg, null); + } + + /** + * Create a new BeanDefinitionStoreException. + * @param resourceDescription description of the resource that the bean definition came from + * @param beanName the name of the bean requested + * @param msg the detail message (appended to an introductory message that indicates + * the resource and the name of the bean) + * @param cause the root cause (may be null) + */ + public BeanDefinitionStoreException(String resourceDescription, String beanName, String msg, Throwable cause) { + super("Invalid bean definition with name '" + beanName + "' defined in " + resourceDescription + ": " + msg, cause); + this.resourceDescription = resourceDescription; + this.beanName = beanName; + } + + + /** + * Return the description of the resource that the bean + * definition came from, if any. + */ + public String getResourceDescription() { + return this.resourceDescription; + } + + /** + * Return the name of the bean requested, if any. + */ + public String getBeanName() { + return this.beanName; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanFactory.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,259 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import org.springframework.beans.BeansException; + +/** + * The root interface for accessing a Spring bean container. + * This is the basic client view of a bean container; + * further interfaces such as {@link ListableBeanFactory} and + * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory} + * are available for specific purposes. + * + *

    This interface is implemented by objects that hold a number of bean definitions, + * each uniquely identified by a String name. Depending on the bean definition, + * the factory will return either an independent instance of a contained object + * (the Prototype design pattern), or a single shared instance (a superior + * alternative to the Singleton design pattern, in which the instance is a + * singleton in the scope of the factory). Which type of instance will be returned + * depends on the bean factory configuration: the API is the same. Since Spring + * 2.0, further scopes are available depending on the concrete application + * context (e.g. "request" and "session" scopes in a web environment). + * + *

    The point of this approach is that the BeanFactory is a central registry + * of application components, and centralizes configuration of application + * components (no more do individual objects need to read properties files, + * for example). See chapters 4 and 11 of "Expert One-on-One J2EE Design and + * Development" for a discussion of the benefits of this approach. + * + *

    Note that it is generally better to rely on Dependency Injection + * ("push" configuration) to configure application objects through setters + * or constructors, rather than use any form of "pull" configuration like a + * BeanFactory lookup. Spring's Dependency Injection functionality is + * implemented using this BeanFactory interface and its subinterfaces. + * + *

    Normally a BeanFactory will load bean definitions stored in a configuration + * source (such as an XML document), and use the org.springframework.beans + * package to configure the beans. However, an implementation could simply return + * Java objects it creates as necessary directly in Java code. There are no + * constraints on how the definitions could be stored: LDAP, RDBMS, XML, + * properties file, etc. Implementations are encouraged to support references + * amongst beans (Dependency Injection). + * + *

    In contrast to the methods in {@link ListableBeanFactory}, all of the + * operations in this interface will also check parent factories if this is a + * {@link HierarchicalBeanFactory}. If a bean is not found in this factory instance, + * the immediate parent factory will be asked. Beans in this factory instance + * are supposed to override beans of the same name in any parent factory. + * + *

    Bean factory implementations should support the standard bean lifecycle interfaces + * as far as possible. The full set of initialization methods and their standard order is:
    + * 1. BeanNameAware's setBeanName
    + * 2. BeanClassLoaderAware's setBeanClassLoader
    + * 3. BeanFactoryAware's setBeanFactory
    + * 4. ResourceLoaderAware's setResourceLoader + * (only applicable when running in an application context)
    + * 5. ApplicationEventPublisherAware's setApplicationEventPublisher + * (only applicable when running in an application context)
    + * 6. MessageSourceAware's setMessageSource + * (only applicable when running in an application context)
    + * 7. ApplicationContextAware's setApplicationContext + * (only applicable when running in an application context)
    + * 8. ServletContextAware's setServletContext + * (only applicable when running in a web application context)
    + * 9. postProcessBeforeInitialization methods of BeanPostProcessors
    + * 10. InitializingBean's afterPropertiesSet
    + * 11. a custom init-method definition
    + * 12. postProcessAfterInitialization methods of BeanPostProcessors + * + *

    On shutdown of a bean factory, the following lifecycle methods apply:
    + * 1. DisposableBean's destroy
    + * 2. a custom destroy-method definition + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 13 April 2001 + * @see BeanNameAware#setBeanName + * @see BeanClassLoaderAware#setBeanClassLoader + * @see BeanFactoryAware#setBeanFactory + * @see org.springframework.context.ResourceLoaderAware#setResourceLoader + * @see org.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher + * @see org.springframework.context.MessageSourceAware#setMessageSource + * @see org.springframework.context.ApplicationContextAware#setApplicationContext + * @see org.springframework.web.context.ServletContextAware#setServletContext + * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization + * @see InitializingBean#afterPropertiesSet + * @see org.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName + * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization + * @see DisposableBean#destroy + * @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName + */ +public interface BeanFactory { + + /** + * Used to dereference a {@link FactoryBean} instance and distinguish it from + * beans created by the FactoryBean. For example, if the bean named + * myJndiObject is a FactoryBean, getting &myJndiObject + * will return the factory, not the instance returned by the factory. + */ + String FACTORY_BEAN_PREFIX = "&"; + + + /** + * Return an instance, which may be shared or independent, of the specified bean. + *

    This method allows a Spring BeanFactory to be used as a replacement for the + * Singleton or Prototype design pattern. Callers may retain references to + * returned objects in the case of Singleton beans. + *

    Translates aliases back to the corresponding canonical bean name. + * Will ask the parent factory if the bean cannot be found in this factory instance. + * @param name the name of the bean to retrieve + * @return an instance of the bean + * @throws NoSuchBeanDefinitionException if there is no bean definition + * with the specified name + * @throws BeansException if the bean could not be obtained + */ + Object getBean(String name) throws BeansException; + + /** + * Return an instance, which may be shared or independent, of the specified bean. + *

    Behaves the same as {@link #getBean(String)}, but provides a measure of type + * safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the + * required type. This means that ClassCastException can't be thrown on casting + * the result correctly, as can happen with {@link #getBean(String)}. + *

    Translates aliases back to the corresponding canonical bean name. + * Will ask the parent factory if the bean cannot be found in this factory instance. + * @param name the name of the bean to retrieve + * @param requiredType type the bean must match. Can be an interface or superclass + * of the actual class, or null for any match. For example, if the value + * is Object.class, this method will succeed whatever the class of the + * returned instance. + * @return an instance of the bean + * @throws NoSuchBeanDefinitionException if there's no such bean definition + * @throws BeanNotOfRequiredTypeException if the bean is not of the required type + * @throws BeansException if the bean could not be created + */ + Object getBean(String name, Class requiredType) throws BeansException; + + /** + * Return an instance, which may be shared or independent, of the specified bean. + *

    Allows for specifying explicit constructor arguments / factory method arguments, + * overriding the specified default arguments (if any) in the bean definition. + * @param name the name of the bean to retrieve + * @param args arguments to use if creating a prototype using explicit arguments to a + * static factory method. It is invalid to use a non-null args value in any other case. + * @return an instance of the bean + * @throws NoSuchBeanDefinitionException if there's no such bean definition + * @throws BeanDefinitionStoreException if arguments have been given but + * the affected bean isn't a prototype + * @throws BeansException if the bean could not be created + * @since 2.5 + */ + Object getBean(String name, Object[] args) throws BeansException; + + /** + * Does this bean factory contain a bean with the given name? More specifically, + * is {@link #getBean} able to obtain a bean instance for the given name? + *

    Translates aliases back to the corresponding canonical bean name. + * Will ask the parent factory if the bean cannot be found in this factory instance. + * @param name the name of the bean to query + * @return whether a bean with the given name is defined + */ + boolean containsBean(String name); + + /** + * Is this bean a shared singleton? That is, will {@link #getBean} always + * return the same instance? + *

    Note: This method returning false does not clearly indicate + * independent instances. It indicates non-singleton instances, which may correspond + * to a scoped bean as well. Use the {@link #isPrototype} operation to explicitly + * check for independent instances. + *

    Translates aliases back to the corresponding canonical bean name. + * Will ask the parent factory if the bean cannot be found in this factory instance. + * @param name the name of the bean to query + * @return whether this bean corresponds to a singleton instance + * @throws NoSuchBeanDefinitionException if there is no bean with the given name + * @see #getBean + * @see #isPrototype + */ + boolean isSingleton(String name) throws NoSuchBeanDefinitionException; + + /** + * Is this bean a prototype? That is, will {@link #getBean} always return + * independent instances? + *

    Note: This method returning false does not clearly indicate + * a singleton object. It indicates non-independent instances, which may correspond + * to a scoped bean as well. Use the {@link #isSingleton} operation to explicitly + * check for a shared singleton instance. + *

    Translates aliases back to the corresponding canonical bean name. + * Will ask the parent factory if the bean cannot be found in this factory instance. + * @param name the name of the bean to query + * @return whether this bean will always deliver independent instances + * @throws NoSuchBeanDefinitionException if there is no bean with the given name + * @since 2.0.3 + * @see #getBean + * @see #isSingleton + */ + boolean isPrototype(String name) throws NoSuchBeanDefinitionException; + + /** + * Check whether the bean with the given name matches the specified type. + * More specifically, check whether a {@link #getBean} call for the given name + * would return an object that is assignable to the specified target type. + *

    Translates aliases back to the corresponding canonical bean name. + * Will ask the parent factory if the bean cannot be found in this factory instance. + * @param name the name of the bean to query + * @param targetType the type to match against + * @return true if the bean type matches, + * false if it doesn't match or cannot be determined yet + * @throws NoSuchBeanDefinitionException if there is no bean with the given name + * @since 2.0.1 + * @see #getBean + * @see #getType + */ + boolean isTypeMatch(String name, Class targetType) throws NoSuchBeanDefinitionException; + + /** + * Determine the type of the bean with the given name. More specifically, + * determine the type of object that {@link #getBean} would return for the given name. + *

    For a {@link FactoryBean}, return the type of object that the FactoryBean creates, + * as exposed by {@link FactoryBean#getObjectType()}. + *

    Translates aliases back to the corresponding canonical bean name. + * Will ask the parent factory if the bean cannot be found in this factory instance. + * @param name the name of the bean to query + * @return the type of the bean, or null if not determinable + * @throws NoSuchBeanDefinitionException if there is no bean with the given name + * @since 1.1.2 + * @see #getBean + * @see #isTypeMatch + */ + Class getType(String name) throws NoSuchBeanDefinitionException; + + /** + * Return the aliases for the given bean name, if any. + * All of those aliases point to the same bean when used in a {@link #getBean} call. + *

    If the given name is an alias, the corresponding original bean name + * and other aliases (if any) will be returned, with the original bean name + * being the first element in the array. + *

    Will ask the parent factory if the bean cannot be found in this factory instance. + * @param name the bean name to check for aliases + * @return the aliases, or an empty array if none + * @see #getBean + */ + String[] getAliases(String name); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanFactoryAware.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanFactoryAware.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanFactoryAware.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import org.springframework.beans.BeansException; + +/** + * Interface to be implemented by beans that wish to be aware of their + * owning {@link BeanFactory}. + * + *

    For example, beans can look up collaborating beans via the factory + * (Dependency Lookup). Note that most beans will choose to receive references + * to collaborating beans via corresponding bean properties or constructor + * arguments (Dependency Injection). + * + *

    For a list of all bean lifecycle methods, see the + * {@link BeanFactory BeanFactory javadocs}. + * + * @author Rod Johnson + * @since 11.03.2003 + * @see BeanNameAware + * @see BeanClassLoaderAware + * @see InitializingBean + * @see org.springframework.context.ApplicationContextAware + */ +public interface BeanFactoryAware { + + /** + * Callback that supplies the owning factory to a bean instance. + *

    Invoked after the population of normal bean properties + * but before an initialization callback such as + * {@link InitializingBean#afterPropertiesSet()} or a custom init-method. + * @param beanFactory owning BeanFactory (never null). + * The bean can immediately call methods on the factory. + * @throws BeansException in case of initialization errors + * @see BeanInitializationException + */ + void setBeanFactory(BeanFactory beanFactory) throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanFactoryUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanFactoryUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanFactoryUtils.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,421 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.BeansException; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +/** + * Convenience methods operating on bean factories, in particular + * on the {@link ListableBeanFactory} interface. + * + *

    Returns bean counts, bean names or bean instances, + * taking into account the nesting hierarchy of a bean factory + * (which the methods defined on the ListableBeanFactory interface don't, + * in contrast to the methods defined on the BeanFactory interface). + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 04.07.2003 + */ +public abstract class BeanFactoryUtils { + + /** + * Separator for generated bean names. If a class name or parent name is not + * unique, "#1", "#2" etc will be appended, until the name becomes unique. + */ + public static final String GENERATED_BEAN_NAME_SEPARATOR = "#"; + + + /** + * Return whether the given name is a factory dereference + * (beginning with the factory dereference prefix). + * @param name the name of the bean + * @return whether the given name is a factory dereference + * @see BeanFactory#FACTORY_BEAN_PREFIX + */ + public static boolean isFactoryDereference(String name) { + return (name != null && name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)); + } + + /** + * Return the actual bean name, stripping out the factory dereference + * prefix (if any, also stripping repeated factory prefixes if found). + * @param name the name of the bean + * @return the transformed name + * @see BeanFactory#FACTORY_BEAN_PREFIX + */ + public static String transformedBeanName(String name) { + Assert.notNull(name, "'name' must not be null"); + String beanName = name; + while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) { + beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length()); + } + return beanName; + } + + /** + * Return whether the given name is a bean name which has been generated + * by the default naming strategy (containing a "#..." part). + * @param name the name of the bean + * @return whether the given name is a generated bean name + * @see #GENERATED_BEAN_NAME_SEPARATOR + * @see org.springframework.beans.factory.support.BeanDefinitionReaderUtils#generateBeanName + * @see org.springframework.beans.factory.support.DefaultBeanNameGenerator + */ + public static boolean isGeneratedBeanName(String name) { + return (name != null && name.indexOf(GENERATED_BEAN_NAME_SEPARATOR) != -1); + } + + /** + * Extract the "raw" bean name from the given (potentially generated) bean name, + * excluding any "#..." suffixes which might have been added for uniqueness. + * @param name the potentially generated bean name + * @return the raw bean name + * @see #GENERATED_BEAN_NAME_SEPARATOR + */ + public static String originalBeanName(String name) { + Assert.notNull(name, "'name' must not be null"); + int separatorIndex = name.indexOf(GENERATED_BEAN_NAME_SEPARATOR); + return (separatorIndex != -1 ? name.substring(0, separatorIndex) : name); + } + + + /** + * Count all beans in any hierarchy in which this factory participates. + * Includes counts of ancestor bean factories. + *

    Beans that are "overridden" (specified in a descendant factory + * with the same name) are only counted once. + * @param lbf the bean factory + * @return count of beans including those defined in ancestor factories + */ + public static int countBeansIncludingAncestors(ListableBeanFactory lbf) { + return beanNamesIncludingAncestors(lbf).length; + } + + /** + * Return all bean names in the factory, including ancestor factories. + * @param lbf the bean factory + * @return the array of matching bean names, or an empty array if none + * @see #beanNamesForTypeIncludingAncestors + */ + public static String[] beanNamesIncludingAncestors(ListableBeanFactory lbf) { + return beanNamesForTypeIncludingAncestors(lbf, Object.class); + } + + + /** + * Get all bean names for the given type, including those defined in ancestor + * factories. Will return unique names in case of overridden bean definitions. + *

    Does consider objects created by FactoryBeans, which means that FactoryBeans + * will get initialized. If the object created by the FactoryBean doesn't match, + * the raw FactoryBean itself will be matched against the type. + *

    This version of beanNamesForTypeIncludingAncestors automatically + * includes prototypes and FactoryBeans. + * @param lbf the bean factory + * @param type the type that beans must match + * @return the array of matching bean names, or an empty array if none + */ + public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lbf, Class type) { + Assert.notNull(lbf, "ListableBeanFactory must not be null"); + String[] result = lbf.getBeanNamesForType(type); + if (lbf instanceof HierarchicalBeanFactory) { + HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; + if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { + String[] parentResult = beanNamesForTypeIncludingAncestors( + (ListableBeanFactory) hbf.getParentBeanFactory(), type); + List resultList = new ArrayList(); + resultList.addAll(Arrays.asList(result)); + for (int i = 0; i < parentResult.length; i++) { + String beanName = parentResult[i]; + if (!resultList.contains(beanName) && !hbf.containsLocalBean(beanName)) { + resultList.add(beanName); + } + } + result = StringUtils.toStringArray(resultList); + } + } + return result; + } + + /** + * Get all bean names for the given type, including those defined in ancestor + * factories. Will return unique names in case of overridden bean definitions. + *

    Does consider objects created by FactoryBeans if the "allowEagerInit" + * flag is set, which means that FactoryBeans will get initialized. If the + * object created by the FactoryBean doesn't match, the raw FactoryBean itself + * will be matched against the type. If "allowEagerInit" is not set, + * only raw FactoryBeans will be checked (which doesn't require initialization + * of each FactoryBean). + * @param lbf the bean factory + * @param includeNonSingletons whether to include prototype or scoped beans too + * or just singletons (also applies to FactoryBeans) + * @param allowEagerInit whether to initialize lazy-init singletons and + * objects created by FactoryBeans (or by factory methods with a + * "factory-bean" reference) for the type check. Note that FactoryBeans need to be + * eagerly initialized to determine their type: So be aware that passing in "true" + * for this flag will initialize FactoryBeans and "factory-bean" references. + * @param type the type that beans must match + * @return the array of matching bean names, or an empty array if none + */ + public static String[] beanNamesForTypeIncludingAncestors( + ListableBeanFactory lbf, Class type, boolean includeNonSingletons, boolean allowEagerInit) { + + Assert.notNull(lbf, "ListableBeanFactory must not be null"); + String[] result = lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit); + if (lbf instanceof HierarchicalBeanFactory) { + HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; + if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { + String[] parentResult = beanNamesForTypeIncludingAncestors( + (ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit); + List resultList = new ArrayList(); + resultList.addAll(Arrays.asList(result)); + for (int i = 0; i < parentResult.length; i++) { + String beanName = parentResult[i]; + if (!resultList.contains(beanName) && !hbf.containsLocalBean(beanName)) { + resultList.add(beanName); + } + } + result = StringUtils.toStringArray(resultList); + } + } + return result; + } + + /** + * Return all beans of the given type or subtypes, also picking up beans defined in + * ancestor bean factories if the current bean factory is a HierarchicalBeanFactory. + * The returned Map will only contain beans of this type. + *

    Does consider objects created by FactoryBeans, which means that FactoryBeans + * will get initialized. If the object created by the FactoryBean doesn't match, + * the raw FactoryBean itself will be matched against the type. + * @param lbf the bean factory + * @param type type of bean to match + * @return the Map of matching bean instances, or an empty Map if none + * @throws BeansException if a bean could not be created + */ + public static Map beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class type) + throws BeansException { + + Assert.notNull(lbf, "ListableBeanFactory must not be null"); + Map result = new LinkedHashMap(4); + result.putAll(lbf.getBeansOfType(type)); + if (lbf instanceof HierarchicalBeanFactory) { + HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; + if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { + Map parentResult = beansOfTypeIncludingAncestors( + (ListableBeanFactory) hbf.getParentBeanFactory(), type); + for (Iterator it = parentResult.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + String beanName = (String) entry.getKey(); + if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) { + result.put(beanName, entry.getValue()); + } + } + } + } + return result; + } + + /** + * Return all beans of the given type or subtypes, also picking up beans defined in + * ancestor bean factories if the current bean factory is a HierarchicalBeanFactory. + * The returned Map will only contain beans of this type. + *

    Does consider objects created by FactoryBeans if the "allowEagerInit" + * flag is set, which means that FactoryBeans will get initialized. If the + * object created by the FactoryBean doesn't match, the raw FactoryBean itself + * will be matched against the type. If "allowEagerInit" is not set, + * only raw FactoryBeans will be checked (which doesn't require initialization + * of each FactoryBean). + * @param lbf the bean factory + * @param type type of bean to match + * @param includeNonSingletons whether to include prototype or scoped beans too + * or just singletons (also applies to FactoryBeans) + * @param allowEagerInit whether to initialize lazy-init singletons and + * objects created by FactoryBeans (or by factory methods with a + * "factory-bean" reference) for the type check. Note that FactoryBeans need to be + * eagerly initialized to determine their type: So be aware that passing in "true" + * for this flag will initialize FactoryBeans and "factory-bean" references. + * @return the Map of matching bean instances, or an empty Map if none + * @throws BeansException if a bean could not be created + */ + public static Map beansOfTypeIncludingAncestors( + ListableBeanFactory lbf, Class type, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException { + + Assert.notNull(lbf, "ListableBeanFactory must not be null"); + Map result = new LinkedHashMap(4); + result.putAll(lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit)); + if (lbf instanceof HierarchicalBeanFactory) { + HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf; + if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) { + Map parentResult = beansOfTypeIncludingAncestors( + (ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit); + for (Iterator it = parentResult.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + String beanName = (String) entry.getKey(); + if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) { + result.put(beanName, entry.getValue()); + } + } + } + } + return result; + } + + + /** + * Return a single bean of the given type or subtypes, also picking up beans + * defined in ancestor bean factories if the current bean factory is a + * HierarchicalBeanFactory. Useful convenience method when we expect a + * single bean and don't care about the bean name. + *

    Does consider objects created by FactoryBeans, which means that FactoryBeans + * will get initialized. If the object created by the FactoryBean doesn't match, + * the raw FactoryBean itself will be matched against the type. + *

    This version of beanOfTypeIncludingAncestors automatically includes + * prototypes and FactoryBeans. + * @param lbf the bean factory + * @param type type of bean to match + * @return the matching bean instance + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + * if 0 or more than 1 beans of the given type were found + * @throws BeansException if the bean could not be created + */ + public static Object beanOfTypeIncludingAncestors(ListableBeanFactory lbf, Class type) + throws BeansException { + + Map beansOfType = beansOfTypeIncludingAncestors(lbf, type); + if (beansOfType.size() == 1) { + return beansOfType.values().iterator().next(); + } + else { + throw new NoSuchBeanDefinitionException(type, "expected single bean but found " + beansOfType.size()); + } + } + + /** + * Return a single bean of the given type or subtypes, also picking up beans + * defined in ancestor bean factories if the current bean factory is a + * HierarchicalBeanFactory. Useful convenience method when we expect a + * single bean and don't care about the bean name. + *

    Does consider objects created by FactoryBeans if the "allowEagerInit" + * flag is set, which means that FactoryBeans will get initialized. If the + * object created by the FactoryBean doesn't match, the raw FactoryBean itself + * will be matched against the type. If "allowEagerInit" is not set, + * only raw FactoryBeans will be checked (which doesn't require initialization + * of each FactoryBean). + * @param lbf the bean factory + * @param type type of bean to match + * @param includeNonSingletons whether to include prototype or scoped beans too + * or just singletons (also applies to FactoryBeans) + * @param allowEagerInit whether to initialize lazy-init singletons and + * objects created by FactoryBeans (or by factory methods with a + * "factory-bean" reference) for the type check. Note that FactoryBeans need to be + * eagerly initialized to determine their type: So be aware that passing in "true" + * for this flag will initialize FactoryBeans and "factory-bean" references. + * @return the matching bean instance + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + * if 0 or more than 1 beans of the given type were found + * @throws BeansException if the bean could not be created + */ + public static Object beanOfTypeIncludingAncestors( + ListableBeanFactory lbf, Class type, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException { + + Map beansOfType = beansOfTypeIncludingAncestors(lbf, type, includeNonSingletons, allowEagerInit); + if (beansOfType.size() == 1) { + return beansOfType.values().iterator().next(); + } + else { + throw new NoSuchBeanDefinitionException(type, "expected single bean but found " + beansOfType.size()); + } + } + + /** + * Return a single bean of the given type or subtypes, not looking in ancestor + * factories. Useful convenience method when we expect a single bean and + * don't care about the bean name. + *

    Does consider objects created by FactoryBeans, which means that FactoryBeans + * will get initialized. If the object created by the FactoryBean doesn't match, + * the raw FactoryBean itself will be matched against the type. + *

    This version of beanOfType automatically includes + * prototypes and FactoryBeans. + * @param lbf the bean factory + * @param type type of bean to match + * @return the matching bean instance + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + * if 0 or more than 1 beans of the given type were found + * @throws BeansException if the bean could not be created + */ + public static Object beanOfType(ListableBeanFactory lbf, Class type) throws BeansException { + Assert.notNull(lbf, "ListableBeanFactory must not be null"); + Map beansOfType = lbf.getBeansOfType(type); + if (beansOfType.size() == 1) { + return beansOfType.values().iterator().next(); + } + else { + throw new NoSuchBeanDefinitionException(type, "expected single bean but found " + beansOfType.size()); + } + } + + /** + * Return a single bean of the given type or subtypes, not looking in ancestor + * factories. Useful convenience method when we expect a single bean and + * don't care about the bean name. + *

    Does consider objects created by FactoryBeans if the "allowEagerInit" + * flag is set, which means that FactoryBeans will get initialized. If the + * object created by the FactoryBean doesn't match, the raw FactoryBean itself + * will be matched against the type. If "allowEagerInit" is not set, + * only raw FactoryBeans will be checked (which doesn't require initialization + * of each FactoryBean). + * @param lbf the bean factory + * @param type type of bean to match + * @param includeNonSingletons whether to include prototype or scoped beans too + * or just singletons (also applies to FactoryBeans) + * @param allowEagerInit whether to initialize lazy-init singletons and + * objects created by FactoryBeans (or by factory methods with a + * "factory-bean" reference) for the type check. Note that FactoryBeans need to be + * eagerly initialized to determine their type: So be aware that passing in "true" + * for this flag will initialize FactoryBeans and "factory-bean" references. + * @return the matching bean instance + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + * if 0 or more than 1 beans of the given type were found + * @throws BeansException if the bean could not be created + */ + public static Object beanOfType( + ListableBeanFactory lbf, Class type, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException { + + Assert.notNull(lbf, "ListableBeanFactory must not be null"); + Map beansOfType = lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit); + if (beansOfType.size() == 1) { + return beansOfType.values().iterator().next(); + } + else { + throw new NoSuchBeanDefinitionException(type, "expected single bean but found " + beansOfType.size()); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanInitializationException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanInitializationException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanInitializationException.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import org.springframework.beans.FatalBeanException; + +/** + * Exception that a bean implementation is suggested to throw if its own + * factory-aware initialization code fails. BeansExceptions thrown by + * bean factory methods themselves should simply be propagated as-is. + * + *

    Note that non-factory-aware initialization methods like afterPropertiesSet() + * or a custom "init-method" can throw any exception. + * + * @author Juergen Hoeller + * @since 13.11.2003 + * @see BeanFactoryAware#setBeanFactory + * @see InitializingBean#afterPropertiesSet + */ +public class BeanInitializationException extends FatalBeanException { + + /** + * Create a new BeanInitializationException with the specified message. + * @param msg the detail message + */ + public BeanInitializationException(String msg) { + super(msg); + } + + /** + * Create a new BeanInitializationException with the specified message + * and root cause. + * @param msg the detail message + * @param cause the root cause + */ + public BeanInitializationException(String msg, Throwable cause) { + super(msg, cause); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanIsAbstractException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanIsAbstractException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanIsAbstractException.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +/** + * Exception thrown when a bean instance has been requested for a bean + * which has been defined as abstract + * @author Juergen Hoeller + * @since 1.1 + * @see org.springframework.beans.factory.support.AbstractBeanDefinition#setAbstract + */ +public class BeanIsAbstractException extends BeanCreationException { + + /** + * Create a new BeanIsAbstractException. + * @param beanName the name of the bean requested + */ + public BeanIsAbstractException(String beanName) { + super(beanName, "Bean definition is abstract"); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanIsNotAFactoryException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanIsNotAFactoryException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanIsNotAFactoryException.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +/** + * Exception thrown when a bean is not a factory, but a user tries to get + * at the factory for the given bean name. Whether a bean is a factory is + * determined by whether it implements the FactoryBean interface. + * + * @author Rod Johnson + * @since 10.03.2003 + * @see org.springframework.beans.factory.FactoryBean + */ +public class BeanIsNotAFactoryException extends BeanNotOfRequiredTypeException { + + /** + * Create a new BeanIsNotAFactoryException. + * @param name the name of the bean requested + * @param actualType the actual type returned, which did not match + * the expected type + */ + public BeanIsNotAFactoryException(String name, Class actualType) { + super(name, FactoryBean.class, actualType); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanNameAware.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanNameAware.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanNameAware.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +/** + * Interface to be implemented by beans that want to be aware of their + * bean name in a bean factory. Note that it is not usually recommended + * that an object depend on its bean name, as this represents a potentially + * brittle dependence on external configuration, as well as a possibly + * unnecessary dependence on a Spring API. + * + *

    For a list of all bean lifecycle methods, see the + * {@link BeanFactory BeanFactory javadocs}. + * + * @author Juergen Hoeller + * @since 01.11.2003 + * @see BeanClassLoaderAware + * @see BeanFactoryAware + * @see InitializingBean + */ +public interface BeanNameAware { + + /** + * Set the name of the bean in the bean factory that created this bean. + *

    Invoked after population of normal bean properties but before an + * init callback such as {@link InitializingBean#afterPropertiesSet()} + * or a custom init-method. + * @param name the name of the bean in the factory. + * Note that this name is the actual bean name used in the factory, which may + * differ from the originally specified name: in particular for inner bean + * names, the actual bean name might have been made unique through appending + * "#..." suffixes. Use the {@link BeanFactoryUtils#originalBeanName(String)} + * method to extract the original bean name (without suffix), if desired. + */ + void setBeanName(String name); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/BeanNotOfRequiredTypeException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/BeanNotOfRequiredTypeException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/BeanNotOfRequiredTypeException.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import org.springframework.beans.BeansException; + +/** + * Thrown when a bean doesn't match the expected type. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public class BeanNotOfRequiredTypeException extends BeansException { + + /** The name of the instance that was of the wrong type */ + private String beanName; + + /** The required type */ + private Class requiredType; + + /** The offending type */ + private Class actualType; + + + /** + * Create a new BeanNotOfRequiredTypeException. + * @param beanName the name of the bean requested + * @param requiredType the required type + * @param actualType the actual type returned, which did not match + * the expected type + */ + public BeanNotOfRequiredTypeException(String beanName, Class requiredType, Class actualType) { + super("Bean named '" + beanName + "' must be of type [" + requiredType.getName() + + "], but was actually of type [" + actualType.getName() + "]"); + this.beanName = beanName; + this.requiredType = requiredType; + this.actualType = actualType; + } + + + /** + * Return the name of the instance that was of the wrong type. + */ + public String getBeanName() { + return this.beanName; + } + + /** + * Return the expected type for the bean. + */ + public Class getRequiredType() { + return this.requiredType; + } + + /** + * Return the actual type of the instance found. + */ + public Class getActualType() { + return this.actualType; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/CannotLoadBeanClassException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/CannotLoadBeanClassException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/CannotLoadBeanClassException.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,96 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import org.springframework.beans.FatalBeanException; + +/** + * Exception thrown when the BeanFactory cannot load the specified class + * of a given bean. + * + * @author Juergen Hoeller + * @since 2.0 + */ +public class CannotLoadBeanClassException extends FatalBeanException { + + private String resourceDescription; + + private String beanName; + + private String beanClassName; + + + /** + * Create a new CannotLoadBeanClassException. + * @param resourceDescription description of the resource + * that the bean definition came from + * @param beanName the name of the bean requested + * @param beanClassName the name of the bean class + * @param cause the root cause + */ + public CannotLoadBeanClassException( + String resourceDescription, String beanName, String beanClassName, ClassNotFoundException cause) { + + super("Cannot find class [" + beanClassName + "] for bean with name '" + beanName + + "' defined in " + resourceDescription, cause); + this.resourceDescription = resourceDescription; + this.beanName = beanName; + this.beanClassName = beanClassName; + } + + /** + * Create a new CannotLoadBeanClassException. + * @param resourceDescription description of the resource + * that the bean definition came from + * @param beanName the name of the bean requested + * @param beanClassName the name of the bean class + * @param cause the root cause + */ + public CannotLoadBeanClassException( + String resourceDescription, String beanName, String beanClassName, LinkageError cause) { + + super("Error loading class [" + beanClassName + "] for bean with name '" + beanName + + "' defined in " + resourceDescription + ": problem with class file or dependent class", cause); + this.resourceDescription = resourceDescription; + this.beanName = beanName; + this.beanClassName = beanClassName; + } + + + /** + * Return the description of the resource that the bean + * definition came from. + */ + public String getResourceDescription() { + return this.resourceDescription; + } + + /** + * Return the name of the bean requested. + */ + public String getBeanName() { + return this.beanName; + } + + /** + * Return the name of the class we were trying to load. + */ + public String getBeanClassName() { + return this.beanClassName; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/DisposableBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/DisposableBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/DisposableBean.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +/** + * Interface to be implemented by beans that want to release resources + * on destruction. A BeanFactory is supposed to invoke the destroy + * method if it disposes a cached singleton. An application context + * is supposed to dispose all of its singletons on close. + * + *

    An alternative to implementing DisposableBean is specifying a custom + * destroy-method, for example in an XML bean definition. + * For a list of all bean lifecycle methods, see the BeanFactory javadocs. + * + * @author Juergen Hoeller + * @since 12.08.2003 + * @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName + * @see org.springframework.context.ConfigurableApplicationContext#close + */ +public interface DisposableBean { + + /** + * Invoked by a BeanFactory on destruction of a singleton. + * @throws Exception in case of shutdown errors. + * Exceptions will get logged but not rethrown to allow + * other beans to release their resources too. + */ + void destroy() throws Exception; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/FactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/FactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/FactoryBean.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,120 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +/** + * Interface to be implemented by objects used within a {@link BeanFactory} + * which are themselves factories. If a bean implements this interface, + * it is used as a factory for an object to expose, not directly as a bean + * instance that will be exposed itself. + * + *

    NB: A bean that implements this interface cannot be used as a + * normal bean. A FactoryBean is defined in a bean style, but the + * object exposed for bean references ({@link #getObject()} is always + * the object that it creates. + * + *

    FactoryBeans can support singletons and prototypes, and can + * either create objects lazily on demand or eagerly on startup. + * The {@link SmartFactoryBean} interface allows for exposing + * more fine-grained behavioral metadata. + * + *

    This interface is heavily used within the framework itself, for + * example for the AOP {@link org.springframework.aop.framework.ProxyFactoryBean} + * or the {@link org.springframework.jndi.JndiObjectFactoryBean}. + * It can be used for application components as well; however, + * this is not common outside of infrastructure code. + * + *

    NOTE: FactoryBean objects participate in the containing + * BeanFactory's synchronization of bean creation. There is usually no + * need for internal synchronization other than for purposes of lazy + * initialization within the FactoryBean itself (or the like). + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 08.03.2003 + * @see org.springframework.beans.factory.BeanFactory + * @see org.springframework.aop.framework.ProxyFactoryBean + * @see org.springframework.jndi.JndiObjectFactoryBean + */ +public interface FactoryBean { + + /** + * Return an instance (possibly shared or independent) of the object + * managed by this factory. + *

    As with a {@link BeanFactory}, this allows support for both the + * Singleton and Prototype design pattern. + *

    If this FactoryBean is not fully initialized yet at the time of + * the call (for example because it is involved in a circular reference), + * throw a corresponding {@link FactoryBeanNotInitializedException}. + *

    As of Spring 2.0, FactoryBeans are allowed to return null + * objects. The factory will consider this as normal value to be used; it + * will not throw a FactoryBeanNotInitializedException in this case anymore. + * FactoryBean implementations are encouraged to throw + * FactoryBeanNotInitializedException themselves now, as appropriate. + * @return an instance of the bean (can be null) + * @throws Exception in case of creation errors + * @see FactoryBeanNotInitializedException + */ + Object getObject() throws Exception; + + /** + * Return the type of object that this FactoryBean creates, + * or null if not known in advance. + *

    This allows one to check for specific types of beans without + * instantiating objects, for example on autowiring. + *

    In the case of implementations that are creating a singleton object, + * this method should try to avoid singleton creation as far as possible; + * it should rather estimate the type in advance. + * For prototypes, returning a meaningful type here is advisable too. + *

    This method can be called before this FactoryBean has + * been fully initialized. It must not rely on state created during + * initialization; of course, it can still use such state if available. + *

    NOTE: Autowiring will simply ignore FactoryBeans that return + * null here. Therefore it is highly recommended to implement + * this method properly, using the current state of the FactoryBean. + * @return the type of object that this FactoryBean creates, + * or null if not known at the time of the call + * @see ListableBeanFactory#getBeansOfType + */ + Class getObjectType(); + + /** + * Is the object managed by this factory a singleton? That is, + * will {@link #getObject()} always return the same object + * (a reference that can be cached)? + *

    NOTE: If a FactoryBean indicates to hold a singleton object, + * the object returned from getObject() might get cached + * by the owning BeanFactory. Hence, do not return true + * unless the FactoryBean always exposes the same reference. + *

    The singleton status of the FactoryBean itself will generally + * be provided by the owning BeanFactory; usually, it has to be + * defined as singleton there. + *

    NOTE: This method returning false does not + * necessarily indicate that returned objects are independent instances. + * An implementation of the extended {@link SmartFactoryBean} interface + * may explicitly indicate independent instances through its + * {@link SmartFactoryBean#isPrototype()} method. Plain {@link FactoryBean} + * implementations which do not implement this extended interface are + * simply assumed to always return independent instances if the + * isSingleton() implementation returns false. + * @return whether the exposed object is a singleton + * @see #getObject() + * @see SmartFactoryBean#isPrototype() + */ + boolean isSingleton(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/FactoryBeanNotInitializedException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/FactoryBeanNotInitializedException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/FactoryBeanNotInitializedException.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import org.springframework.beans.FatalBeanException; + +/** + * Exception to be thrown from a FactoryBean's getObject() method + * if the bean is not fully initialized yet, for example because it is involved + * in a circular reference. + * + *

    Note: A circular reference with a FactoryBean cannot be solved by eagerly + * caching singleton instances like with normal beans. The reason is that + * every FactoryBean needs to be fully initialized before it can + * return the created bean, while only specific normal beans need + * to be initialized - that is, if a collaborating bean actually invokes + * them on initialization instead of just storing the reference. + * + * @author Juergen Hoeller + * @since 30.10.2003 + * @see FactoryBean#getObject() + */ +public class FactoryBeanNotInitializedException extends FatalBeanException { + + /** + * Create a new FactoryBeanNotInitializedException with the default message. + */ + public FactoryBeanNotInitializedException() { + super("FactoryBean is not fully initialized yet"); + } + + /** + * Create a new FactoryBeanNotInitializedException with the given message. + * @param msg the detail message + */ + public FactoryBeanNotInitializedException(String msg) { + super(msg); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/HierarchicalBeanFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/HierarchicalBeanFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/HierarchicalBeanFactory.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +/** + * Sub-interface implemented by bean factories that can be part + * of a hierarchy. + * + *

    The corresponding setParentBeanFactory method for bean + * factories that allow setting the parent in a configurable + * fashion can be found in the ConfigurableBeanFactory interface. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 07.07.2003 + * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#setParentBeanFactory + */ +public interface HierarchicalBeanFactory extends BeanFactory { + + /** + * Return the parent bean factory, or null if there is none. + */ + BeanFactory getParentBeanFactory(); + + /** + * Return whether the local bean factory contains a bean of the given name, + * ignoring beans defined in ancestor contexts. + *

    This is an alternative to containsBean, ignoring a bean + * of the given name from an ancestor bean factory. + * @param name the name of the bean to query + * @return whether a bean with the given name is defined in the local factory + * @see org.springframework.beans.factory.BeanFactory#containsBean + */ + boolean containsLocalBean(String name); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/InitializingBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/InitializingBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/InitializingBean.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +/** + * Interface to be implemented by beans that need to react once all their + * properties have been set by a BeanFactory: for example, to perform custom + * initialization, or merely to check that all mandatory properties have been set. + * + *

    An alternative to implementing InitializingBean is specifying a custom + * init-method, for example in an XML bean definition. + * For a list of all bean lifecycle methods, see the BeanFactory javadocs. + * + * @author Rod Johnson + * @see BeanNameAware + * @see BeanFactoryAware + * @see BeanFactory + * @see org.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName + * @see org.springframework.context.ApplicationContextAware + */ +public interface InitializingBean { + + /** + * Invoked by a BeanFactory after it has set all bean properties supplied + * (and satisfied BeanFactoryAware and ApplicationContextAware). + *

    This method allows the bean instance to perform initialization only + * possible when all bean properties have been set and to throw an + * exception in the event of misconfiguration. + * @throws Exception in the event of misconfiguration (such + * as failure to set an essential property) or if initialization fails. + */ + void afterPropertiesSet() throws Exception; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/ListableBeanFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/ListableBeanFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/ListableBeanFactory.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,213 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import java.util.Map; + +import org.springframework.beans.BeansException; + +/** + * Extension of the {@link BeanFactory} interface to be implemented by bean factories + * that can enumerate all their bean instances, rather than attempting bean lookup + * by name one by one as requested by clients. BeanFactory implementations that + * preload all their bean definitions (such as XML-based factories) may implement + * this interface. + * + *

    If this is a {@link HierarchicalBeanFactory}, the return values will not + * take any BeanFactory hierarchy into account, but will relate only to the beans + * defined in the current factory. Use the {@link BeanFactoryUtils} helper class + * to consider beans in ancestor factories too. + * + *

    The methods in this interface will just respect bean definitions of this factory. + * They will ignore any singleton beans that have been registered by other means like + * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}'s + * registerSingleton method, with the exception of + * getBeanNamesOfType and getBeansOfType which will check + * such manually registered singletons too. Of course, BeanFactory's getBean + * does allow transparent access to such special beans as well. However, in typical + * scenarios, all beans will be defined by external bean definitions anyway, so most + * applications don't need to worry about this differentation. + * + *

    NOTE: With the exception of getBeanDefinitionCount + * and containsBeanDefinition, the methods in this interface + * are not designed for frequent invocation. Implementations may be slow. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 16 April 2001 + * @see HierarchicalBeanFactory + * @see BeanFactoryUtils + */ +public interface ListableBeanFactory extends BeanFactory { + + /** + * Check if this bean factory contains a bean definition with the given name. + *

    Does not consider any hierarchy this factory may participate in, + * and ignores any singleton beans that have been registered by + * other means than bean definitions. + * @param beanName the name of the bean to look for + * @return if this bean factory contains a bean definition with the given name + * @see #containsBean + */ + boolean containsBeanDefinition(String beanName); + + /** + * Return the number of beans defined in the factory. + *

    Does not consider any hierarchy this factory may participate in, + * and ignores any singleton beans that have been registered by + * other means than bean definitions. + * @return the number of beans defined in the factory + */ + int getBeanDefinitionCount(); + + /** + * Return the names of all beans defined in this factory. + *

    Does not consider any hierarchy this factory may participate in, + * and ignores any singleton beans that have been registered by + * other means than bean definitions. + * @return the names of all beans defined in this factory, + * or an empty array if none defined + */ + String[] getBeanDefinitionNames(); + + /** + * Return the names of beans matching the given type (including subclasses), + * judging from either bean definitions or the value of getObjectType + * in the case of FactoryBeans. + *

    NOTE: This method introspects top-level beans only. It does not + * check nested beans which might match the specified type as well. + *

    Does consider objects created by FactoryBeans, which means that FactoryBeans + * will get initialized. If the object created by the FactoryBean doesn't match, + * the raw FactoryBean itself will be matched against the type. + *

    Does not consider any hierarchy this factory may participate in. + * Use BeanFactoryUtils' beanNamesForTypeIncludingAncestors + * to include beans in ancestor factories too. + *

    Note: Does not ignore singleton beans that have been registered + * by other means than bean definitions. + *

    This version of getBeanNamesForType matches all kinds of beans, + * be it singletons, prototypes, or FactoryBeans. In most implementations, the + * result will be the same as for getBeanNamesOfType(type, true, true). + *

    Bean names returned by this method should always return bean names in the + * order of definition in the backend configuration, as far as possible. + * @param type the class or interface to match, or null for all bean names + * @return the names of beans (or objects created by FactoryBeans) matching + * the given object type (including subclasses), or an empty array if none + * @see FactoryBean#getObjectType + * @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class) + */ + String[] getBeanNamesForType(Class type); + + /** + * Return the names of beans matching the given type (including subclasses), + * judging from either bean definitions or the value of getObjectType + * in the case of FactoryBeans. + *

    NOTE: This method introspects top-level beans only. It does not + * check nested beans which might match the specified type as well. + *

    Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set, + * which means that FactoryBeans will get initialized. If the object created by the + * FactoryBean doesn't match, the raw FactoryBean itself will be matched against the + * type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked + * (which doesn't require initialization of each FactoryBean). +$ *

    Does not consider any hierarchy this factory may participate in. + * Use BeanFactoryUtils' beanNamesForTypeIncludingAncestors + * to include beans in ancestor factories too. + *

    Note: Does not ignore singleton beans that have been registered + * by other means than bean definitions. + *

    Bean names returned by this method should always return bean names in the + * order of definition in the backend configuration, as far as possible. + * @param type the class or interface to match, or null for all bean names + * @param includeNonSingletons whether to include prototype or scoped beans too + * or just singletons (also applies to FactoryBeans) + * @param allowEagerInit whether to initialize lazy-init singletons and + * objects created by FactoryBeans (or by factory methods with a + * "factory-bean" reference) for the type check. Note that FactoryBeans need to be + * eagerly initialized to determine their type: So be aware that passing in "true" + * for this flag will initialize FactoryBeans and "factory-bean" references. + * @return the names of beans (or objects created by FactoryBeans) matching + * the given object type (including subclasses), or an empty array if none + * @see FactoryBean#getObjectType + * @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean) + */ + String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit); + + /** + * Return the bean instances that match the given object type (including + * subclasses), judging from either bean definitions or the value of + * getObjectType in the case of FactoryBeans. + *

    NOTE: This method introspects top-level beans only. It does not + * check nested beans which might match the specified type as well. + *

    Does consider objects created by FactoryBeans, which means that FactoryBeans + * will get initialized. If the object created by the FactoryBean doesn't match, + * the raw FactoryBean itself will be matched against the type. + *

    Does not consider any hierarchy this factory may participate in. + * Use BeanFactoryUtils' beansOfTypeIncludingAncestors + * to include beans in ancestor factories too. + *

    Note: Does not ignore singleton beans that have been registered + * by other means than bean definitions. + *

    This version of getBeansOfType matches all kinds of beans, be it + * singletons, prototypes, or FactoryBeans. In most implementations, the + * result will be the same as for getBeansOfType(type, true, true). + *

    The Map returned by this method should always return bean names and + * corresponding bean instances in the order of definition in the + * backend configuration, as far as possible. + * @param type the class or interface to match, or null for all concrete beans + * @return a Map with the matching beans, containing the bean names as + * keys and the corresponding bean instances as values + * @throws BeansException if a bean could not be created + * @since 1.1.2 + * @see FactoryBean#getObjectType + * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class) + */ + Map getBeansOfType(Class type) throws BeansException; + + /** + * Return the bean instances that match the given object type (including + * subclasses), judging from either bean definitions or the value of + * getObjectType in the case of FactoryBeans. + *

    NOTE: This method introspects top-level beans only. It does not + * check nested beans which might match the specified type as well. + *

    Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set, + * which means that FactoryBeans will get initialized. If the object created by the + * FactoryBean doesn't match, the raw FactoryBean itself will be matched against the + * type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked + * (which doesn't require initialization of each FactoryBean). + *

    Does not consider any hierarchy this factory may participate in. + * Use BeanFactoryUtils' beansOfTypeIncludingAncestors + * to include beans in ancestor factories too. + *

    Note: Does not ignore singleton beans that have been registered + * by other means than bean definitions. + *

    The Map returned by this method should always return bean names and + * corresponding bean instances in the order of definition in the + * backend configuration, as far as possible. + * @param type the class or interface to match, or null for all concrete beans + * @param includeNonSingletons whether to include prototype or scoped beans too + * or just singletons (also applies to FactoryBeans) + * @param allowEagerInit whether to initialize lazy-init singletons and + * objects created by FactoryBeans (or by factory methods with a + * "factory-bean" reference) for the type check. Note that FactoryBeans need to be + * eagerly initialized to determine their type: So be aware that passing in "true" + * for this flag will initialize FactoryBeans and "factory-bean" references. + * @return a Map with the matching beans, containing the bean names as + * keys and the corresponding bean instances as values + * @throws BeansException if a bean could not be created + * @see FactoryBean#getObjectType + * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean) + */ + Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/NamedBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/NamedBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/NamedBean.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +/** + * Counterpart of BeanNameAware. Returns the bean name of an object. + * + *

    This interface can be introduced to avoid a brittle dependence + * on bean name in objects used with Spring IoC and Spring AOP. + * + * @author Rod Johnson + * @since 2.0 + * @see BeanNameAware + */ +public interface NamedBean { + + /** + * Return the name of this bean in a Spring bean factory. + */ + String getBeanName(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/NoSuchBeanDefinitionException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/NoSuchBeanDefinitionException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/NoSuchBeanDefinitionException.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,95 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import org.springframework.beans.BeansException; + +/** + * Exception thrown when a BeanFactory is asked for a bean + * instance name for which it cannot find a definition. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public class NoSuchBeanDefinitionException extends BeansException { + + /** Name of the missing bean */ + private String beanName; + + /** Required bean type */ + private Class beanType; + + + /** + * Create a new NoSuchBeanDefinitionException. + * @param name the name of the missing bean + */ + public NoSuchBeanDefinitionException(String name) { + super("No bean named '" + name + "' is defined"); + this.beanName = name; + } + + /** + * Create a new NoSuchBeanDefinitionException. + * @param name the name of the missing bean + * @param message detailed message describing the problem + */ + public NoSuchBeanDefinitionException(String name, String message) { + super("No bean named '" + name + "' is defined: " + message); + this.beanName = name; + } + + /** + * Create a new NoSuchBeanDefinitionException. + * @param type required type of bean + * @param message detailed message describing the problem + */ + public NoSuchBeanDefinitionException(Class type, String message) { + super("No unique bean of type [" + type.getName() + "] is defined: " + message); + this.beanType = type; + } + + /** + * Create a new NoSuchBeanDefinitionException. + * @param type required type of bean + * @param dependencyDescription a description of the originating dependency + * @param message detailed message describing the problem + */ + public NoSuchBeanDefinitionException(Class type, String dependencyDescription, String message) { + super("No matching bean of type [" + type.getName() + "] found for dependency [" + + dependencyDescription + "]: " + message); + this.beanType = type; + } + + + /** + * Return the name of the missing bean, + * if it was a lookup by name that failed. + */ + public String getBeanName() { + return this.beanName; + } + + /** + * Return the required type of bean, + * if it was a lookup by type that failed. + */ + public Class getBeanType() { + return this.beanType; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/ObjectFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/ObjectFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/ObjectFactory.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import org.springframework.beans.BeansException; + +/** + * Defines a factory which can return an Object instance + * (possibly shared or independent) when invoked. + * + *

    This interface is typically used to encapsulate a generic factory which + * returns a new instance (prototype) of some target object on each invocation. + * + *

    This interface is similar to {@link FactoryBean}, but implementations + * of the latter are normally meant to be defined as SPI instances in a + * {@link BeanFactory}, while implementations of this class are normally meant + * to be fed as an API to other beans (through injection). As such, the + * getObject() method has different exception handling behavior. + * + * @author Colin Sampaleanu + * @since 1.0.2 + * @see FactoryBean + */ +public interface ObjectFactory { + + /** + * Return an instance (possibly shared or independent) + * of the object managed by this factory. + * @return an instance of the bean (should never be null) + * @throws BeansException in case of creation errors + */ + Object getObject() throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/SmartFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/SmartFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/SmartFactoryBean.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,75 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +/** + * Extension of the {@link FactoryBean} interface. Implementations may + * indicate whether they always return independent instances, for the + * case where their {@link #isSingleton()} implementation returning + * false does not clearly indicate independent instances. + * + *

    Plain {@link FactoryBean} implementations which do not implement + * this extended interface are simply assumed to always return independent + * instances if their {@link #isSingleton()} implementation returns + * false; the exposed object is only accessed on demand. + * + *

    NOTE: This interface is a special purpose interface, mainly for + * internal use within the framework and within collaborating frameworks. + * In general, application-provided FactoryBeans should simply implement + * the plain {@link FactoryBean} interface. New methods might be added + * to this extended interface even in point releases. + * + * @author Juergen Hoeller + * @since 2.0.3 + * @see #isPrototype() + * @see #isSingleton() + */ +public interface SmartFactoryBean extends FactoryBean { + + /** + * Is the object managed by this factory a prototype? That is, + * will {@link #getObject()} always return an independent instance? + *

    The prototype status of the FactoryBean itself will generally + * be provided by the owning {@link BeanFactory}; usually, it has to be + * defined as singleton there. + *

    This method is supposed to strictly check for independent instances; + * it should not return true for scoped objects or other + * kinds of non-singleton, non-independent objects. For this reason, + * this is not simply the inverted form of {@link #isSingleton()}. + * @return whether the exposed object is a prototype + * @see #getObject() + * @see #isSingleton() + */ + boolean isPrototype(); + + /** + * Does this FactoryBean expect eager initialization, that is, + * eagerly initialize itself as well as expect eager initialization + * of its singleton object (if any)? + *

    A standard FactoryBean is not expected to initialize eagerly: + * Its {@link #getObject()} will only be called for actual access, even + * in case of a singleton object. Returning true from this + * method suggests that {@link #getObject()} should be called eagerly, + * also applying post-processors eagerly. This may make sense in case + * of a {@link #isSingleton() singleton} object, in particular if + * post-processors expect to be applied on startup. + * @return whether eager initialization applies + * @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory#preInstantiateSingletons() + */ + boolean isEagerInit(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/UnsatisfiedDependencyException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/UnsatisfiedDependencyException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/UnsatisfiedDependencyException.java 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,94 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import org.springframework.beans.BeansException; +import org.springframework.util.ClassUtils; + +/** + * Exception thrown when a bean depends on other beans or simple properties + * that were not specified in the bean factory definition, although + * dependency checking was enabled. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 03.09.2003 + */ +public class UnsatisfiedDependencyException extends BeanCreationException { + + /** + * Create a new UnsatisfiedDependencyException. + * @param resourceDescription description of the resource that the bean definition came from + * @param beanName the name of the bean requested + * @param propertyName the name of the bean property that couldn't be satisfied + * @param msg the detail message + */ + public UnsatisfiedDependencyException( + String resourceDescription, String beanName, String propertyName, String msg) { + + super(resourceDescription, beanName, + "Unsatisfied dependency expressed through bean property '" + propertyName + "'" + + (msg != null ? ": " + msg : "")); + } + + /** + * Create a new UnsatisfiedDependencyException. + * @param resourceDescription description of the resource that the bean definition came from + * @param beanName the name of the bean requested + * @param propertyName the name of the bean property that couldn't be satisfied + * @param ex the bean creation exception that indicated the unsatisfied dependency + */ + public UnsatisfiedDependencyException( + String resourceDescription, String beanName, String propertyName, BeansException ex) { + + this(resourceDescription, beanName, propertyName, (ex != null ? ": " + ex.getMessage() : "")); + initCause(ex); + } + + /** + * Create a new UnsatisfiedDependencyException. + * @param resourceDescription description of the resource that the bean definition came from + * @param beanName the name of the bean requested + * @param ctorArgIndex the index of the constructor argument that couldn't be satisfied + * @param ctorArgType the type of the constructor argument that couldn't be satisfied + * @param msg the detail message + */ + public UnsatisfiedDependencyException( + String resourceDescription, String beanName, int ctorArgIndex, Class ctorArgType, String msg) { + + super(resourceDescription, beanName, + "Unsatisfied dependency expressed through constructor argument with index " + + ctorArgIndex + " of type [" + ClassUtils.getQualifiedName(ctorArgType) + "]" + + (msg != null ? ": " + msg : "")); + } + + /** + * Create a new UnsatisfiedDependencyException. + * @param resourceDescription description of the resource that the bean definition came from + * @param beanName the name of the bean requested + * @param ctorArgIndex the index of the constructor argument that couldn't be satisfied + * @param ctorArgType the type of the constructor argument that couldn't be satisfied + * @param ex the bean creation exception that indicated the unsatisfied dependency + */ + public UnsatisfiedDependencyException( + String resourceDescription, String beanName, int ctorArgIndex, Class ctorArgType, BeansException ex) { + + this(resourceDescription, beanName, ctorArgIndex, ctorArgType, (ex != null ? ": " + ex.getMessage() : "")); + initCause(ex); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/package.html 17 Aug 2012 15:11:37 -0000 1.1 @@ -0,0 +1,15 @@ + + + +The core package implementing Spring's lightweight Inversion of Control (IoC) container. +

    +Provides an alternative to the Singleton and Prototype design +patterns, including a consistent approach to configuration management. +Builds on the org.springframework.beans package. + +

    This package and related packages are discussed in Chapter 11 of +Expert One-On-One J2EE Design and Development +by Rod Johnson (Wrox, 2002). + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/access/BeanFactoryLocator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/access/BeanFactoryLocator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/access/BeanFactoryLocator.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.access; + +import org.springframework.beans.BeansException; + +/** + * Defines a contract for the lookup, use, and release of a + * {@link org.springframework.beans.factory.BeanFactory}, + * or a BeanFactory subclass such as an + * {@link org.springframework.context.ApplicationContext}. + * + *

    Where this interface is implemented as a singleton class such as + * {@link SingletonBeanFactoryLocator}, the Spring team strongly + * suggests that it be used sparingly and with caution. By far the vast majority + * of the code inside an application is best written in a Dependency Injection + * style, where that code is served out of a + * BeanFactory/ApplicationContext container, and has + * its own dependencies supplied by the container when it is created. However, + * even such a singleton implementation sometimes has its use in the small glue + * layers of code that is sometimes needed to tie other code together. For + * example, third party code may try to construct new objects directly, without + * the ability to force it to get these objects out of a BeanFactory. + * If the object constructed by the third party code is just a small stub or + * proxy, which then uses an implementation of this class to get a + * BeanFactory from which it gets the real object, to which it + * delegates, then proper Dependency Injection has been achieved. + * + *

    As another example, in a complex J2EE app with multiple layers, with each + * layer having its own ApplicationContext definition (in a + * hierarchy), a class like SingletonBeanFactoryLocator may be used + * to demand load these contexts. + * + * @author Colin Sampaleanu + * @see org.springframework.beans.factory.BeanFactory + * @see org.springframework.context.access.DefaultLocatorFactory + * @see org.springframework.context.ApplicationContext + */ +public interface BeanFactoryLocator { + + /** + * Use the {@link org.springframework.beans.factory.BeanFactory} (or derived + * interface such as {@link org.springframework.context.ApplicationContext}) + * specified by the factoryKey parameter. + *

    The definition is possibly loaded/created as needed. + * @param factoryKey a resource name specifying which BeanFactory the + * BeanFactoryLocator must return for usage. The actual meaning of the + * resource name is specific to the implementation of BeanFactoryLocator. + * @return the BeanFactory instance, wrapped as a {@link BeanFactoryReference} object + * @throws BeansException if there is an error loading or accessing the BeanFactory + */ + BeanFactoryReference useBeanFactory(String factoryKey) throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/access/BeanFactoryReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/access/BeanFactoryReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/access/BeanFactoryReference.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.access; + +import org.springframework.beans.FatalBeanException; +import org.springframework.beans.factory.BeanFactory; + +/** + * Used to track a reference to a {@link BeanFactory} obtained through + * a {@link BeanFactoryLocator}. + * + *

    It is safe to call {@link #release()} multiple times, but + * {@link #getFactory()} must not be called after calling release. + * + * @author Colin Sampaleanu + * @see BeanFactoryLocator + * @see org.springframework.context.access.ContextBeanFactoryReference + */ +public interface BeanFactoryReference { + + /** + * Return the {@link BeanFactory} instance held by this reference. + * @throws IllegalStateException if invoked after release() has been called + */ + BeanFactory getFactory(); + + /** + * Indicate that the {@link BeanFactory} instance referred to by this object is not + * needed any longer by the client code which obtained the {@link BeanFactoryReference}. + *

    Depending on the actual implementation of {@link BeanFactoryLocator}, and + * the actual type of BeanFactory, this may possibly not actually + * do anything; alternately in the case of a 'closeable' BeanFactory + * or derived class (such as {@link org.springframework.context.ApplicationContext}) + * may 'close' it, or may 'close' it once no more references remain. + *

    In an EJB usage scenario this would normally be called from + * ejbRemove() and ejbPassivate(). + *

    This is safe to call multiple times. + * @throws FatalBeanException if the BeanFactory cannot be released + * @see BeanFactoryLocator + * @see org.springframework.context.access.ContextBeanFactoryReference + * @see org.springframework.context.ConfigurableApplicationContext#close() + */ + void release() throws FatalBeanException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/access/BootstrapException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/access/BootstrapException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/access/BootstrapException.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.access; + +import org.springframework.beans.FatalBeanException; + +/** + * Exception thrown if a bean factory could not be loaded by a bootstrap class. + * + * @author Rod Johnson + * @since 02.12.2002 + */ +public class BootstrapException extends FatalBeanException { + + /** + * Create a new BootstrapException with the specified message. + * @param msg the detail message + */ + public BootstrapException(String msg) { + super(msg); + } + + /** + * Create a new BootstrapException with the specified message + * and root cause. + * @param msg the detail message + * @param cause the root cause + */ + public BootstrapException(String msg, Throwable cause) { + super(msg, cause); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/access/SingletonBeanFactoryLocator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/access/SingletonBeanFactoryLocator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/access/SingletonBeanFactoryLocator.java 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,540 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.access; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.BeansException; +import org.springframework.beans.FatalBeanException; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternUtils; + +/** + *

    Keyed-singleton implementation of {@link BeanFactoryLocator}, + * which accesses shared Spring {@link BeanFactory} instances.

    + * + *

    Please see the warning in BeanFactoryLocator's javadoc about appropriate usage + * of singleton style BeanFactoryLocator implementations. It is the opinion of the + * Spring team that the use of this class and similar classes is unnecessary except + * (sometimes) for a small amount of glue code. Excessive usage will lead to code + * that is more tightly coupled, and harder to modify or test.

    + * + *

    In this implementation, a BeanFactory is built up from one or more XML + * definition file fragments, accessed as resources. The default resource name + * searched for is 'classpath*:beanRefFactory.xml', with the Spring-standard + * 'classpath*:' prefix ensuring that if the classpath contains multiple copies + * of this file (perhaps one in each component jar) they will be combined. To + * override the default resource name, instead of using the no-arg + * {@link #getInstance()} method, use the {@link #getInstance(String selector)} + * variant, which will treat the 'selector' argument as the resource name to + * search for.

    + * + *

    The purpose of this 'outer' BeanFactory is to create and hold a copy of one + * or more 'inner' BeanFactory or ApplicationContext instances, and allow those + * to be obtained either directly or via an alias. As such, this class provides + * both singleton style access to one or more BeanFactories/ApplicationContexts, + * and also a level of indirection, allowing multiple pieces of code, which are + * not able to work in a Dependency Injection fashion, to refer to and use the + * same target BeanFactory/ApplicationContext instance(s), by different names.

    + * + *

    Consider an example application scenario: + * + *

      + *
    • com.mycompany.myapp.util.applicationContext.xml - + * ApplicationContext definition file which defines beans for 'util' layer. + *
    • com.mycompany.myapp.dataaccess-applicationContext.xml - + * ApplicationContext definition file which defines beans for 'data access' layer. + * Depends on the above. + *
    • com.mycompany.myapp.services.applicationContext.xml - + * ApplicationContext definition file which defines beans for 'services' layer. + * Depends on the above. + *
    + * + *

    In an ideal scenario, these would be combined to create one ApplicationContext, + * or created as three hierarchical ApplicationContexts, by one piece of code + * somewhere at application startup (perhaps a Servlet filter), from which all other + * code in the application would flow, obtained as beans from the context(s). However + * when third party code enters into the picture, things can get problematic. If the + * third party code needs to create user classes, which should normally be obtained + * from a Spring BeanFactory/ApplicationContext, but can handle only newInstance() + * style object creation, then some extra work is required to actually access and + * use object from a BeanFactory/ApplicationContext. One solutions is to make the + * class created by the third party code be just a stub or proxy, which gets the + * real object from a BeanFactory/ApplicationContext, and delegates to it. However, + * it is is not normally workable for the stub to create the BeanFactory on each + * use, as depending on what is inside it, that can be an expensive operation. + * Additionally, there is a fairly tight coupling between the stub and the name of + * the definition resource for the BeanFactory/ApplicationContext. This is where + * SingletonBeanFactoryLocator comes in. The stub can obtain a + * SingletonBeanFactoryLocator instance, which is effectively a singleton, and + * ask it for an appropriate BeanFactory. A subsequent invocation (assuming the + * same class loader is involved) by the stub or another piece of code, will obtain + * the same instance. The simple aliasing mechanism allows the context to be asked + * for by a name which is appropriate for (or describes) the user. The deployer can + * match alias names to actual context names. + * + *

    Another use of SingletonBeanFactoryLocator, is to demand-load/use one or more + * BeanFactories/ApplicationContexts. Because the definition can contain one of more + * BeanFactories/ApplicationContexts, which can be independent or in a hierarchy, if + * they are set to lazy-initialize, they will only be created when actually requested + * for use. + * + *

    Given the above-mentioned three ApplicationContexts, consider the simplest + * SingletonBeanFactoryLocator usage scenario, where there is only one single + * beanRefFactory.xml definition file: + * + *

    <?xml version="1.0" encoding="UTF-8"?>
    + * <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
    + * 
    + * <beans>
    + * 
    + *   <bean id="com.mycompany.myapp"
    + *         class="org.springframework.context.support.ClassPathXmlApplicationContext">
    + *     <constructor-arg>
    + *       <list>
    + *         <value>com/mycompany/myapp/util/applicationContext.xml</value>
    + *         <value>com/mycompany/myapp/dataaccess/applicationContext.xml</value>
    + *         <value>com/mycompany/myapp/dataaccess/services.xml</value>
    + *       </list>
    + *     </constructor-arg>
    + *   </bean>
    + * 
    + * </beans>
    + * 
    + * + * The client code is as simple as: + * + *
    + * BeanFactoryLocator bfl = SingletonBeanFactoryLocator.getInstance();
    + * BeanFactoryReference bf = bfl.useBeanFactory("com.mycompany.myapp");
    + * // now use some bean from factory 
    + * MyClass zed = bf.getFactory().getBean("mybean");
    + * 
    + * + * Another relatively simple variation of the beanRefFactory.xml definition file could be: + * + *
    <?xml version="1.0" encoding="UTF-8"?>
    + * <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
    + * 
    + * <beans>
    + * 
    + *   <bean id="com.mycompany.myapp.util" lazy-init="true"
    + *         class="org.springframework.context.support.ClassPathXmlApplicationContext">
    + *     <constructor-arg>
    + *       <value>com/mycompany/myapp/util/applicationContext.xml</value>
    + *     </constructor-arg>
    + *   </bean>
    + * 
    + *   <!-- child of above -->
    + *   <bean id="com.mycompany.myapp.dataaccess" lazy-init="true"
    + *         class="org.springframework.context.support.ClassPathXmlApplicationContext">
    + *     <constructor-arg>
    + *       <list><value>com/mycompany/myapp/dataaccess/applicationContext.xml</value></list>
    + *     </constructor-arg>
    + *     <constructor-arg>
    + *       <ref bean="com.mycompany.myapp.util"/>
    + *     </constructor-arg>
    + *   </bean>
    + * 
    + *   <!-- child of above -->
    + *   <bean id="com.mycompany.myapp.services" lazy-init="true"
    + *         class="org.springframework.context.support.ClassPathXmlApplicationContext">
    + *     <constructor-arg>
    + *       <list><value>com/mycompany/myapp/dataaccess.services.xml</value></value>
    + *     </constructor-arg>
    + *     <constructor-arg>
    + *       <ref bean="com.mycompany.myapp.dataaccess"/>
    + *     </constructor-arg>
    + *   </bean>
    + * 
    + *   <!-- define an alias -->
    + *   <bean id="com.mycompany.myapp.mypackage"
    + *         class="java.lang.String">
    + *     <constructor-arg>
    + *       <value>com.mycompany.myapp.services</value>
    + *     </constructor-arg>
    + *   </bean>
    + * 
    + * </beans>
    + * 
    + * + *

    In this example, there is a hierarchy of three contexts created. The (potential) + * advantage is that if the lazy flag is set to true, a context will only be created + * if it's actually used. If there is some code that is only needed some of the time, + * this mechanism can save some resources. Additionally, an alias to the last context + * has been created. Aliases allow usage of the idiom where client code asks for a + * context with an id which represents the package or module the code is in, and the + * actual definition file(s) for the SingletonBeanFactoryLocator maps that id to + * a real context id. + * + *

    A final example is more complex, with a beanRefFactory.xml for every module. + * All the files are automatically combined to create the final definition. + * + *

    beanRefFactory.xml file inside jar for util module: + * + *

    <?xml version="1.0" encoding="UTF-8"?>
    + * <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
    + * 
    + * <beans>
    + *   <bean id="com.mycompany.myapp.util" lazy-init="true"
    + *        class="org.springframework.context.support.ClassPathXmlApplicationContext">
    + *     <constructor-arg>
    + *       <value>com/mycompany/myapp/util/applicationContext.xml</value>
    + *     </constructor-arg>
    + *   </bean>
    + * </beans>
    + * 
    + * + * beanRefFactory.xml file inside jar for data-access module:
    + * + *
    <?xml version="1.0" encoding="UTF-8"?>
    + * <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
    + * 
    + * <beans>
    + *   <!-- child of util -->
    + *   <bean id="com.mycompany.myapp.dataaccess" lazy-init="true"
    + *        class="org.springframework.context.support.ClassPathXmlApplicationContext">
    + *     <constructor-arg>
    + *       <list><value>com/mycompany/myapp/dataaccess/applicationContext.xml</value></list>
    + *     </constructor-arg>
    + *     <constructor-arg>
    + *       <ref bean="com.mycompany.myapp.util"/>
    + *     </constructor-arg>
    + *   </bean>
    + * </beans>
    + * 
    + * + * beanRefFactory.xml file inside jar for services module: + * + *
    <?xml version="1.0" encoding="UTF-8"?>
    + * <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
    + * 
    + * <beans>
    + *   <!-- child of data-access -->
    + *   <bean id="com.mycompany.myapp.services" lazy-init="true"
    + *        class="org.springframework.context.support.ClassPathXmlApplicationContext">
    + *     <constructor-arg>
    + *       <list><value>com/mycompany/myapp/dataaccess/services.xml</value></list>
    + *     </constructor-arg>
    + *     <constructor-arg>
    + *       <ref bean="com.mycompany.myapp.dataaccess"/>
    + *     </constructor-arg>
    + *   </bean>
    + * </beans>
    + * 
    + * + * beanRefFactory.xml file inside jar for mypackage module. This doesn't + * create any of its own contexts, but allows the other ones to be referred to be + * a name known to this module: + * + *
    <?xml version="1.0" encoding="UTF-8"?>
    + * <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
    + * 
    + * <beans>
    + *   <!-- define an alias for "com.mycompany.myapp.services" -->
    + *   <alias name="com.mycompany.myapp.services" alias="com.mycompany.myapp.mypackage"/>
    + * </beans>
    + * 
    + * + * @author Colin Sampaleanu + * @author Juergen Hoeller + * @see org.springframework.context.access.ContextSingletonBeanFactoryLocator + * @see org.springframework.context.access.DefaultLocatorFactory + */ +public class SingletonBeanFactoryLocator implements BeanFactoryLocator { + + private static final String DEFAULT_RESOURCE_LOCATION = "classpath*:beanRefFactory.xml"; + + protected static final Log logger = LogFactory.getLog(SingletonBeanFactoryLocator.class); + + /** The keyed BeanFactory instances */ + private static Map instances = new HashMap(); + + + /** + * Returns an instance which uses the default "classpath*:beanRefFactory.xml", + * as the name of the definition file(s). All resources returned by calling the + * current thread context ClassLoader's getResources method with + * this name will be combined to create a BeanFactory definition set. + * @return the corresponding BeanFactoryLocator instance + * @throws BeansException in case of factory loading failure + */ + public static BeanFactoryLocator getInstance() throws BeansException { + return getInstance(null); + } + + /** + * Returns an instance which uses the the specified selector, as the name of the + * definition file(s). In the case of a name with a Spring 'classpath*:' prefix, + * or with no prefix, which is treated the same, the current thread context + * ClassLoader's getResources method will be called with this value + * to get all resources having that name. These resources will then be combined to + * form a definition. In the case where the name uses a Spring 'classpath:' prefix, + * or a standard URL prefix, then only one resource file will be loaded as the + * definition. + * @param selector the name of the resource(s) which will be read and + * combined to form the definition for the BeanFactoryLocator instance. + * Any such files must form a valid BeanFactory definition. + * @return the corresponding BeanFactoryLocator instance + * @throws BeansException in case of factory loading failure + */ + public static BeanFactoryLocator getInstance(String selector) throws BeansException { + String resourceLocation = selector; + if (resourceLocation == null) { + resourceLocation = DEFAULT_RESOURCE_LOCATION; + } + + // For backwards compatibility, we prepend 'classpath*:' to the selector name if there + // is no other prefix (i.e. classpath*:, classpath:, or some URL prefix. + if (!ResourcePatternUtils.isUrl(resourceLocation)) { + resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation; + } + + synchronized (instances) { + if (logger.isTraceEnabled()) { + logger.trace("SingletonBeanFactoryLocator.getInstance(): instances.hashCode=" + + instances.hashCode() + ", instances=" + instances); + } + BeanFactoryLocator bfl = (BeanFactoryLocator) instances.get(resourceLocation); + if (bfl == null) { + bfl = new SingletonBeanFactoryLocator(resourceLocation); + instances.put(resourceLocation, bfl); + } + return bfl; + } + } + + + // We map BeanFactoryGroup objects by String keys, and by the definition object. + private final Map bfgInstancesByKey = new HashMap(); + + private final Map bfgInstancesByObj = new HashMap(); + + private final String resourceLocation; + + + /** + * Constructor which uses the the specified name as the resource name + * of the definition file(s). + * @param resourceLocation the Spring resource location to use + * (either a URL or a "classpath:" / "classpath*:" pseudo URL) + */ + protected SingletonBeanFactoryLocator(String resourceLocation) { + this.resourceLocation = resourceLocation; + } + + public BeanFactoryReference useBeanFactory(String factoryKey) throws BeansException { + synchronized (this.bfgInstancesByKey) { + BeanFactoryGroup bfg = (BeanFactoryGroup) this.bfgInstancesByKey.get(this.resourceLocation); + + if (bfg != null) { + bfg.refCount++; + } + else { + // This group definition doesn't exist, we need to try to load it. + if (logger.isTraceEnabled()) { + logger.trace("Factory group with resource name [" + this.resourceLocation + + "] requested. Creating new instance."); + } + + // Create the BeanFactory but don't initialize it. + BeanFactory groupContext = createDefinition(this.resourceLocation, factoryKey); + + // Record its existence now, before instantiating any singletons. + bfg = new BeanFactoryGroup(); + bfg.definition = groupContext; + bfg.refCount = 1; + this.bfgInstancesByKey.put(this.resourceLocation, bfg); + this.bfgInstancesByObj.put(groupContext, bfg); + + // Now initialize the BeanFactory. This may cause a re-entrant invocation + // of this method, but since we've already added the BeanFactory to our + // mappings, the next time it will be found and simply have its + // reference count incremented. + try { + initializeDefinition(groupContext); + } + catch (BeansException ex) { + this.bfgInstancesByKey.remove(this.resourceLocation); + this.bfgInstancesByObj.remove(groupContext); + throw new BootstrapException("Unable to initialize group definition. " + + "Group resource name [" + this.resourceLocation + "], factory key [" + factoryKey + "]", ex); + } + } + + try { + BeanFactory beanFactory = null; + if (factoryKey != null) { + beanFactory = (BeanFactory) bfg.definition.getBean(factoryKey, BeanFactory.class); + } + else if (bfg.definition instanceof ListableBeanFactory) { + beanFactory = (BeanFactory) + BeanFactoryUtils.beanOfType((ListableBeanFactory) bfg.definition, BeanFactory.class); + } + else { + throw new IllegalStateException( + "Factory key is null, and underlying factory is not a ListableBeanFactory: " + bfg.definition); + } + return new CountingBeanFactoryReference(beanFactory, bfg.definition); + } + catch (BeansException ex) { + throw new BootstrapException("Unable to return specified BeanFactory instance: factory key [" + + factoryKey + "], from group with resource name [" + this.resourceLocation + "]", ex); + } + + } + } + + /** + * Actually creates definition in the form of a BeanFactory, given a resource name + * which supports standard Spring resource prefixes ('classpath:', 'classpath*:', etc.) + * This is split out as a separate method so that subclasses can override the actual + * type used (to be an ApplicationContext, for example). + *

    The default implementation simply builds a + * {@link org.springframework.beans.factory.support.DefaultListableBeanFactory} + * and populates it using an + * {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}. + *

    This method should not instantiate any singletons. That function is performed + * by {@link #initializeDefinition initializeDefinition()}, which should also be + * overridden if this method is. + * @param resourceLocation the resource location for this factory group + * @param factoryKey the bean name of the factory to obtain + * @return the corresponding BeanFactory reference + */ + protected BeanFactory createDefinition(String resourceLocation, String factoryKey) { + DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); + XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); + ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); + + try { + Resource[] configResources = resourcePatternResolver.getResources(resourceLocation); + if (configResources.length == 0) { + throw new FatalBeanException("Unable to find resource for specified definition. " + + "Group resource name [" + this.resourceLocation + "], factory key [" + factoryKey + "]"); + } + reader.loadBeanDefinitions(configResources); + } + catch (IOException ex) { + throw new BeanDefinitionStoreException( + "Error accessing bean definition resource [" + this.resourceLocation + "]", ex); + } + catch (BeanDefinitionStoreException ex) { + throw new FatalBeanException("Unable to load group definition: " + + "group resource name [" + this.resourceLocation + "], factory key [" + factoryKey + "]", ex); + } + + return factory; + } + + /** + * Instantiate singletons and do any other normal initialization of the factory. + * Subclasses that override {@link #createDefinition createDefinition()} should + * also override this method. + * @param groupDef the factory returned by {@link #createDefinition createDefinition()} + */ + protected void initializeDefinition(BeanFactory groupDef) { + if (groupDef instanceof ConfigurableListableBeanFactory) { + ((ConfigurableListableBeanFactory) groupDef).preInstantiateSingletons(); + } + } + + /** + * Destroy definition in separate method so subclass may work with other definition types. + * @param groupDef the factory returned by {@link #createDefinition createDefinition()} + * @param selector the resource location for this factory group + */ + protected void destroyDefinition(BeanFactory groupDef, String selector) { + if (groupDef instanceof ConfigurableBeanFactory) { + if (logger.isTraceEnabled()) { + logger.trace("Factory group with selector '" + selector + + "' being released, as there are no more references to it"); + } + ((ConfigurableBeanFactory) groupDef).destroySingletons(); + } + } + + + /** + * We track BeanFactory instances with this class. + */ + private static class BeanFactoryGroup { + + private BeanFactory definition; + + private int refCount = 0; + } + + + /** + * BeanFactoryReference implementation for this locator. + */ + private class CountingBeanFactoryReference implements BeanFactoryReference { + + private BeanFactory beanFactory; + + private BeanFactory groupContextRef; + + public CountingBeanFactoryReference(BeanFactory beanFactory, BeanFactory groupContext) { + this.beanFactory = beanFactory; + this.groupContextRef = groupContext; + } + + public BeanFactory getFactory() { + return this.beanFactory; + } + + // Note that it's legal to call release more than once! + public void release() throws FatalBeanException { + synchronized (bfgInstancesByKey) { + BeanFactory savedRef = this.groupContextRef; + if (savedRef != null) { + this.groupContextRef = null; + BeanFactoryGroup bfg = (BeanFactoryGroup) bfgInstancesByObj.get(savedRef); + if (bfg != null) { + bfg.refCount--; + if (bfg.refCount == 0) { + destroyDefinition(savedRef, resourceLocation); + bfgInstancesByKey.remove(resourceLocation); + bfgInstancesByObj.remove(savedRef); + } + } + else { + // This should be impossible. + logger.warn("Tried to release a SingletonBeanFactoryLocator group definition " + + "more times than it has actually been used. Resource name [" + resourceLocation + "]"); + } + } + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/access/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/access/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/access/package.html 17 Aug 2012 15:11:42 -0000 1.1 @@ -0,0 +1,11 @@ + + + +Helper infrastructure to locate and access bean factories. + +

    Note: This package is only relevant for special sharing of bean +factories, for example behind EJB facades. It is not used in a +typical web application or standalone application. + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/access/el/SimpleSpringBeanELResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/access/el/SimpleSpringBeanELResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/access/el/SimpleSpringBeanELResolver.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.access.el; + +import javax.el.ELContext; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.util.Assert; + +/** + * Simple concrete variant of {@link SpringBeanELResolver}, delegating + * to a given {@link BeanFactory} that the resolver was constructed with. + * + * @author Juergen Hoeller + * @since 2.5.2 + */ +public class SimpleSpringBeanELResolver extends SpringBeanELResolver { + + private final BeanFactory beanFactory; + + + /** + * Create a new SimpleSpringBeanELResolver for the given BeanFactory. + * @param beanFactory the Spring BeanFactory to delegate to + */ + public SimpleSpringBeanELResolver(BeanFactory beanFactory) { + Assert.notNull(beanFactory, "BeanFactory must not be null"); + this.beanFactory = beanFactory; + } + + protected BeanFactory getBeanFactory(ELContext elContext) { + return this.beanFactory; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/access/el/SpringBeanELResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/access/el/SpringBeanELResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/access/el/SpringBeanELResolver.java 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,111 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.access.el; + +import java.beans.FeatureDescriptor; +import java.util.Iterator; + +import javax.el.ELContext; +import javax.el.ELException; +import javax.el.ELResolver; +import javax.el.PropertyNotWritableException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.factory.BeanFactory; + +/** + * Unified EL ELResolver that delegates to a Spring BeanFactory, + * resolving name references to Spring-defined beans. + * + * @author Juergen Hoeller + * @since 2.5.2 + * @see org.springframework.web.jsf.el.SpringBeanFacesELResolver + */ +public abstract class SpringBeanELResolver extends ELResolver { + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + + public Object getValue(ELContext elContext, Object base, Object property) throws ELException { + if (base == null) { + String beanName = property.toString(); + BeanFactory bf = getBeanFactory(elContext); + if (bf.containsBean(beanName)) { + if (logger.isTraceEnabled()) { + logger.trace("Successfully resolved variable '" + beanName + "' in Spring BeanFactory"); + } + elContext.setPropertyResolved(true); + return bf.getBean(beanName); + } + } + return null; + } + + public Class getType(ELContext elContext, Object base, Object property) throws ELException { + if (base == null) { + String beanName = property.toString(); + BeanFactory bf = getBeanFactory(elContext); + if (bf.containsBean(beanName)) { + elContext.setPropertyResolved(true); + return bf.getType(beanName); + } + } + return null; + } + + public void setValue(ELContext elContext, Object base, Object property, Object value) throws ELException { + if (base == null) { + String beanName = property.toString(); + BeanFactory bf = getBeanFactory(elContext); + if (bf.containsBean(beanName)) { + throw new PropertyNotWritableException( + "Variable '" + beanName + "' refers to a Spring bean which by definition is not writable"); + } + } + } + + public boolean isReadOnly(ELContext elContext, Object base, Object property) throws ELException { + if (base == null) { + String beanName = property.toString(); + BeanFactory bf = getBeanFactory(elContext); + if (bf.containsBean(beanName)) { + return true; + } + } + return false; + } + + public Iterator getFeatureDescriptors(ELContext elContext, Object base) { + return null; + } + + public Class getCommonPropertyType(ELContext elContext, Object base) { + return Object.class; + } + + + /** + * Retrieve the Spring BeanFactory to delegate bean name resolution to. + * @param elContext the current ELContext + * @return the Spring BeanFactory (never null) + */ + protected abstract BeanFactory getBeanFactory(ELContext elContext); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/access/el/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/access/el/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/access/el/package.html 17 Aug 2012 15:11:40 -0000 1.1 @@ -0,0 +1,7 @@ + + + +Support classes for accessing a Spring BeanFactory from Unified EL. + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/AnnotatedBeanDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/AnnotatedBeanDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/AnnotatedBeanDefinition.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.core.type.AnnotationMetadata; + +/** + * Extended {@link org.springframework.beans.factory.config.BeanDefinition} + * interface that exposes {@link org.springframework.core.type.AnnotationMetadata} + * about its bean class - without requiring the class to be loaded yet. + * + * @author Juergen Hoeller + * @since 2.5 + * @see AnnotatedGenericBeanDefinition + * @see org.springframework.core.type.AnnotationMetadata + */ +public interface AnnotatedBeanDefinition extends BeanDefinition { + + /** + * Obtain the annotation metadata (as well as basic class metadata) + * for this bean definition's bean class. + * @return the annotation metadata object (never null) + */ + AnnotationMetadata getMetadata(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/AnnotatedGenericBeanDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/AnnotatedGenericBeanDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/AnnotatedGenericBeanDefinition.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import org.springframework.beans.factory.support.GenericBeanDefinition; +import org.springframework.core.type.AnnotationMetadata; +import org.springframework.core.type.StandardAnnotationMetadata; + +/** + * Extension of the {@link org.springframework.beans.factory.support.GenericBeanDefinition} + * class, adding support for annotation metadata exposed through the + * {@link AnnotatedBeanDefinition} interface. + * + *

    This GenericBeanDefinition variant is mainly useful for testing code that expects + * to operate on an AnnotatedBeanDefinition, for example strategy implementations + * in Spring's component scanning support (where the default definition class is + * {@link org.springframework.context.annotation.ScannedGenericBeanDefinition}, + * which also implements the AnnotatedBeanDefinition interface). + * + * @author Juergen Hoeller + * @since 2.5 + * @see AnnotatedBeanDefinition#getMetadata() + * @see org.springframework.core.type.StandardAnnotationMetadata + */ +public class AnnotatedGenericBeanDefinition extends GenericBeanDefinition implements AnnotatedBeanDefinition { + + private final AnnotationMetadata annotationMetadata; + + + /** + * Create a new AnnotatedGenericBeanDefinition for the given bean class. + * @param beanClass the loaded bean class + */ + public AnnotatedGenericBeanDefinition(Class beanClass) { + setBeanClass(beanClass); + this.annotationMetadata = new StandardAnnotationMetadata(beanClass); + } + + + public final AnnotationMetadata getMetadata() { + return this.annotationMetadata; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/AnnotationBeanWiringInfoResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/AnnotationBeanWiringInfoResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/AnnotationBeanWiringInfoResolver.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,79 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import org.springframework.beans.factory.wiring.BeanWiringInfo; +import org.springframework.beans.factory.wiring.BeanWiringInfoResolver; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; + +/** + * {@link org.springframework.beans.factory.wiring.BeanWiringInfoResolver} that + * uses the Configurable annotation to identify which classes need autowiring. + * The bean name to look up will be taken from the {@link Configurable} annotation + * if specified; otherwise the default will be the fully-qualified name of the + * class being configured. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see Configurable + * @see org.springframework.beans.factory.wiring.ClassNameBeanWiringInfoResolver + */ +public class AnnotationBeanWiringInfoResolver implements BeanWiringInfoResolver { + + public BeanWiringInfo resolveWiringInfo(Object beanInstance) { + Assert.notNull(beanInstance, "Bean instance must not be null"); + Configurable annotation = beanInstance.getClass().getAnnotation(Configurable.class); + return (annotation != null ? buildWiringInfo(beanInstance, annotation) : null); + } + + /** + * Build the BeanWiringInfo for the given Configurable annotation. + * @param beanInstance the bean instance + * @param annotation the Configurable annotation found on the bean class + * @return the resolved BeanWiringInfo + */ + protected BeanWiringInfo buildWiringInfo(Object beanInstance, Configurable annotation) { + if (!Autowire.NO.equals(annotation.autowire())) { + return new BeanWiringInfo(annotation.autowire().value(), annotation.dependencyCheck()); + } + else { + if (!"".equals(annotation.value())) { + // explicitly specified bean name + return new BeanWiringInfo(annotation.value(), false); + } + else { + // default bean name + return new BeanWiringInfo(getDefaultBeanName(beanInstance), true); + } + } + } + + /** + * Determine the default bean name for the specified bean instance. + *

    The default implementation returns the superclass name for a CGLIB + * proxy and the name of the plain bean class else. + * @param beanInstance the bean instance to build a default name for + * @return the default bean name to use + * @see org.springframework.util.ClassUtils#getUserClass(Class) + */ + protected String getDefaultBeanName(Object beanInstance) { + return ClassUtils.getUserClass(beanInstance).getName(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/Autowire.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/Autowire.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/Autowire.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; + +/** + * Enumeration determining autowiring status: that is, whether a bean should + * have its dependencies automatically injected by the Spring container using + * setter injection. This is a core concept in Spring DI. + * + *

    Available for use in annotation-based configurations, such as for the + * AspectJ AnnotationBeanConfigurer aspect. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see org.springframework.beans.factory.annotation.Configurable + * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory + */ +public enum Autowire { + + /** + * Constant that indicates that autowiring information was not specified. + * In some cases it may be necessary to specify autowiring status, + * but merely confirm that this should be inherited from an enclosing + * container definition scope. + */ + INHERITED(-1), + + /** + * Constant that indicates no autowiring at all. + */ + NO(AutowireCapableBeanFactory.AUTOWIRE_NO), + + /** + * Constant that indicates autowiring bean properties by name. + */ + BY_NAME(AutowireCapableBeanFactory.AUTOWIRE_BY_NAME), + + /** + * Constant that indicates autowiring bean properties by type. + */ + BY_TYPE(AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE); + + + private final int value; + + + Autowire(int value) { + this.value = value; + } + + public int value() { + return this.value; + } + + /** + * Return whether this represents an actual autowiring value. + * @return whether actual autowiring was specified + * (either BY_NAME or BY_TYPE) + */ + public boolean isAutowire() { + return (this == BY_NAME || this == BY_TYPE); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/Autowired.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/Autowired.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/Autowired.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Marks a constructor, field, setter method or config method as to be + * autowired by Spring's dependency injection facilities. + * + *

    Only one constructor (at max) of any given bean class may carry this + * annotation, indicating the constructor to autowire when used as a Spring + * bean. Such a constructor does not have to be public. + * + *

    Fields are injected right after construction of a bean, before any + * config methods are invoked. Such a config field does not have to be public. + * + *

    Config methods may have an arbitrary name and any number of arguments; + * each of those arguments will be autowired with a matching bean in the + * Spring container. Bean property setter methods are effectively just + * a special case of such a general config method. Such config methods + * do not have to be public. + * + *

    In the case of multiple argument methods, the 'required' parameter is + * applicable for all arguments. + * + *

    In case of a {@link java.util.Collection} or {@link java.util.Map} + * dependency type, the container will autowire all beans matching the + * declared value type. In case of a Map, the keys must be declared as + * type String and will be resolved to the corresponding bean names. + * + *

    Please do consult the javadoc for the {@link AutowiredAnnotationBeanPostProcessor} + * class (which, by default, checks for the presence of this annotation). + * + * @author Juergen Hoeller + * @author Mark Fisher + * @since 2.5 + * @see AutowiredAnnotationBeanPostProcessor + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD}) +public @interface Autowired { + + /** + * Declares whether the annotated dependency is required. + *

    Defaults to true. + */ + boolean required() default true; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,548 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import java.beans.PropertyDescriptor; +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.PropertyValues; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.config.DependencyDescriptor; +import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; +import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.core.GenericTypeResolver; +import org.springframework.core.MethodParameter; +import org.springframework.core.Ordered; +import org.springframework.core.PriorityOrdered; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; + +/** + * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation + * that autowires annotated fields, setter methods and arbitrary config methods. + * Such members to be injected are detected through a Java 5 annotation: + * by default, Spring's {@link Autowired} annotation. + * + *

    Only one constructor (at max) of any given bean class may carry this + * annotation with the 'required' parameter set to true, + * indicating the constructor to autowire when used as a Spring bean. + * If multiple non-required constructors carry the annotation, they + * will be considered as candidates for autowiring. The constructor with + * the greatest number of dependencies that can be satisfied by matching + * beans in the Spring container will be chosen. If none of the candidates + * can be satisfied, then a default constructor (if present) will be used. + * An annotated constructor does not have to be public. + * + *

    Fields are injected right after construction of a bean, before any + * config methods are invoked. Such a config field does not have to be public. + * + *

    Config methods may have an arbitrary name and any number of arguments; + * each of those arguments will be autowired with a matching bean in the + * Spring container. Bean property setter methods are effectively just + * a special case of such a general config method. Such config methods + * do not have to be public. + * + *

    Note: A default AutowiredAnnotationBeanPostProcessor will be registered + * by the "context:annotation-config" and "context:component-scan" XML tags. + * Remove or turn off the default annotation configuration there if you intend + * to specify a custom AutowiredAnnotationBeanPostProcessor bean definition. + * + * @author Juergen Hoeller + * @author Mark Fisher + * @since 2.5 + * @see #setAutowiredAnnotationType + * @see Autowired + * @see org.springframework.context.annotation.CommonAnnotationBeanPostProcessor + */ +public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter + implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware { + + protected final Log logger = LogFactory.getLog(AutowiredAnnotationBeanPostProcessor.class); + + private Class autowiredAnnotationType = Autowired.class; + + private String requiredParameterName = "required"; + + private boolean requiredParameterValue = true; + + private int order = Ordered.LOWEST_PRECEDENCE - 2; + + private ConfigurableListableBeanFactory beanFactory; + + private final Map, Constructor[]> candidateConstructorsCache = + new ConcurrentHashMap, Constructor[]>(); + + private final Map, InjectionMetadata> injectionMetadataCache = + new ConcurrentHashMap, InjectionMetadata>(); + + + /** + * Set the 'autowired' annotation type, to be used on constructors, fields, + * setter methods and arbitrary config methods. + *

    The default autowired annotation type is the Spring-provided + * {@link Autowired} annotation. + *

    This setter property exists so that developers can provide their own + * (non-Spring-specific) annotation type to indicate that a member is + * supposed to be autowired. + */ + public void setAutowiredAnnotationType(Class autowiredAnnotationType) { + Assert.notNull(autowiredAnnotationType, "'autowiredAnnotationType' must not be null"); + this.autowiredAnnotationType = autowiredAnnotationType; + } + + /** + * Return the 'autowired' annotation type. + */ + protected Class getAutowiredAnnotationType() { + return this.autowiredAnnotationType; + } + + /** + * Set the name of a parameter of the annotation that specifies + * whether it is required. + * @see #setRequiredParameterValue(boolean) + */ + public void setRequiredParameterName(String requiredParameterName) { + this.requiredParameterName = requiredParameterName; + } + + /** + * Set the boolean value that marks a dependency as required + *

    For example if using 'required=true' (the default), + * this value should be true; but if using + * 'optional=false', this value should be false. + * @see #setRequiredParameterName(String) + */ + public void setRequiredParameterValue(boolean requiredParameterValue) { + this.requiredParameterValue = requiredParameterValue; + } + + public void setOrder(int order) { + this.order = order; + } + + public int getOrder() { + return this.order; + } + + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { + throw new IllegalArgumentException( + "AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory"); + } + this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; + } + + + public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) { + if (beanType != null) { + InjectionMetadata metadata = findAutowiringMetadata(beanType); + metadata.checkConfigMembers(beanDefinition); + } + } + + public Constructor[] determineCandidateConstructors(Class beanClass, String beanName) throws BeansException { + // Quick check on the concurrent map first, with minimal locking. + Constructor[] candidateConstructors = this.candidateConstructorsCache.get(beanClass); + if (candidateConstructors == null) { + synchronized (this.candidateConstructorsCache) { + candidateConstructors = this.candidateConstructorsCache.get(beanClass); + if (candidateConstructors == null) { + Constructor[] rawCandidates = beanClass.getDeclaredConstructors(); + List candidates = new ArrayList(rawCandidates.length); + Constructor requiredConstructor = null; + Constructor defaultConstructor = null; + for (int i = 0; i < rawCandidates.length; i++) { + Constructor candidate = rawCandidates[i]; + Annotation annotation = candidate.getAnnotation(getAutowiredAnnotationType()); + if (annotation != null) { + if (requiredConstructor != null) { + throw new BeanCreationException("Invalid autowire-marked constructor: " + candidate + + ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor); + } + if (candidate.getParameterTypes().length == 0) { + throw new IllegalStateException("Autowired annotation requires at least one argument: " + candidate); + } + boolean required = determineRequiredStatus(annotation); + if (required) { + if (!candidates.isEmpty()) { + throw new BeanCreationException("Invalid autowire-marked constructors: " + candidates + + ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor); + } + requiredConstructor = candidate; + } + candidates.add(candidate); + } + else if (candidate.getParameterTypes().length == 0) { + defaultConstructor = candidate; + } + } + if (!candidates.isEmpty()) { + // Add default constructor to list of optional constructors, as fallback. + if (requiredConstructor == null && defaultConstructor != null) { + candidates.add(defaultConstructor); + } + candidateConstructors = (Constructor[]) candidates.toArray(new Constructor[candidates.size()]); + } + else { + candidateConstructors = new Constructor[0]; + } + this.candidateConstructorsCache.put(beanClass, candidateConstructors); + } + } + } + return (candidateConstructors.length > 0 ? candidateConstructors : null); + } + + public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { + InjectionMetadata metadata = findAutowiringMetadata(bean.getClass()); + try { + metadata.injectFields(bean, beanName); + } + catch (Throwable ex) { + throw new BeanCreationException(beanName, "Autowiring of fields failed", ex); + } + return true; + } + + public PropertyValues postProcessPropertyValues( + PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { + + InjectionMetadata metadata = findAutowiringMetadata(bean.getClass()); + try { + metadata.injectMethods(bean, beanName, pvs); + } + catch (Throwable ex) { + throw new BeanCreationException(beanName, "Autowiring of methods failed", ex); + } + return pvs; + } + + /** + * 'Native' processing method for direct calls with an arbitrary target + * instance, resolving all of its fields and methods which are annotated + * with @Autowired. + * @param bean the target instance to process + */ + public void processInjection(Object bean) throws BeansException { + InjectionMetadata metadata = findAutowiringMetadata(bean.getClass()); + try { + metadata.injectFields(bean, null); + metadata.injectMethods(bean, null, null); + } + catch (Throwable ex) { + throw new BeanCreationException("Autowiring of fields/methods failed", ex); + } + } + + + private InjectionMetadata findAutowiringMetadata(final Class clazz) { + // Quick check on the concurrent map first, with minimal locking. + InjectionMetadata metadata = this.injectionMetadataCache.get(clazz); + if (metadata == null) { + synchronized (this.injectionMetadataCache) { + metadata = this.injectionMetadataCache.get(clazz); + if (metadata == null) { + final InjectionMetadata newMetadata = new InjectionMetadata(clazz); + ReflectionUtils.doWithFields(clazz, new ReflectionUtils.FieldCallback() { + public void doWith(Field field) { + Annotation annotation = field.getAnnotation(getAutowiredAnnotationType()); + if (annotation != null) { + if (Modifier.isStatic(field.getModifiers())) { + throw new IllegalStateException("Autowired annotation is not supported on static fields"); + } + boolean required = determineRequiredStatus(annotation); + newMetadata.addInjectedField(new AutowiredFieldElement(field, required)); + } + } + }); + ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() { + public void doWith(Method method) { + Annotation annotation = method.getAnnotation(getAutowiredAnnotationType()); + if (annotation != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { + if (Modifier.isStatic(method.getModifiers())) { + throw new IllegalStateException("Autowired annotation is not supported on static methods"); + } + if (method.getParameterTypes().length == 0) { + throw new IllegalStateException("Autowired annotation requires at least one argument: " + method); + } + boolean required = determineRequiredStatus(annotation); + PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method); + newMetadata.addInjectedMethod(new AutowiredMethodElement(method, required, pd)); + } + } + }); + metadata = newMetadata; + this.injectionMetadataCache.put(clazz, metadata); + } + } + } + return metadata; + } + + /** + * Obtain all beans of the given type as autowire candidates. + * @param type the type of the bean + * @return the target beans, or an empty Collection if no bean of this type is found + * @throws BeansException if bean retrieval failed + */ + protected Map findAutowireCandidates(Class type) throws BeansException { + if (this.beanFactory == null) { + throw new IllegalStateException("No BeanFactory configured - " + + "override the getBeanOfType method or specify the 'beanFactory' property"); + } + return BeanFactoryUtils.beansOfTypeIncludingAncestors(this.beanFactory, type); + } + + /** + * Determine if the annotated field or method requires its dependency. + *

    A 'required' dependency means that autowiring should fail when no beans + * are found. Otherwise, the autowiring process will simply bypass the field + * or method when no beans are found. + * @param annotation the Autowired annotation + * @return whether the annotation indicates that a dependency is required + */ + protected boolean determineRequiredStatus(Annotation annotation) { + try { + Method method = ReflectionUtils.findMethod(annotation.annotationType(), this.requiredParameterName); + return (this.requiredParameterValue == (Boolean) ReflectionUtils.invokeMethod(method, annotation)); + } + catch (Exception ex) { + // required by default + return true; + } + } + + /** + * Register the specified bean as dependent on the autowired beans. + */ + private void registerDependentBeans(String beanName, Set autowiredBeanNames) { + if (beanName != null) { + for (Iterator it = autowiredBeanNames.iterator(); it.hasNext();) { + String autowiredBeanName = (String) it.next(); + beanFactory.registerDependentBean(autowiredBeanName, beanName); + if (logger.isDebugEnabled()) { + logger.debug("Autowiring by type from bean name '" + beanName + + "' to bean named '" + autowiredBeanName + "'"); + } + } + } + } + + + /** + * Class representing injection information about an annotated field. + */ + private class AutowiredFieldElement extends InjectionMetadata.InjectedElement { + + private final boolean required; + + private volatile boolean cached = false; + + private volatile Object cachedFieldValue; + + public AutowiredFieldElement(Field field, boolean required) { + super(field, null); + this.required = required; + } + + @Override + protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable { + Field field = (Field) this.member; + try { + Object value = null; + if (this.cached) { + if (this.cachedFieldValue instanceof DependencyDescriptor) { + DependencyDescriptor descriptor = (DependencyDescriptor) this.cachedFieldValue; + TypeConverter typeConverter = beanFactory.getTypeConverter(); + value = beanFactory.resolveDependency(descriptor, beanName, null, typeConverter); + } + else if (this.cachedFieldValue instanceof RuntimeBeanReference) { + value = beanFactory.getBean(((RuntimeBeanReference) this.cachedFieldValue).getBeanName()); + } + else { + value = this.cachedFieldValue; + } + } + else { + Set autowiredBeanNames = new LinkedHashSet(1); + TypeConverter typeConverter = beanFactory.getTypeConverter(); + DependencyDescriptor descriptor = new DependencyDescriptor(field, this.required); + this.cachedFieldValue = descriptor; + value = beanFactory.resolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter); + if (value != null) { + registerDependentBeans(beanName, autowiredBeanNames); + if (autowiredBeanNames.size() == 1) { + String autowiredBeanName = autowiredBeanNames.iterator().next(); + if (beanFactory.containsBean(autowiredBeanName)) { + if (beanFactory.isTypeMatch(autowiredBeanName, field.getType())) { + this.cachedFieldValue = new RuntimeBeanReference(autowiredBeanName); + } + } + } + } + else { + this.cachedFieldValue = null; + } + this.cached = true; + } + if (value != null) { + ReflectionUtils.makeAccessible(field); + field.set(bean, value); + } + } + catch (Throwable ex) { + throw new BeanCreationException("Could not autowire field: " + field, ex); + } + } + } + + + /** + * Class representing injection information about an annotated method. + */ + private class AutowiredMethodElement extends InjectionMetadata.InjectedElement { + + private final boolean required; + + private volatile boolean cached = false; + + private volatile Object[] cachedMethodArguments; + + public AutowiredMethodElement(Method method, boolean required, PropertyDescriptor pd) { + super(method, pd); + this.required = required; + } + + @Override + protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable { + if (this.skip == null && this.pd != null && pvs != null && pvs.contains(this.pd.getName())) { + // Explicit value provided as part of the bean definition. + this.skip = Boolean.TRUE; + } + if (this.skip != null && this.skip.booleanValue()) { + return; + } + Method method = (Method) this.member; + try { + Object[] arguments = null; + if (this.cached) { + if (this.cachedMethodArguments != null) { + arguments = new Object[this.cachedMethodArguments.length]; + for (int i = 0; i < arguments.length; i++) { + Object cachedArg = this.cachedMethodArguments[i]; + if (cachedArg instanceof DependencyDescriptor) { + DependencyDescriptor descriptor = (DependencyDescriptor) cachedArg; + TypeConverter typeConverter = beanFactory.getTypeConverter(); + arguments[i] = beanFactory.resolveDependency(descriptor, beanName, null, typeConverter); + } + else if (cachedArg instanceof RuntimeBeanReference) { + arguments[i] = beanFactory.getBean(((RuntimeBeanReference) cachedArg).getBeanName()); + } + else { + arguments[i] = cachedArg; + } + } + } + } + else { + Class[] paramTypes = method.getParameterTypes(); + arguments = new Object[paramTypes.length]; + Set autowiredBeanNames = new LinkedHashSet(arguments.length); + TypeConverter typeConverter = beanFactory.getTypeConverter(); + this.cachedMethodArguments = new Object[arguments.length]; + for (int i = 0; i < arguments.length; i++) { + MethodParameter methodParam = new MethodParameter(method, i); + GenericTypeResolver.resolveParameterType(methodParam, bean.getClass()); + DependencyDescriptor descriptor = new DependencyDescriptor(methodParam, this.required); + this.cachedMethodArguments[i] = descriptor; + arguments[i] = beanFactory.resolveDependency( + descriptor, beanName, autowiredBeanNames, typeConverter); + if (arguments[i] == null) { + arguments = null; + break; + } + } + if (arguments != null) { + registerDependentBeans(beanName, autowiredBeanNames); + if (autowiredBeanNames.size() == paramTypes.length) { + Iterator it = autowiredBeanNames.iterator(); + for (int i = 0; i < paramTypes.length; i++) { + String autowiredBeanName = it.next(); + if (beanFactory.containsBean(autowiredBeanName)) { + if (beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) { + this.cachedMethodArguments[i] = new RuntimeBeanReference(autowiredBeanName); + } + } + else { + this.cachedMethodArguments[i] = arguments[i]; + } + } + } + } + else { + this.cachedMethodArguments = null; + } + this.cached = true; + } + if (this.skip == null) { + if (this.pd != null && pvs instanceof MutablePropertyValues) { + ((MutablePropertyValues) pvs).registerProcessedProperty(this.pd.getName()); + } + this.skip = Boolean.FALSE; + } + if (arguments != null) { + ReflectionUtils.makeAccessible(method); + method.invoke(bean, arguments); + } + } + catch (InvocationTargetException ex) { + throw ex.getTargetException(); + } + catch (Throwable ex) { + throw new BeanCreationException("Could not autowire method: " + method, ex); + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/Configurable.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/Configurable.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/Configurable.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import java.lang.annotation.Documented; +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; + +/** + * Marks a class as being eligible for Spring-driven configuration. + * + *

    Typically used with the AspectJ AnnotationBeanConfigurerAspect. + * + * @author Rod Johnson + * @author Rob Harrop + * @author Adrian Colyer + * @author Ramnivas Laddad + * @since 2.0 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Documented +@Inherited +public @interface Configurable { + + /** + * The name of the bean definition that serves as the configuration template. + */ + String value() default ""; + + /** + * Are dependencies to be injected via autowiring? + */ + Autowire autowire() default Autowire.NO; + + /** + * Is dependency checking to be performed for configured objects? + */ + boolean dependencyCheck() default false; + + /** + * Are dependencies to be injected prior to the construction of an object? + */ + boolean preConstruction() default false; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/CustomAutowireConfigurer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/CustomAutowireConfigurer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/CustomAutowireConfigurer.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,122 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import java.lang.annotation.Annotation; +import java.util.Iterator; +import java.util.Set; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.core.Ordered; +import org.springframework.util.ClassUtils; + +/** + * A {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor} + * implementation that allows for convenient registration of custom autowire + * qualifier types. + * + *

    + * <bean id="customAutowireConfigurer" class="org.springframework.beans.factory.annotation.CustomAutowireConfigurer">
    + *   <property name="customQualifierTypes">
    + *     <set>
    + *       <value>mypackage.MyQualifier</value>
    + *     </set>
    + *   </property>
    + * </bean>
    + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + * @see org.springframework.beans.factory.annotation.Qualifier + */ +public class CustomAutowireConfigurer implements BeanFactoryPostProcessor, BeanClassLoaderAware, Ordered { + + private int order = Ordered.LOWEST_PRECEDENCE; // default: same as non-Ordered + + private Set customQualifierTypes; + + private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); + + + public void setOrder(int order) { + this.order = order; + } + + public int getOrder() { + return this.order; + } + + public void setBeanClassLoader(ClassLoader beanClassLoader) { + this.beanClassLoader = beanClassLoader; + } + + /** + * Register custom qualifier annotation types to be considered + * when autowiring beans. Each element of the provided set may + * be either a Class instance or a String representation of the + * fully-qualified class name of the custom annotation. + *

    Note that any annotation that is itself annotated with Spring's + * {@link org.springframework.beans.factory.annotation.Qualifier} + * does not require explicit registration. + * @param customQualifierTypes the custom types to register + */ + public void setCustomQualifierTypes(Set customQualifierTypes) { + this.customQualifierTypes = customQualifierTypes; + } + + + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + if (this.customQualifierTypes != null) { + if (!(beanFactory instanceof DefaultListableBeanFactory)) { + throw new IllegalStateException( + "CustomAutowireConfigurer needs to operate on a DefaultListableBeanFactory"); + } + DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory; + if (!(dlbf.getAutowireCandidateResolver() instanceof QualifierAnnotationAutowireCandidateResolver)) { + throw new IllegalStateException( + "CustomAutowireConfigurer needs to operate on a QualifierAnnotationAutowireCandidateResolver"); + } + QualifierAnnotationAutowireCandidateResolver resolver = + (QualifierAnnotationAutowireCandidateResolver) dlbf.getAutowireCandidateResolver(); + for (Iterator it = this.customQualifierTypes.iterator(); it.hasNext();) { + Class customType = null; + Object value = it.next(); + if (value instanceof Class) { + customType = (Class) value; + } + else if (value instanceof String) { + String className = (String) value; + customType = ClassUtils.resolveClassName(className, this.beanClassLoader); + } + else { + throw new IllegalArgumentException( + "Invalid value [" + value + "] for custom qualifier type: needs to be Class or String."); + } + if (!Annotation.class.isAssignableFrom(customType)) { + throw new IllegalArgumentException( + "Qualifier type [" + customType.getName() + "] needs to be annotation type"); + } + resolver.addQualifierType(customType); + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,310 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import java.io.Serializable; +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; +import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.core.Ordered; +import org.springframework.core.PriorityOrdered; +import org.springframework.util.ReflectionUtils; + +/** + * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation + * that invokes annotated init and destroy methods. Allows for an annotation + * alternative to Spring's {@link org.springframework.beans.factory.InitializingBean} + * and {@link org.springframework.beans.factory.DisposableBean} callback interfaces. + * + *

    The actual annotation types that this post-processor checks for can be + * configured through the {@link #setInitAnnotationType "initAnnotationType"} + * and {@link #setDestroyAnnotationType "destroyAnnotationType"} properties. + * Any custom annotation can be used, since there are no required annotation + * attributes. + * + *

    Init and destroy annotations may be applied to methods of any visibility: + * public, package-protected, protected, or private. Multiple such methods + * may be annotated, but it is recommended to only annotate one single + * init method and destroy method, respectively. + * + *

    Spring's {@link org.springframework.context.annotation.CommonAnnotationBeanPostProcessor} + * supports the JSR-250 {@link javax.annotation.PostConstruct} and {@link javax.annotation.PreDestroy} + * annotations out of the box, as init annotation and destroy annotation, respectively. + * Furthermore, it also supports the {@link javax.annotation.Resource} annotation + * for annotation-driven injection of named beans. + * + * @author Juergen Hoeller + * @since 2.5 + * @see #setInitAnnotationType + * @see #setDestroyAnnotationType + * @see org.springframework.context.annotation.CommonAnnotationBeanPostProcessor + */ +public class InitDestroyAnnotationBeanPostProcessor + implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, PriorityOrdered, Serializable { + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + private Class initAnnotationType; + + private Class destroyAnnotationType; + + private int order = Ordered.LOWEST_PRECEDENCE - 1; + + private transient final Map, LifecycleMetadata> lifecycleMetadataCache = + new ConcurrentHashMap, LifecycleMetadata>(); + + + /** + * Specify the init annotation to check for, indicating initialization + * methods to call after configuration of a bean. + *

    Any custom annotation can be used, since there are no required + * annotation attributes. There is no default, although a typical choice + * is the JSR-250 {@link javax.annotation.PostConstruct} annotation. + */ + public void setInitAnnotationType(Class initAnnotationType) { + this.initAnnotationType = initAnnotationType; + } + + /** + * Specify the destroy annotation to check for, indicating destruction + * methods to call when the context is shutting down. + *

    Any custom annotation can be used, since there are no required + * annotation attributes. There is no default, although a typical choice + * is the JSR-250 {@link javax.annotation.PreDestroy} annotation. + */ + public void setDestroyAnnotationType(Class destroyAnnotationType) { + this.destroyAnnotationType = destroyAnnotationType; + } + + public void setOrder(int order) { + this.order = order; + } + + public int getOrder() { + return this.order; + } + + + public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) { + if (beanType != null) { + LifecycleMetadata metadata = findLifecycleMetadata(beanType); + for (Iterator it = metadata.getInitMethods().iterator(); it.hasNext();) { + String methodName = it.next().getMethod().getName(); + if (!beanDefinition.isExternallyManagedInitMethod(methodName)) { + beanDefinition.registerExternallyManagedInitMethod(methodName); + } + else { + it.remove(); + } + } + for (Iterator it = metadata.getDestroyMethods().iterator(); it.hasNext();) { + String methodName = it.next().getMethod().getName(); + if (!beanDefinition.isExternallyManagedDestroyMethod(methodName)) { + beanDefinition.registerExternallyManagedDestroyMethod(methodName); + } + else { + it.remove(); + } + } + } + } + + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass()); + try { + metadata.invokeInitMethods(bean, beanName); + } + catch (InvocationTargetException ex) { + throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException()); + } + catch (Throwable ex) { + throw new BeanCreationException(beanName, "Couldn't invoke init method", ex); + } + return bean; + } + + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + return bean; + } + + public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { + LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass()); + try { + metadata.invokeDestroyMethods(bean, beanName); + } + catch (InvocationTargetException ex) { + String msg = "Invocation of destroy method failed on bean with name '" + beanName + "'"; + if (logger.isDebugEnabled()) { + logger.warn(msg, ex.getTargetException()); + } + else { + logger.warn(msg + ": " + ex.getTargetException()); + } + } + catch (Throwable ex) { + logger.error("Couldn't invoke destroy method on bean with name '" + beanName + "'", ex); + } + } + + + private LifecycleMetadata findLifecycleMetadata(Class clazz) { + if (this.lifecycleMetadataCache == null) { + // Happens after deserialization, during destruction... + return buildLifecycleMetadata(clazz); + } + // Quick check on the concurrent map first, with minimal locking. + LifecycleMetadata metadata = this.lifecycleMetadataCache.get(clazz); + if (metadata == null) { + synchronized (this.lifecycleMetadataCache) { + metadata = this.lifecycleMetadataCache.get(clazz); + if (metadata == null) { + metadata = buildLifecycleMetadata(clazz); + this.lifecycleMetadataCache.put(clazz, metadata); + } + return metadata; + } + } + return metadata; + } + + private LifecycleMetadata buildLifecycleMetadata(final Class clazz) { + final LifecycleMetadata newMetadata = new LifecycleMetadata(); + final boolean debug = logger.isDebugEnabled(); + ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() { + public void doWith(Method method) { + if (initAnnotationType != null) { + if (method.getAnnotation(initAnnotationType) != null) { + newMetadata.addInitMethod(method); + if (debug) { + logger.debug("Found init method on class [" + clazz.getName() + "]: " + method); + } + } + } + if (destroyAnnotationType != null) { + if (method.getAnnotation(destroyAnnotationType) != null) { + newMetadata.addDestroyMethod(method); + if (debug) { + logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method); + } + } + } + } + }); + return newMetadata; + } + + + /** + * Class representing information about annotated init and destroy methods. + */ + private class LifecycleMetadata { + + private final Set initMethods = new LinkedHashSet(); + + private final Set destroyMethods = new LinkedHashSet(); + + public void addInitMethod(Method method) { + this.initMethods.add(new LifecycleElement(method)); + } + + public Set getInitMethods() { + return this.initMethods; + } + + public void invokeInitMethods(Object target, String beanName) throws Throwable { + if (!this.initMethods.isEmpty()) { + boolean debug = logger.isDebugEnabled(); + for (LifecycleElement element : this.initMethods) { + if (debug) { + logger.debug("Invoking init method on bean '" + beanName + "': " + element.getMethod()); + } + element.invoke(target); + } + } + } + + public void addDestroyMethod(Method method) { + this.destroyMethods.add(new LifecycleElement(method)); + } + + public Set getDestroyMethods() { + return this.destroyMethods; + } + + public void invokeDestroyMethods(Object target, String beanName) throws Throwable { + if (!this.destroyMethods.isEmpty()) { + boolean debug = logger.isDebugEnabled(); + for (LifecycleElement element : this.destroyMethods) { + if (debug) { + logger.debug("Invoking destroy method on bean '" + beanName + "': " + element.getMethod()); + } + element.invoke(target); + } + } + } + } + + + /** + * Class representing injection information about an annotated method. + */ + private static class LifecycleElement { + + private final Method method; + + public LifecycleElement(Method method) { + if (method.getParameterTypes().length != 0) { + throw new IllegalStateException("Lifecycle method annotation requires a no-arg method: " + method); + } + this.method = method; + } + + public Method getMethod() { + return this.method; + } + + public void invoke(Object target) throws Throwable { + ReflectionUtils.makeAccessible(this.method); + this.method.invoke(target, (Object[]) null); + } + + public boolean equals(Object other) { + return (this == other || (other instanceof LifecycleElement && + this.method.getName().equals(((LifecycleElement) other).method.getName()))); + } + + public int hashCode() { + return this.method.getName().hashCode(); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/InjectionMetadata.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/InjectionMetadata.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/InjectionMetadata.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,253 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.PropertyValues; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.util.ReflectionUtils; + +/** + * Internal class for managing injection metadata. + * Not intended for direct use in applications. + * + *

    Used by {@link AutowiredAnnotationBeanPostProcessor}, + * {@link org.springframework.context.annotation.CommonAnnotationBeanPostProcessor} and + * {@link org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor}. + * + * @author Juergen Hoeller + * @since 2.5 + */ +public class InjectionMetadata { + + private final Log logger = LogFactory.getLog(InjectionMetadata.class); + + private String targetClassName; + + private final Set injectedFields = new LinkedHashSet(); + + private final Set injectedMethods = new LinkedHashSet(); + + + public InjectionMetadata() { + } + + public InjectionMetadata(Class targetClass) { + this.targetClassName = targetClass.getName(); + } + + + public void addInjectedField(InjectedElement element) { + if (logger.isDebugEnabled()) { + logger.debug("Found injected field on class [" + this.targetClassName + "]: " + element); + } + this.injectedFields.add(element); + } + + public void addInjectedMethod(InjectedElement element) { + if (logger.isDebugEnabled()) { + logger.debug("Found injected method on class [" + this.targetClassName + "]: " + element); + } + this.injectedMethods.add(element); + } + + public void checkConfigMembers(RootBeanDefinition beanDefinition) { + doRegisterConfigMembers(beanDefinition, this.injectedFields); + doRegisterConfigMembers(beanDefinition, this.injectedMethods); + } + + private void doRegisterConfigMembers(RootBeanDefinition beanDefinition, Set members) { + for (Iterator it = members.iterator(); it.hasNext();) { + Member member = it.next().getMember(); + if (!beanDefinition.isExternallyManagedConfigMember(member)) { + beanDefinition.registerExternallyManagedConfigMember(member); + } + else { + it.remove(); + } + } + } + + public void injectFields(Object target, String beanName) throws Throwable { + if (!this.injectedFields.isEmpty()) { + boolean debug = logger.isDebugEnabled(); + for (InjectedElement element : this.injectedFields) { + if (debug) { + logger.debug("Processing injected field of bean '" + beanName + "': " + element); + } + element.inject(target, beanName, null); + } + } + } + + public void injectMethods(Object target, String beanName, PropertyValues pvs) throws Throwable { + if (!this.injectedMethods.isEmpty()) { + boolean debug = logger.isDebugEnabled(); + for (InjectedElement element : this.injectedMethods) { + if (debug) { + logger.debug("Processing injected method of bean '" + beanName + "': " + element); + } + element.inject(target, beanName, pvs); + } + } + } + + + public static abstract class InjectedElement { + + protected final Member member; + + protected final boolean isField; + + protected final PropertyDescriptor pd; + + protected volatile Boolean skip; + + protected InjectedElement(Member member, PropertyDescriptor pd) { + this.member = member; + this.isField = (member instanceof Field); + this.pd = pd; + } + + public final Member getMember() { + return this.member; + } + + protected final Class getResourceType() { + if (this.isField) { + return ((Field) this.member).getType(); + } + else if (this.pd != null) { + return this.pd.getPropertyType(); + } + else { + return ((Method) this.member).getParameterTypes()[0]; + } + } + + protected final void checkResourceType(Class resourceType) { + if (this.isField) { + Class fieldType = ((Field) this.member).getType(); + if (!(resourceType.isAssignableFrom(fieldType) || fieldType.isAssignableFrom(resourceType))) { + throw new IllegalStateException("Specified field type [" + fieldType + + "] is incompatible with resource type [" + resourceType.getName() + "]"); + } + } + else { + Class paramType = + (this.pd != null ? this.pd.getPropertyType() : ((Method) this.member).getParameterTypes()[0]); + if (!(resourceType.isAssignableFrom(paramType) || paramType.isAssignableFrom(resourceType))) { + throw new IllegalStateException("Specified parameter type [" + paramType + + "] is incompatible with resource type [" + resourceType.getName() + "]"); + } + } + } + + /** + * Either this or {@link #getResourceToInject} needs to be overridden. + */ + protected void inject(Object target, String requestingBeanName, PropertyValues pvs) throws Throwable { + if (this.isField) { + Field field = (Field) this.member; + ReflectionUtils.makeAccessible(field); + field.set(target, getResourceToInject(target, requestingBeanName)); + } + else { + if (this.skip == null) { + this.skip = Boolean.valueOf(checkPropertySkipping(pvs)); + } + if (this.skip.booleanValue()) { + return; + } + try { + Method method = (Method) this.member; + ReflectionUtils.makeAccessible(method); + method.invoke(target, getResourceToInject(target, requestingBeanName)); + } + catch (InvocationTargetException ex) { + throw ex.getTargetException(); + } + } + } + + /** + * Checks whether this injector's property needs to be skipped due to + * an explicit property value having been specified. Also marks the + * affected property as processed for other processors to ignore it. + */ + protected boolean checkPropertySkipping(PropertyValues pvs) { + if (this.pd != null && pvs != null) { + if (pvs.contains(this.pd.getName())) { + // Explicit value provided as part of the bean definition. + return true; + } + else if (pvs instanceof MutablePropertyValues) { + ((MutablePropertyValues) pvs).registerProcessedProperty(this.pd.getName()); + } + } + return false; + } + + /** + * Either this or {@link #inject} needs to be overridden. + */ + protected Object getResourceToInject(Object target, String requestingBeanName) { + return null; + } + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof InjectedElement)) { + return false; + } + InjectedElement otherElement = (InjectedElement) other; + if (this.isField) { + return this.member.equals(otherElement.member); + } + else { + return (otherElement.member instanceof Method && + this.member.getName().equals(otherElement.member.getName()) && + Arrays.equals(((Method) this.member).getParameterTypes(), + ((Method) otherElement.member).getParameterTypes())); + } + } + + public int hashCode() { + return this.member.getClass().hashCode() * 29 + this.member.getName().hashCode(); + } + + public String toString() { + return getClass().getSimpleName() + " for " + this.member; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/Qualifier.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/Qualifier.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/Qualifier.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import java.lang.annotation.Documented; +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; + +/** + * This annotation may be used on a field or parameter as a qualifier for + * candidate beans when autowiring. It may also be used to annotate other + * custom annotations that can then in turn be used as qualifiers. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + */ +@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Inherited +@Documented +public @interface Qualifier { + + String value() default ""; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,179 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import java.lang.annotation.Annotation; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.springframework.beans.SimpleTypeConverter; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.config.DependencyDescriptor; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.AutowireCandidateQualifier; +import org.springframework.beans.factory.support.AutowireCandidateResolver; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; + +/** + * {@link AutowireCandidateResolver} implementation that matches bean definition + * qualifiers against qualifier annotations on the field or parameter to be autowired. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + * @see AutowireCandidateQualifier + * @see Qualifier + */ +public class QualifierAnnotationAutowireCandidateResolver implements AutowireCandidateResolver { + + private final Set> qualifierTypes; + + + /** + * Create a new QualifierAnnotationAutowireCandidateResolver + * for Spring's standard {@link Qualifier} annotation. + */ + public QualifierAnnotationAutowireCandidateResolver() { + this.qualifierTypes = new HashSet>(1); + this.qualifierTypes.add(Qualifier.class); + } + + /** + * Create a new QualifierAnnotationAutowireCandidateResolver + * for the given qualifier annotation type. + * @param qualifierType the qualifier annotation to look for + */ + public QualifierAnnotationAutowireCandidateResolver(Class qualifierType) { + Assert.notNull(qualifierType, "'qualifierType' must not be null"); + this.qualifierTypes = new HashSet>(1); + this.qualifierTypes.add(qualifierType); + } + + /** + * Create a new QualifierAnnotationAutowireCandidateResolver + * for the given qualifier annotation types. + * @param qualifierTypes the qualifier annotations to look for + */ + public QualifierAnnotationAutowireCandidateResolver(Set> qualifierTypes) { + Assert.notNull(qualifierTypes, "'qualifierTypes' must not be null"); + this.qualifierTypes = new HashSet>(qualifierTypes); + } + + + /** + * Register the given type to be used as a qualifier when autowiring. + *

    This implementation only supports annotations as qualifier types. + * @param qualifierType the annotation type to register + */ + public void addQualifierType(Class qualifierType) { + this.qualifierTypes.add(qualifierType); + } + + /** + * Determine if the provided bean definition is an autowire candidate. + *

    To be considered a candidate the bean's autowire-candidate + * attribute must not have been set to 'false'. Also if an annotation on + * the field or parameter to be autowired is recognized by this bean factory + * as a qualifier, the bean must 'match' against the annotation as + * well as any attributes it may contain. The bean definition must contain + * the same qualifier or match by meta attributes. A "value" attribute will + * fallback to match against the bean name or an alias if a qualifier or + * attribute does not match. + */ + public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) { + if (!bdHolder.getBeanDefinition().isAutowireCandidate()) { + // if explicitly false, do not proceed with qualifier check + return false; + } + if (descriptor == null || ObjectUtils.isEmpty(descriptor.getAnnotations())) { + // no qualification necessary + return true; + } + AbstractBeanDefinition bd = (AbstractBeanDefinition) bdHolder.getBeanDefinition(); + SimpleTypeConverter typeConverter = new SimpleTypeConverter(); + Annotation[] annotations = (Annotation[]) descriptor.getAnnotations(); + for (Annotation annotation : annotations) { + Class type = annotation.annotationType(); + if (isQualifier(type)) { + AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName()); + if (qualifier == null) { + qualifier = bd.getQualifier(ClassUtils.getShortName(type)); + } + if (qualifier == null && bd.hasBeanClass()) { + // look for matching annotation on the target class + Class beanClass = bd.getBeanClass(); + Annotation targetAnnotation = beanClass.getAnnotation(type); + if (targetAnnotation != null && targetAnnotation.equals(annotation)) { + return true; + } + } + Map attributes = AnnotationUtils.getAnnotationAttributes(annotation); + if (attributes.isEmpty() && qualifier == null) { + // if no attributes, the qualifier must be present + return false; + } + for (Map.Entry entry : attributes.entrySet()) { + String attributeName = entry.getKey(); + Object expectedValue = entry.getValue(); + Object actualValue = null; + // check qualifier first + if (qualifier != null) { + actualValue = qualifier.getAttribute(attributeName); + } + if (actualValue == null) { + // fall back on bean definition attribute + actualValue = bd.getAttribute(attributeName); + } + if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) && + (expectedValue.equals(bdHolder.getBeanName()) || + ObjectUtils.containsElement(bdHolder.getAliases(), expectedValue))) { + // fall back on bean name (or alias) match + continue; + } + if (actualValue == null && qualifier != null) { + // fall back on default, but only if the qualifier is present + actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName); + } + if (actualValue != null) { + actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass()); + } + if (!expectedValue.equals(actualValue)) { + return false; + } + } + } + } + return true; + } + + /** + * Checks whether the given annotation type is a recognized qualifier type. + */ + private boolean isQualifier(Class annotationType) { + for (Class qualifierType : this.qualifierTypes) { + if (annotationType.equals(qualifierType) || annotationType.isAnnotationPresent(qualifierType)) { + return true; + } + } + return false; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/Required.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/Required.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/Required.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Marks a method (typically a JavaBean setter method) as being 'required': that is, + * the setter method must be configured to be dependency-injected with a value. + * + *

    Please do consult the javadoc for the {@link RequiredAnnotationBeanPostProcessor} + * class (which, by default, checks for the presence of this annotation). + * + * @author Rob Harrop + * @since 2.0 + * @see RequiredAnnotationBeanPostProcessor + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Required { + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessor.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,169 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.annotation; + +import java.beans.PropertyDescriptor; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.springframework.beans.BeansException; +import org.springframework.beans.PropertyValues; +import org.springframework.beans.factory.BeanInitializationException; +import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; +import org.springframework.core.Ordered; +import org.springframework.core.PriorityOrdered; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.util.Assert; + +/** + * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation + * that enforces required JavaBean properties to have been configured. + * Required bean properties are detected through a Java 5 annotation: + * by default, Spring's {@link Required} annotation. + * + *

    The motivation for the existence of this BeanPostProcessor is to allow + * developers to annotate the setter properties of their own classes with an + * arbitrary JDK 1.5 annotation to indicate that the container must check + * for the configuration of a dependency injected value. This neatly pushes + * responsibility for such checking onto the container (where it arguably belongs), + * and obviates the need (in part) for a developer to code a method that + * simply checks that all required properties have actually been set. + * + *

    Please note that an 'init' method may still need to implemented (and may + * still be desirable), because all that this class does is enforce that a + * 'required' property has actually been configured with a value. It does + * not check anything else... In particular, it does not check that a + * configured value is not null. + * + *

    Note: A default RequiredAnnotationBeanPostProcessor will be registered + * by the "context:annotation-config" and "context:component-scan" XML tags. + * Remove or turn off the default annotation configuration there if you intend + * to specify a custom RequiredAnnotationBeanPostProcessor bean definition. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + * @see #setRequiredAnnotationType + * @see Required + */ +public class RequiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter + implements PriorityOrdered { + + private Class requiredAnnotationType = Required.class; + + private int order = Ordered.LOWEST_PRECEDENCE - 1; + + /** Cache for validated bean names, skipping re-validation for the same bean */ + private final Set validatedBeanNames = Collections.synchronizedSet(new HashSet()); + + + /** + * Set the 'required' annotation type, to be used on bean property + * setter methods. + *

    The default required annotation type is the Spring-provided + * {@link Required} annotation. + *

    This setter property exists so that developers can provide their own + * (non-Spring-specific) annotation type to indicate that a property value + * is required. + */ + public void setRequiredAnnotationType(Class requiredAnnotationType) { + Assert.notNull(requiredAnnotationType, "'requiredAnnotationType' must not be null"); + this.requiredAnnotationType = requiredAnnotationType; + } + + /** + * Return the 'required' annotation type. + */ + protected Class getRequiredAnnotationType() { + return this.requiredAnnotationType; + } + + public void setOrder(int order) { + this.order = order; + } + + public int getOrder() { + return this.order; + } + + + public PropertyValues postProcessPropertyValues( + PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) + throws BeansException { + + if (!this.validatedBeanNames.contains(beanName)) { + List invalidProperties = new ArrayList(); + for (PropertyDescriptor pd : pds) { + if (isRequiredProperty(pd) && !pvs.contains(pd.getName())) { + invalidProperties.add(pd.getName()); + } + } + if (!invalidProperties.isEmpty()) { + throw new BeanInitializationException(buildExceptionMessage(invalidProperties, beanName)); + } + this.validatedBeanNames.add(beanName); + } + return pvs; + } + + /** + * Is the supplied property required to have a value (that is, to be dependency-injected)? + *

    This implementation looks for the existence of a + * {@link #setRequiredAnnotationType "required" annotation} + * on the supplied {@link PropertyDescriptor property}. + * @param propertyDescriptor the target PropertyDescriptor (never null) + * @return true if the supplied property has been marked as being required; + * false if not, or if the supplied property does not have a setter method + */ + protected boolean isRequiredProperty(PropertyDescriptor propertyDescriptor) { + Method setter = propertyDescriptor.getWriteMethod(); + return (setter != null && AnnotationUtils.getAnnotation(setter, getRequiredAnnotationType()) != null); + } + + /** + * Build an exception message for the given list of invalid properties. + * @param invalidProperties the list of names of invalid properties + * @param beanName the name of the bean + * @return the exception message + */ + private String buildExceptionMessage(List invalidProperties, String beanName) { + int size = invalidProperties.size(); + StringBuilder sb = new StringBuilder(); + sb.append(size == 1 ? "Property" : "Properties"); + for (int i = 0; i < size; i++) { + String propertyName = invalidProperties.get(i); + if (i > 0) { + if (i == (size - 1)) { + sb.append(" and"); + } + else { + sb.append(","); + } + } + sb.append(" '").append(propertyName).append("'"); + } + sb.append(size == 1 ? " is" : " are"); + sb.append(" required for bean '").append(beanName).append("'"); + return sb.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/annotation/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/annotation/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/annotation/package.html 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,7 @@ + + + +Support package for annotation-driven bean configuration. + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/AbstractFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/AbstractFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/AbstractFactoryBean.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,262 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.SimpleTypeConverter; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.FactoryBeanNotInitializedException; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; +import org.springframework.util.ReflectionUtils; + +/** + * Simple template superclass for {@link FactoryBean} implementations that + * creates a singleton or a prototype object, depending on a flag. + * + *

    If the "singleton" flag is true (the default), + * this class will create the object that it creates exactly once + * on initialization and subsequently return said singleton instance + * on all calls to the {@link #getObject()} method. + * + *

    Else, this class will create a new instance every time the + * {@link #getObject()} method is invoked. Subclasses are responsible + * for implementing the abstract {@link #createInstance()} template + * method to actually create the object(s) to expose. + * + * @author Juergen Hoeller + * @author Keith Donald + * @since 1.0.2 + * @see #setSingleton + * @see #createInstance() + */ +public abstract class AbstractFactoryBean + implements FactoryBean, BeanClassLoaderAware, BeanFactoryAware, InitializingBean, DisposableBean { + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + private boolean singleton = true; + + private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); + + private BeanFactory beanFactory; + + private boolean initialized = false; + + private Object singletonInstance; + + private Object earlySingletonInstance; + + + /** + * Set if a singleton should be created, or a new object + * on each request else. Default is true (a singleton). + */ + public void setSingleton(boolean singleton) { + this.singleton = singleton; + } + + public boolean isSingleton() { + return this.singleton; + } + + public void setBeanClassLoader(ClassLoader classLoader) { + this.beanClassLoader = classLoader; + } + + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + + /** + * Return the BeanFactory that this bean runs in. + */ + protected BeanFactory getBeanFactory() { + return this.beanFactory; + } + + /** + * Obtain a bean type converter from the BeanFactory that this bean + * runs in. This is typically a fresh instance for each call, + * since TypeConverters are usually not thread-safe. + *

    Falls back to a SimpleTypeConverter when not running in a BeanFactory. + * @see ConfigurableBeanFactory#getTypeConverter() + * @see org.springframework.beans.SimpleTypeConverter + */ + protected TypeConverter getBeanTypeConverter() { + BeanFactory beanFactory = getBeanFactory(); + if (beanFactory instanceof ConfigurableBeanFactory) { + return ((ConfigurableBeanFactory) beanFactory).getTypeConverter(); + } + else { + return new SimpleTypeConverter(); + } + } + + /** + * Eagerly create the singleton instance, if necessary. + */ + public void afterPropertiesSet() throws Exception { + if (isSingleton()) { + this.initialized = true; + this.singletonInstance = createInstance(); + this.earlySingletonInstance = null; + } + } + + + /** + * Expose the singleton instance or create a new prototype instance. + * @see #createInstance() + * @see #getEarlySingletonInterfaces() + */ + public final Object getObject() throws Exception { + if (isSingleton()) { + return (this.initialized ? this.singletonInstance : getEarlySingletonInstance()); + } + else { + return createInstance(); + } + } + + /** + * Determine an 'eager singleton' instance, exposed in case of a + * circular reference. Not called in a non-circular scenario. + */ + private Object getEarlySingletonInstance() throws Exception { + Class[] ifcs = getEarlySingletonInterfaces(); + if (ifcs == null) { + throw new FactoryBeanNotInitializedException( + getClass().getName() + " does not support circular references"); + } + if (this.earlySingletonInstance == null) { + this.earlySingletonInstance = Proxy.newProxyInstance( + this.beanClassLoader, ifcs, new EarlySingletonInvocationHandler()); + } + return this.earlySingletonInstance; + } + + /** + * Expose the singleton instance (for access through the 'early singleton' proxy). + * @return the singleton instance that this FactoryBean holds + * @throws IllegalStateException if the singleton instance is not initialized + */ + private Object getSingletonInstance() throws IllegalStateException { + if (!this.initialized) { + throw new IllegalStateException("Singleton instance not initialized yet"); + } + return this.singletonInstance; + } + + /** + * Destroy the singleton instance, if any. + * @see #destroyInstance(Object) + */ + public void destroy() throws Exception { + if (isSingleton()) { + destroyInstance(this.singletonInstance); + } + } + + + /** + * This abstract method declaration mirrors the method in the FactoryBean + * interface, for a consistent offering of abstract template methods. + * @see org.springframework.beans.factory.FactoryBean#getObjectType() + */ + public abstract Class getObjectType(); + + /** + * Template method that subclasses must override to construct + * the object returned by this factory. + *

    Invoked on initialization of this FactoryBean in case of + * a singleton; else, on each {@link #getObject()} call. + * @return the object returned by this factory + * @throws Exception if an exception occured during object creation + * @see #getObject() + */ + protected abstract Object createInstance() throws Exception; + + /** + * Return an array of interfaces that a singleton object exposed by this + * FactoryBean is supposed to implement, for use with an 'early singleton + * proxy' that will be exposed in case of a circular reference. + *

    The default implementation returns this FactoryBean's object type, + * provided that it is an interface, or null else. The latter + * indicates that early singleton access is not supported by this FactoryBean. + * This will lead to a FactoryBeanNotInitializedException getting thrown. + * @return the interfaces to use for 'early singletons', + * or null to indicate a FactoryBeanNotInitializedException + * @see org.springframework.beans.factory.FactoryBeanNotInitializedException + */ + protected Class[] getEarlySingletonInterfaces() { + Class type = getObjectType(); + return (type != null && type.isInterface() ? new Class[] {type} : null); + } + + /** + * Callback for destroying a singleton instance. Subclasses may + * override this to destroy the previously created instance. + *

    The default implementation is empty. + * @param instance the singleton instance, as returned by + * {@link #createInstance()} + * @throws Exception in case of shutdown errors + * @see #createInstance() + */ + protected void destroyInstance(Object instance) throws Exception { + } + + + private class EarlySingletonInvocationHandler implements InvocationHandler { + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (ReflectionUtils.isEqualsMethod(method)) { + // Only consider equal when proxies are identical. + return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE); + } + else if (ReflectionUtils.isHashCodeMethod(method)) { + // Use hashCode of reference proxy. + return new Integer(System.identityHashCode(proxy)); + } + else if (!initialized && ReflectionUtils.isToStringMethod(method)) { + return "Early singleton proxy for interfaces " + + ObjectUtils.nullSafeToString(getEarlySingletonInterfaces()); + } + try { + return method.invoke(getSingletonInstance(), args); + } + catch (InvocationTargetException ex) { + throw ex.getTargetException(); + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,317 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.util.Set; + +import org.springframework.beans.BeansException; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.BeanFactory; + +/** + * Extension of the {@link org.springframework.beans.factory.BeanFactory} + * interface to be implemented by bean factories that are capable of + * autowiring, provided that they want to expose this functionality for + * existing bean instances. + * + *

    This subinterface of BeanFactory is not meant to be used in normal + * application code: stick to {@link org.springframework.beans.factory.BeanFactory} + * or {@link org.springframework.beans.factory.ListableBeanFactory} for + * typical use cases. + * + *

    Integration code for other frameworks can leverage this interface to + * wire and populate existing bean instances that Spring does not control + * the lifecycle of. This is particularly useful for WebWork Actions and + * Tapestry Page objects, for example. + * + *

    Note that this interface is not implemented by + * {@link org.springframework.context.ApplicationContext} facades, + * as it is hardly ever used by application code. That said, it is available + * from an application context too, accessible through ApplicationContext's + * {@link org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()} + * method. + * + *

    You may also implement the {@link org.springframework.beans.factory.BeanFactoryAware} + * interface, which exposes the internal BeanFactory even when running in an + * ApplicationContext, to get access to an AutowireCapableBeanFactory: + * simply cast the passed-in BeanFactory to AutowireCapableBeanFactory. + * + * @author Juergen Hoeller + * @since 04.12.2003 + * @see org.springframework.beans.factory.BeanFactoryAware + * @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory + * @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory() + */ +public interface AutowireCapableBeanFactory extends BeanFactory { + + /** + * Constant that indicates no externally defined autowiring. Note that + * BeanFactoryAware etc and annotation-driven injection will still be applied. + * @see #createBean + * @see #autowire + * @see #autowireBeanProperties + */ + int AUTOWIRE_NO = 0; + + /** + * Constant that indicates autowiring bean properties by name + * (applying to all bean property setters). + * @see #createBean + * @see #autowire + * @see #autowireBeanProperties + */ + int AUTOWIRE_BY_NAME = 1; + + /** + * Constant that indicates autowiring bean properties by type + * (applying to all bean property setters). + * @see #createBean + * @see #autowire + * @see #autowireBeanProperties + */ + int AUTOWIRE_BY_TYPE = 2; + + /** + * Constant that indicates autowiring the greediest constructor that + * can be satisfied (involves resolving the appropriate constructor). + * @see #createBean + * @see #autowire + */ + int AUTOWIRE_CONSTRUCTOR = 3; + + /** + * Constant that indicates determining an appropriate autowire strategy + * through introspection of the bean class. + * @see #createBean + * @see #autowire + */ + int AUTOWIRE_AUTODETECT = 4; + + + //------------------------------------------------------------------------- + // Typical methods for creating and populating external bean instances + //------------------------------------------------------------------------- + + /** + * Fully create a new bean instance of the given class. + *

    Performs full initialization of the bean, including all applicable + * {@link BeanPostProcessor BeanPostProcessors}. + *

    Note: This is intended for creating a fresh instance, populating annotated + * fields and methods as well as applying all standard bean initialiation callbacks. + * It does not imply traditional by-name or by-type autowiring of properties; + * use {@link #createBean(Class, int, boolean)} for that purposes. + * @param beanClass the class of the bean to create + * @return the new bean instance + * @throws BeansException if instantiation or wiring failed + */ + Object createBean(Class beanClass) throws BeansException; + + /** + * Populate the given bean instance through applying after-instantiation callbacks + * and bean property post-processing (e.g. for annotation-driven injection). + *

    Note: This is essentially intended for (re-)populating annotated fields and + * methods, either for new instances or for deserialized instances. It does + * not imply traditional by-name or by-type autowiring of properties; + * use {@link #autowireBeanProperties} for that purposes. + * @param existingBean the existing bean instance + * @throws BeansException if wiring failed + */ + void autowireBean(Object existingBean) throws BeansException; + + /** + * Configure the given raw bean: autowiring bean properties, applying + * bean property values, applying factory callbacks such as setBeanName + * and setBeanFactory, and also applying all bean post processors + * (including ones which might wrap the given raw bean). + *

    This is effectively a superset of what {@link #initializeBean} provides, + * fully applying the configuration specified by the corresponding bean definition. + * Note: This method requires a bean definition for the given name! + * @param existingBean the existing bean instance + * @param beanName the name of the bean, to be passed to it if necessary + * (a bean definition of that name has to be available) + * @return the bean instance to use, either the original or a wrapped one + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + * if there is no bean definition with the given name + * @throws BeansException if the initialization failed + * @see #initializeBean + */ + Object configureBean(Object existingBean, String beanName) throws BeansException; + + /** + * Resolve the specified dependency against the beans defined in this factory. + * @param descriptor the descriptor for the dependency + * @param beanName the name of the bean which declares the present dependency + * @return the resolved object, or null if none found + * @throws BeansException in dependency resolution failed + */ + Object resolveDependency(DependencyDescriptor descriptor, String beanName) throws BeansException; + + + //------------------------------------------------------------------------- + // Specialized methods for fine-grained control over the bean lifecycle + //------------------------------------------------------------------------- + + /** + * Fully create a new bean instance of the given class with the specified + * autowire strategy. All constants defined in this interface are supported here. + *

    Performs full initialization of the bean, including all applicable + * {@link BeanPostProcessor BeanPostProcessors}. This is effectively a superset + * of what {@link #autowire} provides, adding {@link #initializeBean} behavior. + * @param beanClass the class of the bean to create + * @param autowireMode by name or type, using the constants in this interface + * @param dependencyCheck whether to perform a dependency check for objects + * (not applicable to autowiring a constructor, thus ignored there) + * @return the new bean instance + * @throws BeansException if instantiation or wiring failed + * @see #AUTOWIRE_NO + * @see #AUTOWIRE_BY_NAME + * @see #AUTOWIRE_BY_TYPE + * @see #AUTOWIRE_CONSTRUCTOR + * @see #AUTOWIRE_AUTODETECT + */ + Object createBean(Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException; + + /** + * Instantiate a new bean instance of the given class with the specified autowire + * strategy. All constants defined in this interface are supported here. + * Can also be invoked with AUTOWIRE_NO in order to just apply + * before-instantiation callbacks (e.g. for annotation-driven injection). + *

    Does not apply standard {@link BeanPostProcessor BeanPostProcessors} + * callbacks or perform any further initialization of the bean. This interface + * offers distinct, fine-grained operations for those purposes, for example + * {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor} + * callbacks are applied, if applicable to the construction of the instance. + * @param beanClass the class of the bean to instantiate + * @param autowireMode by name or type, using the constants in this interface + * @param dependencyCheck whether to perform a dependency check for object + * references in the bean instance (not applicable to autowiring a constructor, + * thus ignored there) + * @return the new bean instance + * @throws BeansException if instantiation or wiring failed + * @see #AUTOWIRE_NO + * @see #AUTOWIRE_BY_NAME + * @see #AUTOWIRE_BY_TYPE + * @see #AUTOWIRE_CONSTRUCTOR + * @see #AUTOWIRE_AUTODETECT + * @see #initializeBean + * @see #applyBeanPostProcessorsBeforeInitialization + * @see #applyBeanPostProcessorsAfterInitialization + */ + Object autowire(Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException; + + /** + * Autowire the bean properties of the given bean instance by name or type. + * Can also be invoked with AUTOWIRE_NO in order to just apply + * after-instantiation callbacks (e.g. for annotation-driven injection). + *

    Does not apply standard {@link BeanPostProcessor BeanPostProcessors} + * callbacks or perform any further initialization of the bean. This interface + * offers distinct, fine-grained operations for those purposes, for example + * {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor} + * callbacks are applied, if applicable to the configuration of the instance. + * @param existingBean the existing bean instance + * @param autowireMode by name or type, using the constants in this interface + * @param dependencyCheck whether to perform a dependency check for object + * references in the bean instance + * @throws BeansException if wiring failed + * @see #AUTOWIRE_BY_NAME + * @see #AUTOWIRE_BY_TYPE + * @see #AUTOWIRE_NO + */ + void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) + throws BeansException; + + /** + * Apply the property values of the bean definition with the given name to + * the given bean instance. The bean definition can either define a fully + * self-contained bean, reusing its property values, or just property values + * meant to be used for existing bean instances. + *

    This method does not autowire bean properties; it just applies + * explicitly defined property values. Use the {@link #autowireBeanProperties} + * method to autowire an existing bean instance. + * Note: This method requires a bean definition for the given name! + *

    Does not apply standard {@link BeanPostProcessor BeanPostProcessors} + * callbacks or perform any further initialization of the bean. This interface + * offers distinct, fine-grained operations for those purposes, for example + * {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor} + * callbacks are applied, if applicable to the configuration of the instance. + * @param existingBean the existing bean instance + * @param beanName the name of the bean definition in the bean factory + * (a bean definition of that name has to be available) + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + * if there is no bean definition with the given name + * @throws BeansException if applying the property values failed + * @see #autowireBeanProperties + */ + void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException; + + /** + * Initialize the given raw bean, applying factory callbacks + * such as setBeanName and setBeanFactory, + * also applying all bean post processors (including ones which + * might wrap the given raw bean). + *

    Note that no bean definition of the given name has to exist + * in the bean factory. The passed-in bean name will simply be used + * for callbacks but not checked against the registered bean definitions. + * @param existingBean the existing bean instance + * @param beanName the name of the bean, to be passed to it if necessary + * (only passed to {@link BeanPostProcessor BeanPostProcessors}) + * @return the bean instance to use, either the original or a wrapped one + * @throws BeansException if the initialization failed + */ + Object initializeBean(Object existingBean, String beanName) throws BeansException; + + /** + * Apply {@link BeanPostProcessor BeanPostProcessors} to the given existing bean + * instance, invoking their postProcessBeforeInitialization methods. + * The returned bean instance may be a wrapper around the original. + * @param existingBean the new bean instance + * @param beanName the name of the bean + * @return the bean instance to use, either the original or a wrapped one + * @throws BeansException if any post-processing failed + * @see BeanPostProcessor#postProcessBeforeInitialization + */ + Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) + throws BeansException; + + /** + * Apply {@link BeanPostProcessor BeanPostProcessors} to the given existing bean + * instance, invoking their postProcessAfterInitialization methods. + * The returned bean instance may be a wrapper around the original. + * @param existingBean the new bean instance + * @param beanName the name of the bean + * @return the bean instance to use, either the original or a wrapped one + * @throws BeansException if any post-processing failed + * @see BeanPostProcessor#postProcessAfterInitialization + */ + Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) + throws BeansException; + + /** + * Resolve the specified dependency against the beans defined in this factory. + * @param descriptor the descriptor for the dependency + * @param beanName the name of the bean which declares the present dependency + * @param autowiredBeanNames a Set that all names of autowired beans (used for + * resolving the present dependency) are supposed to be added to + * @param typeConverter the TypeConverter to use for populating arrays and + * collections + * @return the resolved object, or null if none found + * @throws BeansException in dependency resolution failed + */ + Object resolveDependency(DependencyDescriptor descriptor, String beanName, + Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/BeanDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanDefinition.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,218 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.beans.MutablePropertyValues; +import org.springframework.core.AttributeAccessor; + +/** + * A BeanDefinition describes a bean instance, which has property values, + * constructor argument values, and further information supplied by + * concrete implementations. + * + *

    This is just a minimal interface: The main intention is to allow a + * {@link BeanFactoryPostProcessor} such as {@link PropertyPlaceholderConfigurer} + * to introspect and modify property values and other bean metadata. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @since 19.03.2004 + * @see ConfigurableListableBeanFactory#getBeanDefinition + * @see org.springframework.beans.factory.support.RootBeanDefinition + * @see org.springframework.beans.factory.support.ChildBeanDefinition + */ +public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement { + + /** + * Scope identifier for the standard singleton scope: "singleton". + *

    Note that extended bean factories might support further scopes. + * @see #setScope + */ + String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON; + + /** + * Scope identifier for the standard prototype scope: "prototype". + *

    Note that extended bean factories might support further scopes. + * @see #setScope + */ + String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE; + + + /** + * Role hint indicating that a BeanDefinition is a major part + * of the application. Typically corresponds to a user-defined bean. + */ + int ROLE_APPLICATION = 0; + + /** + * Role hint indicating that a BeanDefinition is a supporting + * part of some larger configuration, typically an outer + * {@link org.springframework.beans.factory.parsing.ComponentDefinition}. + * SUPPORT beans are considered important enough to be aware + * of when looking more closely at a particular + * {@link org.springframework.beans.factory.parsing.ComponentDefinition}, + * but not when looking at the overall configuration of an application. + */ + int ROLE_SUPPORT = 1; + + /** + * Role hint indicating that a BeanDefinition is providing an + * entirely background role and has no relevance to the end-user. This hint is + * used when registering beans that are completely part of the internal workings + * of a {@link org.springframework.beans.factory.parsing.ComponentDefinition}. + */ + int ROLE_INFRASTRUCTURE = 2; + + + /** + * Return the name of the parent definition of this bean definition, if any. + */ + String getParentName(); + + /** + * Set the name of the parent definition of this bean definition, if any. + */ + void setParentName(String parentName); + + /** + * Return the current bean class name of this bean definition. + *

    Note that this does not have to be the actual class name used at runtime, in + * case of a child definition overriding/inheriting the class name from its parent. + * Hence, do not consider this to be the definitive bean type at runtime but + * rather only use it for parsing purposes at the individual bean definition level. + */ + String getBeanClassName(); + + /** + * Override the bean class name of this bean definition. + *

    The class name can be modified during bean factory post-processing, + * typically replacing the original class name with a parsed variant of it. + */ + void setBeanClassName(String beanClassName); + + /** + * Return the factory bean name, if any. + */ + String getFactoryBeanName(); + + /** + * Specify the factory bean to use, if any. + */ + void setFactoryBeanName(String factoryBeanName); + + /** + * Return a factory method, if any. + */ + String getFactoryMethodName(); + + /** + * Specify a factory method, if any. This method will be invoked with + * constructor arguments, or with no arguments if none are specified. + * The method will be invoked on the specifed factory bean, if any, + * or as static method on the local bean class else. + * @param factoryMethodName static factory method name, + * or null if normal constructor creation should be used + * @see #getBeanClassName() + */ + void setFactoryMethodName(String factoryMethodName); + + /** + * Return the name of the current target scope for this bean. + */ + String getScope(); + + /** + * Override the target scope of this bean, specifying a new scope name. + * @see #SCOPE_SINGLETON + * @see #SCOPE_PROTOTYPE + */ + void setScope(String scope); + + /** + * Return whether this bean is a candidate for getting autowired into some other bean. + */ + boolean isAutowireCandidate(); + + /** + * Set whether this bean is a candidate for getting autowired into some other bean. + */ + void setAutowireCandidate(boolean autowireCandidate); + + + /** + * Return the constructor argument values for this bean. + *

    The returned instance can be modified during bean factory post-processing. + * @return the ConstructorArgumentValues object (never null) + */ + ConstructorArgumentValues getConstructorArgumentValues(); + + /** + * Return the property values to be applied to a new instance of the bean. + *

    The returned instance can be modified during bean factory post-processing. + * @return the MutablePropertyValues object (never null) + */ + MutablePropertyValues getPropertyValues(); + + + /** + * Return whether this a Singleton, with a single, shared instance + * returned on all calls. + */ + boolean isSingleton(); + + /** + * Return whether this bean is "abstract", that is, not meant to be instantiated. + */ + boolean isAbstract(); + + /** + * Return whether this bean should be lazily initialized, that is, not + * eagerly instantiated on startup. + */ + boolean isLazyInit(); + + /** + * Get the role hint for this BeanDefinition. The role hint + * provides tools with an indication of the importance of a particular + * BeanDefinition. + * @see #ROLE_APPLICATION + * @see #ROLE_INFRASTRUCTURE + * @see #ROLE_SUPPORT + */ + int getRole(); + + /** + * Return a human-readable description of this bean definition. + */ + String getDescription(); + + /** + * Return a description of the resource that this bean definition + * came from (for the purpose of showing context in case of errors). + */ + String getResourceDescription(); + + /** + * Return the originating BeanDefinition, or null if none. + * Allows for retrieving the decorated bean definition, if any. + *

    Note that this method returns the immediate originator. Iterate through the + * originator chain to find the original BeanDefinition as defined by the user. + */ + BeanDefinition getOriginatingBeanDefinition(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanDefinitionHolder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/BeanDefinitionHolder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanDefinitionHolder.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,173 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +/** + * Holder for a BeanDefinition with name and aliases. + * Can be registered as a placeholder for an inner bean. + * + *

    Can also be used for programmatic registration of inner bean + * definitions. If you don't care about BeanNameAware and the like, + * registering RootBeanDefinition or ChildBeanDefinition is good enough. + * + * @author Juergen Hoeller + * @since 1.0.2 + * @see org.springframework.beans.factory.BeanNameAware + * @see org.springframework.beans.factory.support.RootBeanDefinition + * @see org.springframework.beans.factory.support.ChildBeanDefinition + */ +public class BeanDefinitionHolder implements BeanMetadataElement { + + private final BeanDefinition beanDefinition; + + private final String beanName; + + private final String[] aliases; + + + /** + * Create a new BeanDefinitionHolder. + * @param beanDefinition the BeanDefinition to wrap + * @param beanName the name of the bean, as specified for the bean definition + */ + public BeanDefinitionHolder(BeanDefinition beanDefinition, String beanName) { + this(beanDefinition, beanName, null); + } + + /** + * Create a new BeanDefinitionHolder. + * @param beanDefinition the BeanDefinition to wrap + * @param beanName the name of the bean, as specified for the bean definition + * @param aliases alias names for the bean, or null if none + */ + public BeanDefinitionHolder(BeanDefinition beanDefinition, String beanName, String[] aliases) { + Assert.notNull(beanDefinition, "BeanDefinition must not be null"); + Assert.notNull(beanName, "Bean name must not be null"); + this.beanDefinition = beanDefinition; + this.beanName = beanName; + this.aliases = aliases; + } + + /** + * Copy constructor: Create a new BeanDefinitionHolder with the + * same contents as the given BeanDefinitionHolder instance. + *

    Note: The wrapped BeanDefinition reference is taken as-is; + * it is not deeply copied. + * @param beanDefinitionHolder the BeanDefinitionHolder to copy + */ + public BeanDefinitionHolder(BeanDefinitionHolder beanDefinitionHolder) { + Assert.notNull(beanDefinitionHolder, "BeanDefinitionHolder must not be null"); + this.beanDefinition = beanDefinitionHolder.getBeanDefinition(); + this.beanName = beanDefinitionHolder.getBeanName(); + this.aliases = beanDefinitionHolder.getAliases(); + } + + + /** + * Return the wrapped BeanDefinition. + */ + public BeanDefinition getBeanDefinition() { + return this.beanDefinition; + } + + /** + * Return the primary name of the bean, as specified for the bean definition. + */ + public String getBeanName() { + return this.beanName; + } + + /** + * Return the alias names for the bean, as specified directly for the bean definition. + * @return the array of alias names, or null if none + */ + public String[] getAliases() { + return this.aliases; + } + + /** + * Expose the bean definition's source object. + * @see BeanDefinition#getSource() + */ + public Object getSource() { + return this.beanDefinition.getSource(); + } + + + /** + * Return a friendly, short description for the bean, stating name and aliases. + * @see #getBeanName() + * @see #getAliases() + */ + public String getShortDescription() { + StringBuffer sb = new StringBuffer(); + sb.append("Bean definition with name '").append(this.beanName).append("'"); + if (this.aliases != null) { + sb.append(" and aliases [").append(StringUtils.arrayToCommaDelimitedString(this.aliases)).append("]"); + } + return sb.toString(); + } + + /** + * Return a long description for the bean, including name and aliases + * as well as a description of the contained {@link BeanDefinition}. + * @see #getShortDescription() + * @see #getBeanDefinition() + */ + public String getLongDescription() { + StringBuffer sb = new StringBuffer(getShortDescription()); + sb.append(": ").append(this.beanDefinition); + return sb.toString(); + } + + /** + * This implementation returns the long description. Can be overridden + * to return the short description or any kind of custom description instead. + * @see #getLongDescription() + * @see #getShortDescription() + */ + public String toString() { + return getLongDescription(); + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof BeanDefinitionHolder)) { + return false; + } + BeanDefinitionHolder otherHolder = (BeanDefinitionHolder) other; + return this.beanDefinition.equals(otherHolder.beanDefinition) && + this.beanName.equals(otherHolder.beanName) && + ObjectUtils.nullSafeEquals(this.aliases, otherHolder.aliases); + } + + public int hashCode() { + int hashCode = this.beanDefinition.hashCode(); + hashCode = 29 * hashCode + this.beanName.hashCode(); + hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.aliases); + return hashCode; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanDefinitionVisitor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/BeanDefinitionVisitor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanDefinitionVisitor.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,268 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.PropertyValue; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringValueResolver; + +/** + * Visitor class for traversing {@link BeanDefinition} objects, in particular + * the property values and constructor argument values contained in them, + * resolving bean metadata values. + * + *

    Used by {@link PropertyPlaceholderConfigurer} to parse all String values + * contained in a BeanDefinition, resolving any placeholders found. + * + * @author Juergen Hoeller + * @since 1.2 + * @see BeanDefinition + * @see BeanDefinition#getPropertyValues + * @see BeanDefinition#getConstructorArgumentValues + * @see PropertyPlaceholderConfigurer + */ +public class BeanDefinitionVisitor { + + private StringValueResolver valueResolver; + + + /** + * Create a new BeanDefinitionVisitor, applying the specified + * value resolver to all bean metadata values. + * @param valueResolver the StringValueResolver to apply + */ + public BeanDefinitionVisitor(StringValueResolver valueResolver) { + Assert.notNull(valueResolver, "StringValueResolver must not be null"); + this.valueResolver = valueResolver; + } + + /** + * Create a new BeanDefinitionVisitor for subclassing. + * Subclasses need to override the {@link #resolveStringValue} method. + */ + protected BeanDefinitionVisitor() { + } + + + /** + * Traverse the given BeanDefinition object and the MutablePropertyValues + * and ConstructorArgumentValues contained in them. + * @param beanDefinition the BeanDefinition object to traverse + * @see #resolveStringValue(String) + */ + public void visitBeanDefinition(BeanDefinition beanDefinition) { + visitParentName(beanDefinition); + visitBeanClassName(beanDefinition); + visitFactoryBeanName(beanDefinition); + visitFactoryMethodName(beanDefinition); + visitScope(beanDefinition); + visitPropertyValues(beanDefinition.getPropertyValues()); + ConstructorArgumentValues cas = beanDefinition.getConstructorArgumentValues(); + visitIndexedArgumentValues(cas.getIndexedArgumentValues()); + visitGenericArgumentValues(cas.getGenericArgumentValues()); + } + + protected void visitParentName(BeanDefinition beanDefinition) { + String parentName = beanDefinition.getParentName(); + if (parentName != null) { + String resolvedName = resolveStringValue(parentName); + if (!parentName.equals(resolvedName)) { + beanDefinition.setParentName(resolvedName); + } + } + } + + protected void visitBeanClassName(BeanDefinition beanDefinition) { + String beanClassName = beanDefinition.getBeanClassName(); + if (beanClassName != null) { + String resolvedName = resolveStringValue(beanClassName); + if (!beanClassName.equals(resolvedName)) { + beanDefinition.setBeanClassName(resolvedName); + } + } + } + + protected void visitFactoryBeanName(BeanDefinition beanDefinition) { + String factoryBeanName = beanDefinition.getFactoryBeanName(); + if (factoryBeanName != null) { + String resolvedName = resolveStringValue(factoryBeanName); + if (!factoryBeanName.equals(resolvedName)) { + beanDefinition.setFactoryBeanName(resolvedName); + } + } + } + + protected void visitFactoryMethodName(BeanDefinition beanDefinition) { + String factoryMethodName = beanDefinition.getFactoryBeanName(); + if (factoryMethodName != null) { + String resolvedName = resolveStringValue(factoryMethodName); + if (!factoryMethodName.equals(resolvedName)) { + beanDefinition.setFactoryMethodName(resolvedName); + } + } + } + + protected void visitScope(BeanDefinition beanDefinition) { + String scope = beanDefinition.getScope(); + if (scope != null) { + String resolvedScope = resolveStringValue(scope); + if (!scope.equals(resolvedScope)) { + beanDefinition.setScope(resolvedScope); + } + } + } + + protected void visitPropertyValues(MutablePropertyValues pvs) { + PropertyValue[] pvArray = pvs.getPropertyValues(); + for (int i = 0; i < pvArray.length; i++) { + PropertyValue pv = pvArray[i]; + Object newVal = resolveValue(pv.getValue()); + if (!ObjectUtils.nullSafeEquals(newVal, pv.getValue())) { + pvs.addPropertyValue(pv.getName(), newVal); + } + } + } + + protected void visitIndexedArgumentValues(Map ias) { + for (Iterator it = ias.values().iterator(); it.hasNext();) { + ConstructorArgumentValues.ValueHolder valueHolder = + (ConstructorArgumentValues.ValueHolder) it.next(); + Object newVal = resolveValue(valueHolder.getValue()); + if (!ObjectUtils.nullSafeEquals(newVal, valueHolder.getValue())) { + valueHolder.setValue(newVal); + } + } + } + + protected void visitGenericArgumentValues(List gas) { + for (Iterator it = gas.iterator(); it.hasNext();) { + ConstructorArgumentValues.ValueHolder valueHolder = + (ConstructorArgumentValues.ValueHolder) it.next(); + Object newVal = resolveValue(valueHolder.getValue()); + if (!ObjectUtils.nullSafeEquals(newVal, valueHolder.getValue())) { + valueHolder.setValue(newVal); + } + } + } + + protected Object resolveValue(Object value) { + if (value instanceof BeanDefinition) { + visitBeanDefinition((BeanDefinition) value); + } + else if (value instanceof BeanDefinitionHolder) { + visitBeanDefinition(((BeanDefinitionHolder) value).getBeanDefinition()); + } + else if (value instanceof RuntimeBeanReference) { + RuntimeBeanReference ref = (RuntimeBeanReference) value; + String newBeanName = resolveStringValue(ref.getBeanName()); + if (!newBeanName.equals(ref.getBeanName())) { + return new RuntimeBeanReference(newBeanName); + } + } + else if (value instanceof List) { + visitList((List) value); + } + else if (value instanceof Set) { + visitSet((Set) value); + } + else if (value instanceof Map) { + visitMap((Map) value); + } + else if (value instanceof TypedStringValue) { + TypedStringValue typedStringValue = (TypedStringValue) value; + String stringValue = typedStringValue.getValue(); + if (stringValue != null) { + String visitedString = resolveStringValue(stringValue); + typedStringValue.setValue(visitedString); + } + } + else if (value instanceof String) { + return resolveStringValue((String) value); + } + return value; + } + + protected void visitList(List listVal) { + for (int i = 0; i < listVal.size(); i++) { + Object elem = listVal.get(i); + Object newVal = resolveValue(elem); + if (!ObjectUtils.nullSafeEquals(newVal, elem)) { + listVal.set(i, newVal); + } + } + } + + protected void visitSet(Set setVal) { + Set newContent = new LinkedHashSet(); + boolean entriesModified = false; + for (Iterator it = setVal.iterator(); it.hasNext();) { + Object elem = it.next(); + int elemHash = (elem != null ? elem.hashCode() : 0); + Object newVal = resolveValue(elem); + int newValHash = (newVal != null ? newVal.hashCode() : 0); + newContent.add(newVal); + entriesModified = entriesModified || (newVal != elem || newValHash != elemHash); + } + if (entriesModified) { + setVal.clear(); + setVal.addAll(newContent); + } + } + + protected void visitMap(Map mapVal) { + Map newContent = new LinkedHashMap(); + boolean entriesModified = false; + for (Iterator it = mapVal.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + Object key = entry.getKey(); + int keyHash = (key != null ? key.hashCode() : 0); + Object newKey = resolveValue(key); + int newKeyHash = (newKey != null ? newKey.hashCode() : 0); + Object val = entry.getValue(); + Object newVal = resolveValue(val); + newContent.put(newKey, newVal); + entriesModified = entriesModified || (newVal != val || newKey != key || newKeyHash != keyHash); + } + if (entriesModified) { + mapVal.clear(); + mapVal.putAll(newContent); + } + } + + /** + * Resolve the given String value, for example parsing placeholders. + * @param strVal the original String value + * @return the resolved String value + */ + protected String resolveStringValue(String strVal) { + if (this.valueResolver == null) { + throw new IllegalStateException("No StringValueResolver specified - pass a resolver " + + "object into the constructor or override the 'resolveStringValue' method"); + } + return this.valueResolver.resolveStringValue(strVal); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanFactoryPostProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/BeanFactoryPostProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanFactoryPostProcessor.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.beans.BeansException; + +/** + * Allows for custom modification of an application context's bean definitions, + * adapting the bean property values of the context's underlying bean factory. + * + *

    Application contexts can auto-detect BeanFactoryPostProcessor beans in + * their bean definitions and apply them before any other beans get created. + * + *

    Useful for custom config files targeted at system administrators that + * override bean properties configured in the application context. + * + *

    See PropertyResourceConfigurer and its concrete implementations + * for out-of-the-box solutions that address such configuration needs. + * + * @author Juergen Hoeller + * @since 06.07.2003 + * @see BeanPostProcessor + * @see PropertyResourceConfigurer + */ +public interface BeanFactoryPostProcessor { + + /** + * Modify the application context's internal bean factory after its standard + * initialization. All bean definitions will have been loaded, but no beans + * will have been instantiated yet. This allows for overriding or adding + * properties even to eager-initializing beans. + * @param beanFactory the bean factory used by the application context + * @throws org.springframework.beans.BeansException in case of errors + */ + void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanPostProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/BeanPostProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanPostProcessor.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.beans.BeansException; + +/** + * Factory hook that allows for custom modification of new bean instances, + * e.g. checking for marker interfaces or wrapping them with proxies. + * + *

    ApplicationContexts can autodetect BeanPostProcessor beans in their + * bean definitions and apply them to any beans subsequently created. + * Plain bean factories allow for programmatic registration of post-processors, + * applying to all beans created through this factory. + * + *

    Typically, post-processors that populate beans via marker interfaces + * or the like will implement {@link #postProcessBeforeInitialization}, + * while post-processors that wrap beans with proxies will normally + * implement {@link #postProcessAfterInitialization}. + * + * @author Juergen Hoeller + * @since 10.10.2003 + * @see InstantiationAwareBeanPostProcessor + * @see DestructionAwareBeanPostProcessor + * @see ConfigurableBeanFactory#addBeanPostProcessor + * @see BeanFactoryPostProcessor + */ +public interface BeanPostProcessor { + + /** + * Apply this BeanPostProcessor to the given new bean instance before any bean + * initialization callbacks (like InitializingBean's afterPropertiesSet + * or a custom init-method). The bean will already be populated with property values. + * The returned bean instance may be a wrapper around the original. + * @param bean the new bean instance + * @param beanName the name of the bean + * @return the bean instance to use, either the original or a wrapped one + * @throws org.springframework.beans.BeansException in case of errors + * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet + */ + Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException; + + /** + * Apply this BeanPostProcessor to the given new bean instance after any bean + * initialization callbacks (like InitializingBean's afterPropertiesSet + * or a custom init-method). The bean will already be populated with property values. + * The returned bean instance may be a wrapper around the original. + *

    In case of a FactoryBean, this callback will be invoked for both the FactoryBean + * instance and the objects created by the FactoryBean (as of Spring 2.0). The + * post-processor can decide whether to apply to either the FactoryBean or created + * objects or both through corresponding bean instanceof FactoryBean checks. + *

    This callback will also be invoked after a short-circuiting triggered by a + * {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method, + * in contrast to all other BeanPostProcessor callbacks. + * @param bean the new bean instance + * @param beanName the name of the bean + * @return the bean instance to use, either the original or a wrapped one + * @throws org.springframework.beans.BeansException in case of errors + * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet + * @see org.springframework.beans.factory.FactoryBean + */ + Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/BeanReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanReference.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.beans.BeanMetadataElement; + +/** + * Interface that exposes a reference to a bean name in an abstract fashion. + * This interface does not necessarily imply a reference to an actual bean + * instance; it just expresses a logical reference to the name of a bean. + * + *

    Serves as common interface implemented by any kind of bean reference + * holder, such as {@link RuntimeBeanReference RuntimeBeanReference} and + * {@link RuntimeBeanNameReference RuntimeBeanNameReference}. + * + * @author Juergen Hoeller + * @since 2.0 + */ +public interface BeanReference extends BeanMetadataElement { + + /** + * Return the target bean name that this reference points to (never null). + */ + String getBeanName(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanReferenceFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/BeanReferenceFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/BeanReferenceFactoryBean.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,108 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.FactoryBeanNotInitializedException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.SmartFactoryBean; + +/** + * FactoryBean that exposes an arbitrary target bean under a different name. + * + *

    Usually, the target bean will reside in a different bean definition file, + * using this FactoryBean to link it in and expose it under a different name. + * Effectively, this corresponds to an alias for the target bean. + * + *

    NOTE: For XML bean definition files, an <alias> + * tag is available that effectively achieves the same. + * + *

    A special capability of this FactoryBean is enabled through its configuration + * as bean definition: The "targetBeanName" can be substituted through a placeholder, + * in combination with Spring's {@link PropertyPlaceholderConfigurer}. + * Thanks to Marcus Bristav for pointing this out! + * + * @author Juergen Hoeller + * @since 1.2 + * @see #setTargetBeanName + * @see PropertyPlaceholderConfigurer + */ +public class BeanReferenceFactoryBean implements SmartFactoryBean, BeanFactoryAware { + + private String targetBeanName; + + private BeanFactory beanFactory; + + + /** + * Set the name of the target bean. + *

    This property is required. The value for this property can be + * substituted through a placeholder, in combination with Spring's + * PropertyPlaceholderConfigurer. + * @param targetBeanName the name of the target bean + * @see PropertyPlaceholderConfigurer + */ + public void setTargetBeanName(String targetBeanName) { + this.targetBeanName = targetBeanName; + } + + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + if (this.targetBeanName == null) { + throw new IllegalArgumentException("'targetBeanName' is required"); + } + if (!this.beanFactory.containsBean(this.targetBeanName)) { + throw new NoSuchBeanDefinitionException(this.targetBeanName, this.beanFactory.toString()); + } + } + + + public Object getObject() throws BeansException { + if (this.beanFactory == null) { + throw new FactoryBeanNotInitializedException(); + } + return this.beanFactory.getBean(this.targetBeanName); + } + + public Class getObjectType() { + if (this.beanFactory == null) { + return null; + } + return this.beanFactory.getType(this.targetBeanName); + } + + public boolean isSingleton() { + if (this.beanFactory == null) { + throw new FactoryBeanNotInitializedException(); + } + return this.beanFactory.isSingleton(this.targetBeanName); + } + + public boolean isPrototype() { + if (this.beanFactory == null) { + throw new FactoryBeanNotInitializedException(); + } + return this.beanFactory.isPrototype(this.targetBeanName); + } + + public boolean isEagerInit() { + return false; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/CommonsLogFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/CommonsLogFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/CommonsLogFactoryBean.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; + +/** + * Factory bean for + * commons-logging + * {@link org.apache.commons.logging.Log} instances. + * + *

    Useful for sharing Log instances among multiple beans instead of using + * one Log instance per class name, e.g. for common log topics. + * + * @author Juergen Hoeller + * @see org.apache.commons.logging.Log + * @since 16.11.2003 + */ +public class CommonsLogFactoryBean implements FactoryBean, InitializingBean { + + private Log log; + + + /** + * The name of the log. + *

    This property is required. + * @param logName the name of the log + */ + public void setLogName(String logName) { + this.log = LogFactory.getLog(logName); + } + + + public void afterPropertiesSet() { + if (this.log == null) { + throw new IllegalArgumentException("logName is required"); + } + } + + public Object getObject() { + return log; + } + + public Class getObjectType() { + return (this.log != null ? this.log.getClass() : Log.class); + } + + public boolean isSingleton() { + return true; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/ConfigurableBeanFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/ConfigurableBeanFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/ConfigurableBeanFactory.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,334 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.beans.PropertyEditor; + +import org.springframework.beans.PropertyEditorRegistrar; +import org.springframework.beans.PropertyEditorRegistry; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.HierarchicalBeanFactory; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.util.StringValueResolver; + +/** + * Configuration interface to be implemented by most bean factories. Provides + * facilities to configure a bean factory, in addition to the bean factory + * client methods in the {@link org.springframework.beans.factory.BeanFactory} + * interface. + * + *

    This bean factory interface is not meant to be used in normal application + * code: Stick to {@link org.springframework.beans.factory.BeanFactory} or + * {@link org.springframework.beans.factory.ListableBeanFactory} for typical + * needs. This extended interface is just meant to allow for framework-internal + * plug'n'play and for special access to bean factory configuration methods. + * + * @author Juergen Hoeller + * @since 03.11.2003 + * @see org.springframework.beans.factory.BeanFactory + * @see org.springframework.beans.factory.ListableBeanFactory + * @see ConfigurableListableBeanFactory + */ +public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry { + + /** + * Scope identifier for the standard singleton scope: "singleton". + * Custom scopes can be added via registerScope. + * @see #registerScope + */ + String SCOPE_SINGLETON = "singleton"; + + /** + * Scope identifier for the standard prototype scope: "prototype". + * Custom scopes can be added via registerScope. + * @see #registerScope + */ + String SCOPE_PROTOTYPE = "prototype"; + + + /** + * Set the parent of this bean factory. + *

    Note that the parent cannot be changed: It should only be set outside + * a constructor if it isn't available at the time of factory instantiation. + * @param parentBeanFactory the parent BeanFactory + * @throws IllegalStateException if this factory is already associated with + * a parent BeanFactory + * @see #getParentBeanFactory() + */ + void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException; + + /** + * Set the class loader to use for loading bean classes. + * Default is the thread context class loader. + *

    Note that this class loader will only apply to bean definitions + * that do not carry a resolved bean class yet. This is the case as of + * Spring 2.0 by default: Bean definitions only carry bean class names, + * to be resolved once the factory processes the bean definition. + * @param beanClassLoader the class loader to use, + * or null to suggest the default class loader + */ + void setBeanClassLoader(ClassLoader beanClassLoader); + + /** + * Return this factory's class loader for loading bean classes. + */ + ClassLoader getBeanClassLoader(); + + /** + * Specify a temporary ClassLoader to use for type matching purposes. + * Default is none, simply using the standard bean ClassLoader. + *

    A temporary ClassLoader is usually just specified if + * load-time weaving is involved, to make sure that actual bean + * classes are loaded as lazily as possible. The temporary loader is + * then removed once the BeanFactory completes its bootstrap phase. + */ + void setTempClassLoader(ClassLoader tempClassLoader); + + /** + * Return the temporary ClassLoader to use for type matching purposes, + * if any. + */ + ClassLoader getTempClassLoader(); + + /** + * Set whether to cache bean metadata such as given bean definitions + * (in merged fashion) and resolved bean classes. Default is on. + *

    Turn this flag off to enable hot-refreshing of bean definition objects + * and in particular bean classes. If this flag is off, any creation of a bean + * instance will re-query the bean class loader for newly resolved classes. + */ + void setCacheBeanMetadata(boolean cacheBeanMetadata); + + /** + * Return whether to cache bean metadata such as given bean definitions + * (in merged fashion) and resolved bean classes. + */ + boolean isCacheBeanMetadata(); + + /** + * Add a PropertyEditorRegistrar to be applied to all bean creation processes. + *

    Such a registrar creates new PropertyEditor instances and registers them + * on the given registry, fresh for each bean creation attempt. This avoids + * the need for synchronization on custom editors; hence, it is generally + * preferable to use this method instead of {@link #registerCustomEditor}. + * @param registrar the PropertyEditorRegistrar to register + */ + void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar); + + /** + * Register the given custom property editor for all properties of the + * given type. To be invoked during factory configuration. + *

    Note that this method will register a shared custom editor instance; + * access to that instance will be synchronized for thread-safety. It is + * generally preferable to use {@link #addPropertyEditorRegistrar} instead + * of this method, to avoid for the need for synchronization on custom editors. + * @param requiredType type of the property + * @param propertyEditorClass the {@link PropertyEditor} class to register + */ + void registerCustomEditor(Class requiredType, Class propertyEditorClass); + + /** + * Register the given custom property editor for all properties of the + * given type. To be invoked during factory configuration. + *

    Note that this method will register a shared custom editor instance; + * access to that instance will be synchronized for thread-safety. It is + * generally preferable to use {@link #addPropertyEditorRegistrar} instead + * of this method, to avoid for the need for synchronization on custom editors. + * @param requiredType type of the property + * @param propertyEditor editor to register + * @deprecated as of Spring 2.0.7, in favor of {@link #addPropertyEditorRegistrar} + * and {@link #registerCustomEditor(Class, Class)} + */ + void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor); + + /** + * Initialize the given PropertyEditorRegistry with the custom editors + * that have been registered with this BeanFactory. + * @param registry the PropertyEditorRegistry to initialize + */ + void copyRegisteredEditorsTo(PropertyEditorRegistry registry); + + /** + * Set a custom type converter that this BeanFactory should use for converting + * bean property values, constructor argument values, etc. + *

    This will override the default PropertyEditor mechanism and hence make + * any custom editors or custom editor registrars irrelevant. + * @see #addPropertyEditorRegistrar + * @see #registerCustomEditor + */ + void setTypeConverter(TypeConverter typeConverter); + + /** + * Obtain a type converter as used by this BeanFactory. This may be a fresh + * instance for each call, since TypeConverters are usually not thread-safe. + *

    If the default PropertyEditor mechanism is active, the returned + * TypeConverter will be aware of all custom editors that have been registered. + */ + TypeConverter getTypeConverter(); + + /** + * Add a new BeanPostProcessor that will get applied to beans created + * by this factory. To be invoked during factory configuration. + *

    Note: Post-processors submitted here will be applied in the order of + * registration; any ordering semantics expressed through implementing the + * {@link org.springframework.core.Ordered} interface will be ignored. Note + * that autodetected post-processors (e.g. as beans in an ApplicationContext) + * will always be applied after programmatically registered ones. + * @param beanPostProcessor the post-processor to register + */ + void addBeanPostProcessor(BeanPostProcessor beanPostProcessor); + + /** + * Return the current number of registered BeanPostProcessors, if any. + */ + int getBeanPostProcessorCount(); + + /** + * Register the given scope, backed by the given Scope implementation. + * @param scopeName the scope identifier + * @param scope the backing Scope implementation + */ + void registerScope(String scopeName, Scope scope); + + /** + * Return the names of all currently registered scopes. + *

    This will only return the names of explicitly registered scopes. + * Built-in scopes such as "singleton" and "prototype" won't be exposed. + * @return the array of scope names, or an empty array if none + * @see #registerScope + */ + String[] getRegisteredScopeNames(); + + /** + * Return the Scope implementation for the given scope name, if any. + *

    This will only return explicitly registered scopes. + * Built-in scopes such as "singleton" and "prototype" won't be exposed. + * @param scopeName the name of the scope + * @return the registered Scope implementation, or null if none + * @see #registerScope + */ + Scope getRegisteredScope(String scopeName); + + /** + * Copy all relevant configuration from the given other factory. + *

    Should include all standard configuration settings as well as + * BeanPostProcessors, Scopes, and factory-specific internal settings. + * Should not include any metadata of actual bean definitions, + * such as BeanDefinition objects and bean name aliases. + * @param otherFactory the other BeanFactory to copy from + */ + void copyConfigurationFrom(ConfigurableBeanFactory otherFactory); + + /** + * Given a bean name, create an alias. We typically use this method to + * support names that are illegal within XML ids (used for bean names). + *

    Typically invoked during factory configuration, but can also be + * used for runtime registration of aliases. Therefore, a factory + * implementation should synchronize alias access. + * @param beanName the canonical name of the target bean + * @param alias the alias to be registered for the bean + * @throws BeanDefinitionStoreException if the alias is already in use + */ + void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException; + + /** + * Resolve all alias target names and aliases registered in this + * factory, applying the given StringValueResolver to them. + *

    The value resolver may for example resolve placeholders + * in target bean names and even in alias names. + * @param valueResolver the StringValueResolver to apply + */ + void resolveAliases(StringValueResolver valueResolver); + + /** + * Return a merged BeanDefinition for the given bean name, + * merging a child bean definition with its parent if necessary. + * Considers bean definitions in ancestor factories as well. + * @param beanName the name of the bean to retrieve the merged definition for + * @return a (potentially merged) BeanDefinition for the given bean + * @throws NoSuchBeanDefinitionException if there is no bean definition with the given name + */ + BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; + + /** + * Determine whether the bean with the given name is a FactoryBean. + * @param name the name of the bean to check + * @return whether the bean is a FactoryBean + * (false means the bean exists but is not a FactoryBean) + * @throws NoSuchBeanDefinitionException if there is no bean with the given name + */ + boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException; + + /** + * Determine whether the specified bean is currently in creation. + * @param beanName the name of the bean + * @return whether the bean is currently in creation + */ + boolean isCurrentlyInCreation(String beanName); + + /** + * Register a dependent bean for the given bean, + * to be destroyed before the given bean is destroyed. + * @param beanName the name of the bean + * @param dependentBeanName the name of the dependent bean + */ + void registerDependentBean(String beanName, String dependentBeanName); + + /** + * Return the names of all beans which depend on the specified bean, if any. + * @param beanName the name of the bean + * @return the array of dependent bean names, or an empty array if none + */ + String[] getDependentBeans(String beanName); + + /** + * Return the names of all beans that the specified bean depends on, if any. + * @param beanName the name of the bean + * @return the array of names of beans which the bean depends on, + * or an empty array if none + */ + String[] getDependenciesForBean(String beanName); + + /** + * Destroy the given bean instance (usually a prototype instance + * obtained from this factory) according to its bean definition. + *

    Any exception that arises during destruction should be caught + * and logged instead of propagated to the caller of this method. + * @param beanName the name of the bean definition + * @param beanInstance the bean instance to destroy + */ + void destroyBean(String beanName, Object beanInstance); + + /** + * Destroy the specified scoped bean in the current target scope, if any. + *

    Any exception that arises during destruction should be caught + * and logged instead of propagated to the caller of this method. + * @param beanName the name of the scoped bean + */ + void destroyScopedBean(String beanName); + + /** + * Destroy all singleton beans in this factory, including inner beans that have + * been registered as disposable. To be called on shutdown of a factory. + *

    Any exception that arises during destruction should be caught + * and logged instead of propagated to the caller of this method. + */ + void destroySingletons(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/ConfigurableListableBeanFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/ConfigurableListableBeanFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/ConfigurableListableBeanFactory.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,133 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; + +/** + * Configuration interface to be implemented by most listable bean factories. + * In addition to {@link ConfigurableBeanFactory}, it provides facilities to + * analyze and modify bean definitions, and to pre-instantiate singletons. + * + *

    This subinterface of {@link org.springframework.beans.factory.BeanFactory} + * is not meant to be used in normal application code: Stick to + * {@link org.springframework.beans.factory.BeanFactory} or + * {@link org.springframework.beans.factory.ListableBeanFactory} for typical + * use cases. This interface is just meant to allow for framework-internal + * plug'n'play even when needing access to bean factory configuration methods. + * + * @author Juergen Hoeller + * @since 03.11.2003 + * @see org.springframework.context.support.AbstractApplicationContext#getBeanFactory() + */ +public interface ConfigurableListableBeanFactory + extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory { + + /** + * Ignore the given dependency type for autowiring: + * for example, String. Default is none. + * @param type the dependency type to ignore + */ + void ignoreDependencyType(Class type); + + /** + * Ignore the given dependency interface for autowiring. + *

    This will typically be used by application contexts to register + * dependencies that are resolved in other ways, like BeanFactory through + * BeanFactoryAware or ApplicationContext through ApplicationContextAware. + *

    By default, only the BeanFactoryAware interface is ignored. + * For further types to ignore, invoke this method for each type. + * @param ifc the dependency interface to ignore + * @see org.springframework.beans.factory.BeanFactoryAware + * @see org.springframework.context.ApplicationContextAware + */ + void ignoreDependencyInterface(Class ifc); + + /** + * Register a special dependency type with corresponding autowired value. + *

    This is intended for factory/context references that are supposed + * to be autowirable but are not defined as beans in the factory: + * e.g. a dependency of type ApplicationContext resolved to the + * ApplicationContext instance that the bean is living in. + *

    Note: There are no such default types registered in a plain BeanFactory, + * not even for the BeanFactory interface itself. + * @param dependencyType the dependency type to register. This will typically + * be a base interface such as BeanFactory, with extensions of it resolved + * as well if declared as an autowiring dependency (e.g. ListableBeanFactory), + * as long as the given value actually implements the extended interface. + * @param autowiredValue the corresponding autowired value. This may also be an + * implementation of the {@link org.springframework.beans.factory.ObjectFactory} + * interface, which allows for lazy resolution of the actual target value. + */ + void registerResolvableDependency(Class dependencyType, Object autowiredValue); + + /** + * Determine whether the specified bean qualifies as an autowire candidate, + * to be injected into other beans which declare a dependency of matching type. + *

    This method checks ancestor factories as well. + * @param beanName the name of the bean to check + * @param descriptor the descriptor of the dependency to resolve + * @return whether the bean should be considered as autowire candidate + * @throws NoSuchBeanDefinitionException if there is no bean with the given name + */ + boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor) + throws NoSuchBeanDefinitionException; + + /** + * Return the registered BeanDefinition for the specified bean, allowing access + * to its property values and constructor argument value (which can be + * modified during bean factory post-processing). + *

    A returned BeanDefinition object should not be a copy but the original + * definition object as registered in the factory. This means that it should + * be castable to a more specific implementation type, if necessary. + *

    NOTE: This method does not consider ancestor factories. + * It is only meant for accessing local bean definitions of this factory. + * @param beanName the name of the bean + * @return the registered BeanDefinition + * @throws NoSuchBeanDefinitionException if there is no bean with the given name + * defined in this factory + */ + BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; + + /** + * Freeze all bean definitions, signalling that the registered bean definitions + * will not be modified or post-processed any further. + *

    This allows the factory to aggressively cache bean definition metadata. + */ + void freezeConfiguration(); + + /** + * Return whether this factory's bean definitions are frozen, + * i.e. are not supposed to be modified or post-processed any further. + * @return true if the factory's configuration is considered frozen + */ + boolean isConfigurationFrozen(); + + /** + * Ensure that all non-lazy-init singletons are instantiated, also considering + * {@link org.springframework.beans.factory.FactoryBean FactoryBeans}. + * Typically invoked at the end of factory setup, if desired. + * @throws BeansException if one of the singleton beans could not be created. + * Note: This may have left the factory with some beans already initialized! + * Call {@link #destroySingletons()} for full cleanup in this case. + * @see #destroySingletons() + */ + void preInstantiateSingletons() throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/ConstructorArgumentValues.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/ConstructorArgumentValues.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/ConstructorArgumentValues.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,502 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.beans.Mergeable; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; + +/** + * Holder for constructor argument values, typically as part of a bean definition. + * + *

    Supports values for a specific index in the constructor argument list + * as well as for generic argument matches by type. + * + * @author Juergen Hoeller + * @since 09.11.2003 + * @see BeanDefinition#getConstructorArgumentValues + */ +public class ConstructorArgumentValues { + + private final Map indexedArgumentValues = new HashMap(); + + private final List genericArgumentValues = new LinkedList(); + + + /** + * Create a new empty ConstructorArgumentValues object. + */ + public ConstructorArgumentValues() { + } + + /** + * Deep copy constructor. + * @param original the ConstructorArgumentValues to copy + */ + public ConstructorArgumentValues(ConstructorArgumentValues original) { + addArgumentValues(original); + } + + /** + * Copy all given argument values into this object, using separate holder + * instances to keep the values independent from the original object. + *

    Note: Identical ValueHolder instances will only be registered once, + * to allow for merging and re-merging of argument value definitions. Distinct + * ValueHolder instances carrying the same content are of course allowed. + */ + public void addArgumentValues(ConstructorArgumentValues other) { + if (other != null) { + for (Iterator it = other.indexedArgumentValues.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + ValueHolder valueHolder = (ValueHolder) entry.getValue(); + addOrMergeIndexedArgumentValue(entry.getKey(), valueHolder.copy()); + } + for (Iterator it = other.genericArgumentValues.iterator(); it.hasNext();) { + ValueHolder valueHolder = (ValueHolder) it.next(); + if (!this.genericArgumentValues.contains(valueHolder)) { + this.genericArgumentValues.add(valueHolder.copy()); + } + } + } + } + + + /** + * Add argument value for the given index in the constructor argument list. + * @param index the index in the constructor argument list + * @param value the argument value + */ + public void addIndexedArgumentValue(int index, Object value) { + addIndexedArgumentValue(index, new ValueHolder(value)); + } + + /** + * Add argument value for the given index in the constructor argument list. + * @param index the index in the constructor argument list + * @param value the argument value + * @param type the type of the constructor argument + */ + public void addIndexedArgumentValue(int index, Object value, String type) { + addIndexedArgumentValue(index, new ValueHolder(value, type)); + } + + /** + * Add argument value for the given index in the constructor argument list. + * @param index the index in the constructor argument list + * @param newValue the argument value in the form of a ValueHolder + */ + public void addIndexedArgumentValue(int index, ValueHolder newValue) { + Assert.isTrue(index >= 0, "Index must not be negative"); + Assert.notNull(newValue, "ValueHolder must not be null"); + addOrMergeIndexedArgumentValue(new Integer(index), newValue); + } + + /** + * Add argument value for the given index in the constructor argument list, + * merging the new value (typically a collection) with the current value + * if demanded: see {@link org.springframework.beans.Mergeable}. + * @param key the index in the constructor argument list + * @param newValue the argument value in the form of a ValueHolder + */ + private void addOrMergeIndexedArgumentValue(Object key, ValueHolder newValue) { + ValueHolder currentValue = (ValueHolder) this.indexedArgumentValues.get(key); + if (currentValue != null && newValue.getValue() instanceof Mergeable) { + Mergeable mergeable = (Mergeable) newValue.getValue(); + if (mergeable.isMergeEnabled()) { + newValue.setValue(mergeable.merge(currentValue.getValue())); + } + } + this.indexedArgumentValues.put(key, newValue); + } + + /** + * Get argument value for the given index in the constructor argument list. + * @param index the index in the constructor argument list + * @param requiredType the type to match (can be null to match + * untyped values only) + * @return the ValueHolder for the argument, or null if none set + */ + public ValueHolder getIndexedArgumentValue(int index, Class requiredType) { + Assert.isTrue(index >= 0, "Index must not be negative"); + ValueHolder valueHolder = (ValueHolder) this.indexedArgumentValues.get(new Integer(index)); + if (valueHolder != null) { + if (valueHolder.getType() == null || + (requiredType != null && requiredType.getName().equals(valueHolder.getType()))) { + return valueHolder; + } + } + return null; + } + + /** + * Return the map of indexed argument values. + * @return unmodifiable Map with Integer index as key and ValueHolder as value + * @see ValueHolder + */ + public Map getIndexedArgumentValues() { + return Collections.unmodifiableMap(this.indexedArgumentValues); + } + + + /** + * Add generic argument value to be matched by type. + *

    Note: A single generic argument value will just be used once, + * rather than matched multiple times (as of Spring 1.1). + * @param value the argument value + */ + public void addGenericArgumentValue(Object value) { + this.genericArgumentValues.add(new ValueHolder(value)); + } + + /** + * Add generic argument value to be matched by type. + *

    Note: A single generic argument value will just be used once, + * rather than matched multiple times (as of Spring 1.1). + * @param value the argument value + * @param type the type of the constructor argument + */ + public void addGenericArgumentValue(Object value, String type) { + this.genericArgumentValues.add(new ValueHolder(value, type)); + } + + /** + * Add generic argument value to be matched by type. + *

    Note: A single generic argument value will just be used once, + * rather than matched multiple times (as of Spring 1.1). + * @param newValue the argument value in the form of a ValueHolder + *

    Note: Identical ValueHolder instances will only be registered once, + * to allow for merging and re-merging of argument value definitions. Distinct + * ValueHolder instances carrying the same content are of course allowed. + */ + public void addGenericArgumentValue(ValueHolder newValue) { + Assert.notNull(newValue, "ValueHolder must not be null"); + if (!this.genericArgumentValues.contains(newValue)) { + this.genericArgumentValues.add(newValue); + } + } + + /** + * Look for a generic argument value that matches the given type. + * @param requiredType the type to match (can be null to find + * an arbitrary next generic argument value) + * @return the ValueHolder for the argument, or null if none set + */ + public ValueHolder getGenericArgumentValue(Class requiredType) { + return getGenericArgumentValue(requiredType, null); + } + + /** + * Look for the next generic argument value that matches the given type, + * ignoring argument values that have already been used in the current + * resolution process. + * @param requiredType the type to match (can be null to find + * an arbitrary next generic argument value) + * @param usedValueHolders a Set of ValueHolder objects that have already been used + * in the current resolution process and should therefore not be returned again + * @return the ValueHolder for the argument, or null if none found + */ + public ValueHolder getGenericArgumentValue(Class requiredType, Set usedValueHolders) { + for (Iterator it = this.genericArgumentValues.iterator(); it.hasNext();) { + ValueHolder valueHolder = (ValueHolder) it.next(); + if (usedValueHolders == null || !usedValueHolders.contains(valueHolder)) { + if (requiredType != null) { + // Check matching type. + if (valueHolder.getType() != null) { + if (valueHolder.getType().equals(requiredType.getName())) { + return valueHolder; + } + } + else if (ClassUtils.isAssignableValue(requiredType, valueHolder.getValue())) { + return valueHolder; + } + } + else { + // No required type specified -> consider untyped values only. + if (valueHolder.getType() == null) { + return valueHolder; + } + } + } + } + return null; + } + + /** + * Return the list of generic argument values. + * @return unmodifiable List of ValueHolders + * @see ValueHolder + */ + public List getGenericArgumentValues() { + return Collections.unmodifiableList(this.genericArgumentValues); + } + + + /** + * Look for an argument value that either corresponds to the given index + * in the constructor argument list or generically matches by type. + * @param index the index in the constructor argument list + * @param requiredType the type to match + * @return the ValueHolder for the argument, or null if none set + */ + public ValueHolder getArgumentValue(int index, Class requiredType) { + return getArgumentValue(index, requiredType, null); + } + + /** + * Look for an argument value that either corresponds to the given index + * in the constructor argument list or generically matches by type. + * @param index the index in the constructor argument list + * @param requiredType the type to match (can be null to find + * an untyped argument value) + * @param usedValueHolders a Set of ValueHolder objects that have already + * been used in the current resolution process and should therefore not + * be returned again (allowing to return the next generic argument match + * in case of multiple generic argument values of the same type) + * @return the ValueHolder for the argument, or null if none set + */ + public ValueHolder getArgumentValue(int index, Class requiredType, Set usedValueHolders) { + Assert.isTrue(index >= 0, "Index must not be negative"); + ValueHolder valueHolder = getIndexedArgumentValue(index, requiredType); + if (valueHolder == null) { + valueHolder = getGenericArgumentValue(requiredType, usedValueHolders); + } + return valueHolder; + } + + /** + * Return the number of argument values held in this instance, + * counting both indexed and generic argument values. + */ + public int getArgumentCount() { + return (this.indexedArgumentValues.size() + this.genericArgumentValues.size()); + } + + /** + * Return if this holder does not contain any argument values, + * neither indexed ones nor generic ones. + */ + public boolean isEmpty() { + return (this.indexedArgumentValues.isEmpty() && this.genericArgumentValues.isEmpty()); + } + + /** + * Clear this holder, removing all argument values. + */ + public void clear() { + this.indexedArgumentValues.clear(); + this.genericArgumentValues.clear(); + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof ConstructorArgumentValues)) { + return false; + } + ConstructorArgumentValues that = (ConstructorArgumentValues) other; + if (this.genericArgumentValues.size() != that.genericArgumentValues.size() || + this.indexedArgumentValues.size() != that.indexedArgumentValues.size()) { + return false; + } + Iterator it1 = this.genericArgumentValues.iterator(); + Iterator it2 = that.genericArgumentValues.iterator(); + while (it1.hasNext() && it2.hasNext()) { + ValueHolder vh1 = (ValueHolder) it1.next(); + ValueHolder vh2 = (ValueHolder) it2.next(); + if (!vh1.contentEquals(vh2)) { + return false; + } + } + for (Iterator it = this.indexedArgumentValues.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + ValueHolder vh1 = (ValueHolder) entry.getValue(); + ValueHolder vh2 = (ValueHolder) that.indexedArgumentValues.get(entry.getKey()); + if (!vh1.contentEquals(vh2)) { + return false; + } + } + return true; + } + + public int hashCode() { + int hashCode = 7; + for (Iterator it = this.genericArgumentValues.iterator(); it.hasNext();) { + ValueHolder valueHolder = (ValueHolder) it.next(); + hashCode = 31 * hashCode + valueHolder.contentHashCode(); + } + hashCode = 29 * hashCode; + for (Iterator it = this.indexedArgumentValues.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + Integer key = (Integer) entry.getKey(); + ValueHolder value = (ValueHolder) entry.getValue(); + hashCode = 31 * hashCode + (value.contentHashCode() ^ key.hashCode()); + } + return hashCode; + } + + + /** + * Holder for a constructor argument value, with an optional type + * attribute indicating the target type of the actual constructor argument. + */ + public static class ValueHolder implements BeanMetadataElement { + + private Object value; + + private String type; + + private Object source; + + private boolean converted = false; + + private Object convertedValue; + + /** + * Create a new ValueHolder for the given value. + * @param value the argument value + */ + public ValueHolder(Object value) { + this.value = value; + } + + /** + * Create a new ValueHolder for the given value and type. + * @param value the argument value + * @param type the type of the constructor argument + */ + public ValueHolder(Object value, String type) { + this.value = value; + this.type = type; + } + + /** + * Set the value for the constructor argument. + * Only necessary for manipulating a registered value, + * for example in BeanFactoryPostProcessors. + * @see PropertyPlaceholderConfigurer + */ + public void setValue(Object value) { + this.value = value; + } + + /** + * Return the value for the constructor argument. + */ + public Object getValue() { + return this.value; + } + + /** + * Set the type of the constructor argument. + * Only necessary for manipulating a registered value, + * for example in BeanFactoryPostProcessors. + * @see PropertyPlaceholderConfigurer + */ + public void setType(String type) { + this.type = type; + } + + /** + * Return the type of the constructor argument. + */ + public String getType() { + return this.type; + } + + /** + * Set the configuration source Object for this metadata element. + *

    The exact type of the object will depend on the configuration mechanism used. + */ + public void setSource(Object source) { + this.source = source; + } + + public Object getSource() { + return this.source; + } + + /** + * Return whether this holder contains a converted value already (true), + * or whether the value still needs to be converted (false). + */ + public synchronized boolean isConverted() { + return this.converted; + } + + /** + * Set the converted value of the constructor argument, + * after processed type conversion. + */ + public synchronized void setConvertedValue(Object value) { + this.converted = true; + this.convertedValue = value; + } + + /** + * Return the converted value of the constructor argument, + * after processed type conversion. + */ + public synchronized Object getConvertedValue() { + return this.convertedValue; + } + + /** + * Determine whether the content of this ValueHolder is equal + * to the content of the given other ValueHolder. + *

    Note that ValueHolder does not implement equals + * directly, to allow for multiple ValueHolder instances with the + * same content to reside in the same Set. + */ + private boolean contentEquals(ValueHolder other) { + return (this == other || + (ObjectUtils.nullSafeEquals(this.value, other.value) && ObjectUtils.nullSafeEquals(this.type, other.type))); + } + + /** + * Determine whether the hash code of the content of this ValueHolder. + *

    Note that ValueHolder does not implement hashCode + * directly, to allow for multiple ValueHolder instances with the + * same content to reside in the same Set. + */ + private int contentHashCode() { + return ObjectUtils.nullSafeHashCode(this.value) * 29 + ObjectUtils.nullSafeHashCode(this.type); + } + + /** + * Create a copy of this ValueHolder: that is, an independent + * ValueHolder instance with the same contents. + */ + public ValueHolder copy() { + ValueHolder copy = new ValueHolder(this.value, this.type); + copy.setSource(this.source); + return copy; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/CustomEditorConfigurer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/CustomEditorConfigurer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/CustomEditorConfigurer.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,208 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.beans.PropertyEditor; +import java.util.Iterator; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.BeansException; +import org.springframework.beans.FatalBeanException; +import org.springframework.beans.PropertyEditorRegistrar; +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.core.Ordered; +import org.springframework.util.ClassUtils; + +/** + * {@link BeanFactoryPostProcessor} implementation that allows for convenient + * registration of custom {@link PropertyEditor property editors}. + * + *

    As of Spring 2.0, the recommended usage is to use custom + * {@link PropertyEditorRegistrar} implementations that in turn register + * any desired editors on a given + * {@link org.springframework.beans.PropertyEditorRegistry registry}. + * Each PropertyEditorRegistrar can register any number of custom editors. + * + *

    + * <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    + *   <property name="propertyEditorRegistrars">
    + *     <list>
    + *       <bean class="mypackage.MyCustomDateEditorRegistrar"/>
    + *       <bean class="mypackage.MyObjectEditorRegistrar"/>
    + *     </list>
    + *   </property>
    + * </bean>
    + * + *

    Alternative configuration example with custom editor classes: + * + *

    + * <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    + *   <property name="customEditors">
    + *     <map>
    + *       <entry key="java.util.Date" value="mypackage.MyCustomDateEditor"/>
    + *       <entry key="mypackage.MyObject" value="mypackage.MyObjectEditor"/>
    + *     </map>
    + *   </property>
    + * </bean>
    + * + *

    Also supports "java.lang.String[]"-style array class names and primitive + * class names (e.g. "boolean"). Delegates to {@link ClassUtils} for actual + * class name resolution. + * + *

    NOTE: Custom property editors registered with this configurer do + * not apply to data binding. Custom editors for data binding need to + * be registered on the {@link org.springframework.validation.DataBinder}: + * Use a common base class or delegate to common PropertyEditorRegistrar + * implementations to reuse editor registration there. + * + * @author Juergen Hoeller + * @since 27.02.2004 + * @see java.beans.PropertyEditor + * @see org.springframework.beans.PropertyEditorRegistrar + * @see ConfigurableBeanFactory#addPropertyEditorRegistrar + * @see ConfigurableBeanFactory#registerCustomEditor + * @see org.springframework.validation.DataBinder#registerCustomEditor + * @see org.springframework.web.servlet.mvc.BaseCommandController#setPropertyEditorRegistrars + * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder + */ +public class CustomEditorConfigurer implements BeanFactoryPostProcessor, BeanClassLoaderAware, Ordered { + + protected final Log logger = LogFactory.getLog(getClass()); + + private int order = Ordered.LOWEST_PRECEDENCE; // default: same as non-Ordered + + private PropertyEditorRegistrar[] propertyEditorRegistrars; + + private Map customEditors; + + private boolean ignoreUnresolvableEditors = false; + + private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); + + + public void setOrder(int order) { + this.order = order; + } + + public int getOrder() { + return this.order; + } + + /** + * Specify the {@link PropertyEditorRegistrar PropertyEditorRegistrars} + * to apply to beans defined within the current application context. + *

    This allows for sharing PropertyEditorRegistrars with + * {@link org.springframework.validation.DataBinder DataBinders}, etc. + * Furthermore, it avoids the need for synchronization on custom editors: + * A PropertyEditorRegistrar will always create fresh editor + * instances for each bean creation attempt. + * @see ConfigurableListableBeanFactory#addPropertyEditorRegistrar + */ + public void setPropertyEditorRegistrars(PropertyEditorRegistrar[] propertyEditorRegistrars) { + this.propertyEditorRegistrars = propertyEditorRegistrars; + } + + /** + * Specify the custom editors to register via a {@link Map}, using the + * class name of the required type as the key and the class name of the + * associated {@link PropertyEditor} as value. + *

    Also supports {@link PropertyEditor} instances as values; however, + * this is deprecated since Spring 2.0.7 and will be removed in Spring 3.0. + * @param customEditors said Map of editors (can be null) + * @see ConfigurableListableBeanFactory#registerCustomEditor + */ + public void setCustomEditors(Map customEditors) { + this.customEditors = customEditors; + } + + /** + * Set whether unresolvable editors should simply be skipped. + * Default is to raise an exception in such a case. + *

    This typically applies to either the editor class or the required type + * class not being found in the classpath. If you expect this to happen in + * some deployments and prefer to simply ignore the affected editors, + * then switch this flag to "true". + */ + public void setIgnoreUnresolvableEditors(boolean ignoreUnresolvableEditors) { + this.ignoreUnresolvableEditors = ignoreUnresolvableEditors; + } + + public void setBeanClassLoader(ClassLoader beanClassLoader) { + this.beanClassLoader = beanClassLoader; + } + + + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + if (this.propertyEditorRegistrars != null) { + for (int i = 0; i < this.propertyEditorRegistrars.length; i++) { + beanFactory.addPropertyEditorRegistrar(this.propertyEditorRegistrars[i]); + } + } + + if (this.customEditors != null) { + for (Iterator it = this.customEditors.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + Object key = entry.getKey(); + Object value = entry.getValue(); + Class requiredType = null; + + try { + if (key instanceof Class) { + requiredType = (Class) key; + } + else if (key instanceof String) { + requiredType = ClassUtils.forName((String) key, this.beanClassLoader); + } + else { + throw new IllegalArgumentException( + "Invalid key [" + key + "] for custom editor: needs to be Class or String."); + } + + if (value instanceof PropertyEditor) { + beanFactory.registerCustomEditor(requiredType, (PropertyEditor) value); + } + else if (value instanceof Class) { + beanFactory.registerCustomEditor(requiredType, (Class) value); + } + else if (value instanceof String) { + Class editorClass = ClassUtils.forName((String) value, this.beanClassLoader); + beanFactory.registerCustomEditor(requiredType, editorClass); + } + else { + throw new IllegalArgumentException("Mapped value [" + value + "] for custom editor key [" + + key + "] is not of required type [" + PropertyEditor.class.getName() + + "] or a corresponding Class or String value indicating a PropertyEditor implementation"); + } + } + catch (ClassNotFoundException ex) { + if (this.ignoreUnresolvableEditors) { + logger.info("Skipping editor [" + value + "] for required type [" + key + "]: " + + (requiredType != null ? "editor" : "required type") + " class not found."); + } + else { + throw new FatalBeanException( + (requiredType != null ? "Editor" : "Required type") + " class not found", ex); + } + } + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/CustomScopeConfigurer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/CustomScopeConfigurer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/CustomScopeConfigurer.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,111 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.util.Iterator; +import java.util.Map; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.core.Ordered; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; + +/** + * Simple {@link BeanFactoryPostProcessor} implementation that registers + * custom {@link Scope Scope(s)} with the containing {@link ConfigurableBeanFactory}. + * + *

    Will register all of the supplied {@link #setScopes(java.util.Map) scopes} + * with the {@link ConfigurableListableBeanFactory} that is passed to the + * {@link #postProcessBeanFactory(ConfigurableListableBeanFactory)} method. + * + *

    This class allows for declarative registration of custom scopes. + * Alternatively, consider implementing a custom {@link BeanFactoryPostProcessor} + * that calls {@link ConfigurableBeanFactory#registerScope} programmatically. + * + * @author Juergen Hoeller + * @author Rick Evans + * @since 2.0 + * @see ConfigurableBeanFactory#registerScope + */ +public class CustomScopeConfigurer implements BeanFactoryPostProcessor, BeanClassLoaderAware, Ordered { + + private Map scopes; + + private int order = Ordered.LOWEST_PRECEDENCE; + + private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); + + + /** + * Specify the custom scopes that are to be registered. + *

    The keys indicate the scope names (of type String); each value + * is expected to be the corresponding custom {@link Scope} instance + * or class name. + */ + public void setScopes(Map scopes) { + this.scopes = scopes; + } + + public void setOrder(int order) { + this.order = order; + } + + public int getOrder() { + return this.order; + } + + public void setBeanClassLoader(ClassLoader beanClassLoader) { + this.beanClassLoader = beanClassLoader; + } + + + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + if (this.scopes != null) { + for (Iterator it = this.scopes.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + Object key = entry.getKey(); + if (!(key instanceof String)) { + throw new IllegalArgumentException( + "Invalid scope key [" + key + "]: only Strings allowed"); + } + String scopeName = (String) key; + Object value = entry.getValue(); + if (value instanceof Scope) { + beanFactory.registerScope(scopeName, (Scope) value); + } + else if (value instanceof Class) { + Class scopeClass = (Class) value; + Assert.isAssignable(Scope.class, scopeClass); + beanFactory.registerScope(scopeName, (Scope) BeanUtils.instantiateClass(scopeClass)); + } + else if (value instanceof String) { + Class scopeClass = ClassUtils.resolveClassName((String) value, this.beanClassLoader); + Assert.isAssignable(Scope.class, scopeClass); + beanFactory.registerScope(scopeName, (Scope) BeanUtils.instantiateClass(scopeClass)); + } + else { + throw new IllegalArgumentException("Mapped value [" + value + "] for scope key [" + + key + "] is not an instance of required type [" + Scope.class.getName() + + "] or a corresponding Class or String value indicating a Scope implementation"); + } + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/DependencyDescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/DependencyDescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/DependencyDescriptor.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,207 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import org.springframework.core.GenericCollectionTypeResolver; +import org.springframework.core.JdkVersion; +import org.springframework.core.MethodParameter; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; + +/** + * Descriptor for a specific dependency that is about to be injected. + * Wraps a constructor parameter, a method parameter or a field, + * allowing unified access to their metadata. + * + * @author Juergen Hoeller + * @since 2.5 + */ +public class DependencyDescriptor { + + private static final Method fieldAnnotationsMethod = + ClassUtils.getMethodIfAvailable(Field.class, "getAnnotations", new Class[0]); + + + private MethodParameter methodParameter; + + private Field field; + + private final boolean required; + + private final boolean eager; + + private Object[] fieldAnnotations; + + + /** + * Create a new descriptor for a method or constructor parameter. + * Considers the dependency as 'eager'. + * @param methodParameter the MethodParameter to wrap + * @param required whether the dependency is required + */ + public DependencyDescriptor(MethodParameter methodParameter, boolean required) { + this(methodParameter, required, true); + } + + /** + * Create a new descriptor for a method or constructor parameter. + * @param methodParameter the MethodParameter to wrap + * @param required whether the dependency is required + * @param eager whether this dependency is 'eager' in the sense of + * eagerly resolving potential target beans for type matching + */ + public DependencyDescriptor(MethodParameter methodParameter, boolean required, boolean eager) { + Assert.notNull(methodParameter, "MethodParameter must not be null"); + this.methodParameter = methodParameter; + this.required = required; + this.eager = eager; + } + + /** + * Create a new descriptor for a field. + * Considers the dependency as 'eager'. + * @param field the field to wrap + * @param required whether the dependency is required + */ + public DependencyDescriptor(Field field, boolean required) { + this(field, required, true); + } + + /** + * Create a new descriptor for a field. + * @param field the field to wrap + * @param required whether the dependency is required + * @param eager whether this dependency is 'eager' in the sense of + * eagerly resolving potential target beans for type matching + */ + public DependencyDescriptor(Field field, boolean required, boolean eager) { + Assert.notNull(field, "Field must not be null"); + this.field = field; + this.required = required; + this.eager = eager; + } + + + /** + * Return the wrapped MethodParameter, if any. + *

    Note: Either MethodParameter or Field is available. + * @return the MethodParameter, or null if none + */ + public MethodParameter getMethodParameter() { + return this.methodParameter; + } + + /** + * Return the wrapped Field, if any. + *

    Note: Either MethodParameter or Field is available. + * @return the Field, or null if none + */ + public Field getField() { + return this.field; + } + + /** + * Return whether this dependency is required. + */ + public boolean isRequired() { + return this.required; + } + + /** + * Return whether this dependency is 'eager' in the sense of + * eagerly resolving potential target beans for type matching. + */ + public boolean isEager() { + return this.eager; + } + + + /** + * Determine the declared (non-generic) type of the wrapped parameter/field. + * @return the declared type (never null) + */ + public Class getDependencyType() { + return (this.field != null ? this.field.getType() : this.methodParameter.getParameterType()); + } + + /** + * Determine the generic element type of the wrapped Collection parameter/field, if any. + * @return the generic type, or null if none + */ + public Class getCollectionType() { + if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) { + return null; + } + return (this.field != null ? + GenericCollectionTypeResolver.getCollectionFieldType(this.field) : + GenericCollectionTypeResolver.getCollectionParameterType(this.methodParameter)); + } + + /** + * Determine the generic key type of the wrapped Map parameter/field, if any. + * @return the generic type, or null if none + */ + public Class getMapKeyType() { + if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) { + return null; + } + return (this.field != null ? + GenericCollectionTypeResolver.getMapKeyFieldType(this.field) : + GenericCollectionTypeResolver.getMapKeyParameterType(this.methodParameter)); + } + + /** + * Determine the generic value type of the wrapped Map parameter/field, if any. + * @return the generic type, or null if none + */ + public Class getMapValueType() { + if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) { + return null; + } + return (this.field != null ? + GenericCollectionTypeResolver.getMapValueFieldType(this.field) : + GenericCollectionTypeResolver.getMapValueParameterType(this.methodParameter)); + } + + /** + * Obtain the annotations associated with the wrapped parameter/field, if any. + * @return the parameter/field annotations, or null if there is + * no annotation support (on JDK < 1.5). The return value is an Object array + * instead of an Annotation array simply for compatibility with older JDKs; + * feel free to cast it to Annotation[] on JDK 1.5 or higher. + */ + public Object[] getAnnotations() { + if (this.field != null) { + if (this.fieldAnnotations != null) { + return this.fieldAnnotations; + } + if (fieldAnnotationsMethod == null) { + return null; + } + this.fieldAnnotations = (Object[]) ReflectionUtils.invokeMethod(fieldAnnotationsMethod, this.field); + return this.fieldAnnotations; + } + else { + return this.methodParameter.getParameterAnnotations(); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/DestructionAwareBeanPostProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/DestructionAwareBeanPostProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/DestructionAwareBeanPostProcessor.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.beans.BeansException; + +/** + * Subinterface of BeanPostProcessor that adds a before-destruction callback. + * + *

    The typical usage will be to invoke custom destruction callbacks on + * specific bean types, matching corresponding initialization callbacks. + * + * @author Juergen Hoeller + * @since 1.0.1 + * @see org.springframework.web.struts.ActionServletAwareProcessor + */ +public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor { + + /** + * Apply this BeanPostProcessor to the given bean instance before + * its destruction. Can invoke custom destruction callbacks. + *

    Like DisposableBean's destroy and a custom destroy method, + * this callback just applies to singleton beans in the factory (including + * inner beans). + * @param bean the bean instance to be destroyed + * @param beanName the name of the bean + * @throws org.springframework.beans.BeansException in case of errors + * @see org.springframework.beans.factory.DisposableBean + * @see org.springframework.beans.factory.support.AbstractBeanDefinition#setDestroyMethodName + */ + void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/FieldRetrievingFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/FieldRetrievingFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/FieldRetrievingFactoryBean.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,216 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.lang.reflect.Field; + +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.BeanNameAware; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.FactoryBeanNotInitializedException; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; + +/** + * FactoryBean which retrieves a static or non-static field value. + * + *

    Typically used for retrieving public static final constants. Usage example: + * + *

    // standard definition for exposing a static field, specifying the "staticField" property
    + * <bean id="myField" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
    + *   <property name="staticField" value="java.sql.Connection.TRANSACTION_SERIALIZABLE"/>
    + * </bean>
    + *
    + * // convenience version that specifies a static field pattern as bean name
    + * <bean id="java.sql.Connection.TRANSACTION_SERIALIZABLE"
    + *       class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/>
    + * + * + *

    If you are using Spring 2.0, you can also use the following style of configuration for + * public static fields. + * + *

    <util:constant static-field="java.sql.Connection.TRANSACTION_SERIALIZABLE"/>
    + * + * @author Juergen Hoeller + * @since 1.1 + * @see #setStaticField + */ +public class FieldRetrievingFactoryBean implements FactoryBean, BeanNameAware, BeanClassLoaderAware, InitializingBean { + + private Class targetClass; + + private Object targetObject; + + private String targetField; + + private String staticField; + + private String beanName; + + private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); + + // the field we will retrieve + private Field fieldObject; + + + /** + * Set the target class on which the field is defined. + * Only necessary when the target field is static; else, + * a target object needs to be specified anyway. + * @see #setTargetObject + * @see #setTargetField + */ + public void setTargetClass(Class targetClass) { + this.targetClass = targetClass; + } + + /** + * Return the target class on which the field is defined. + */ + public Class getTargetClass() { + return targetClass; + } + + /** + * Set the target object on which the field is defined. + * Only necessary when the target field is not static; + * else, a target class is sufficient. + * @see #setTargetClass + * @see #setTargetField + */ + public void setTargetObject(Object targetObject) { + this.targetObject = targetObject; + } + + /** + * Return the target object on which the field is defined. + */ + public Object getTargetObject() { + return this.targetObject; + } + + /** + * Set the name of the field to be retrieved. + * Refers to either a static field or a non-static field, + * depending on a target object being set. + * @see #setTargetClass + * @see #setTargetObject + */ + public void setTargetField(String targetField) { + this.targetField = StringUtils.trimAllWhitespace(targetField); + } + + /** + * Return the name of the field to be retrieved. + */ + public String getTargetField() { + return this.targetField; + } + + /** + * Set a fully qualified static field name to retrieve, + * e.g. "example.MyExampleClass.MY_EXAMPLE_FIELD". + * Convenient alternative to specifying targetClass and targetField. + * @see #setTargetClass + * @see #setTargetField + */ + public void setStaticField(String staticField) { + this.staticField = StringUtils.trimAllWhitespace(staticField); + } + + /** + * The bean name of this FieldRetrievingFactoryBean will be interpreted + * as "staticField" pattern, if neither "targetClass" nor "targetObject" + * nor "targetField" have been specified. + * This allows for concise bean definitions with just an id/name. + */ + public void setBeanName(String beanName) { + this.beanName = StringUtils.trimAllWhitespace(BeanFactoryUtils.originalBeanName(beanName)); + } + + public void setBeanClassLoader(ClassLoader classLoader) { + this.beanClassLoader = classLoader; + } + + + public void afterPropertiesSet() throws ClassNotFoundException, NoSuchFieldException { + if (this.targetClass != null && this.targetObject != null) { + throw new IllegalArgumentException("Specify either targetClass or targetObject, not both"); + } + + if (this.targetClass == null && this.targetObject == null) { + if (this.targetField != null) { + throw new IllegalArgumentException( + "Specify targetClass or targetObject in combination with targetField"); + } + + // If no other property specified, consider bean name as static field expression. + if (this.staticField == null) { + this.staticField = this.beanName; + } + + // Try to parse static field into class and field. + int lastDotIndex = this.staticField.lastIndexOf('.'); + if (lastDotIndex == -1 || lastDotIndex == this.staticField.length()) { + throw new IllegalArgumentException( + "staticField must be a fully qualified class plus method name: " + + "e.g. 'example.MyExampleClass.MY_EXAMPLE_FIELD'"); + } + String className = this.staticField.substring(0, lastDotIndex); + String fieldName = this.staticField.substring(lastDotIndex + 1); + this.targetClass = ClassUtils.forName(className, this.beanClassLoader); + this.targetField = fieldName; + } + + else if (this.targetField == null) { + // Either targetClass or targetObject specified. + throw new IllegalArgumentException("targetField is required"); + } + + // Try to get the exact method first. + Class targetClass = (this.targetObject != null) ? this.targetObject.getClass() : this.targetClass; + this.fieldObject = targetClass.getField(this.targetField); + } + + + public Object getObject() throws IllegalAccessException { + if (this.fieldObject == null) { + throw new FactoryBeanNotInitializedException(); + } + ReflectionUtils.makeAccessible(this.fieldObject); + if (this.targetObject != null) { + // instance field + return this.fieldObject.get(this.targetObject); + } + else{ + // class field + return this.fieldObject.get(null); + } + } + + public Class getObjectType() { + return (this.fieldObject != null ? this.fieldObject.getType() : null); + } + + public boolean isSingleton() { + return false; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/InstantiationAwareBeanPostProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/InstantiationAwareBeanPostProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/InstantiationAwareBeanPostProcessor.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,109 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.beans.PropertyDescriptor; + +import org.springframework.beans.BeansException; +import org.springframework.beans.PropertyValues; + +/** + * Subinterface of {@link BeanPostProcessor} that adds a before-instantiation callback, + * and a callback after instantiation but before explicit properties are set or + * autowiring occurs. + * + *

    Typically used to suppress default instantiation for specific target beans, + * for example to create proxies with special TargetSources (pooling targets, + * lazily initializing targets, etc), or to implement additional injection strategies + * such as field injection. + * + *

    NOTE: This interface is a special purpose interface, mainly for + * internal use within the framework. It is recommended to implement the plain + * {@link BeanPostProcessor} interface as far as possible, or to derive from + * {@link InstantiationAwareBeanPostProcessorAdapter} in order to be shielded + * from extensions to this interface. + * + * @author Juergen Hoeller + * @author Rod Johnson + * @since 1.2 + * @see org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#setCustomTargetSourceCreators + * @see org.springframework.aop.framework.autoproxy.target.LazyInitTargetSourceCreator + */ +public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor { + + /** + * Apply this BeanPostProcessor before the target bean gets instantiated. + * The returned bean object may be a proxy to use instead of the target bean, + * effectively suppressing default instantiation of the target bean. + *

    If a non-null object is returned by this method, the bean creation process + * will be short-circuited. The only further processing applied is the + * {@link #postProcessAfterInitialization} callback from the configured + * {@link BeanPostProcessor BeanPostProcessors}. + *

    This callback will only be applied to bean definitions with a bean class. + * In particular, it will not be applied to beans with a "factory-method". + *

    Post-processors may implement the extended + * {@link SmartInstantiationAwareBeanPostProcessor} interface in order + * to predict the type of the bean object that they are going to return here. + * @param beanClass the class of the bean to be instantiated + * @param beanName the name of the bean + * @return the bean object to expose instead of a default instance of the target bean, + * or null to proceed with default instantiation + * @throws org.springframework.beans.BeansException in case of errors + * @see org.springframework.beans.factory.support.AbstractBeanDefinition#hasBeanClass + * @see org.springframework.beans.factory.support.AbstractBeanDefinition#getFactoryMethodName + */ + Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException; + + /** + * Perform operations after the bean has been instantiated, via a constructor or factory method, + * but before Spring property population (from explicit properties or autowiring) occurs. + *

    This is the ideal callback for performing field injection on the given bean instance. + * See Spring's own {@link org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor} + * for a typical example. + * @param bean the bean instance created, with properties not having been set yet + * @param beanName the name of the bean + * @return true if properties should be set on the bean; false + * if property population should be skipped. Normal implementations should return true. + * Returning false will also prevent any subsequent InstantiationAwareBeanPostProcessor + * instances being invoked on this bean instance. + * @throws org.springframework.beans.BeansException in case of errors + */ + boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException; + + /** + * Post-process the given property values before the factory applies them + * to the given bean. Allows for checking whether all dependencies have been + * satisfied, for example based on a "Required" annotation on bean property setters. + *

    Also allows for replacing the property values to apply, typically through + * creating a new MutablePropertyValues instance based on the original PropertyValues, + * adding or removing specific values. + * @param pvs the property values that the factory is about to apply (never null) + * @param pds the relevant property descriptors for the target bean (with ignored + * dependency types - which the factory handles specifically - already filtered out) + * @param bean the bean instance created, but whose properties have not yet been set + * @param beanName the name of the bean + * @return the actual property values to apply to to the given bean + * (can be the passed-in PropertyValues instance), or null + * to skip property population + * @throws org.springframework.beans.BeansException in case of errors + * @see org.springframework.beans.MutablePropertyValues + */ + PropertyValues postProcessPropertyValues( + PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) + throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/InstantiationAwareBeanPostProcessorAdapter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/InstantiationAwareBeanPostProcessorAdapter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/InstantiationAwareBeanPostProcessorAdapter.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Constructor; + +import org.springframework.beans.BeansException; +import org.springframework.beans.PropertyValues; + +/** + * Adapter that implements all methods on {@link SmartInstantiationAwareBeanPostProcessor} + * as no-ops, which will not change normal processing of each bean instantiated + * by the container. Subclasses may override merely those methods that they are + * actually interested in. + * + *

    Note that this base class is only recommendable if you actually require + * {@link InstantiationAwareBeanPostProcessor} functionality. If all you need + * is plain {@link BeanPostProcessor} functionality, prefer a straight + * implementation of that (simpler) interface. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + */ +public abstract class InstantiationAwareBeanPostProcessorAdapter implements SmartInstantiationAwareBeanPostProcessor { + + public Class predictBeanType(Class beanClass, String beanName) { + return null; + } + + public Constructor[] determineCandidateConstructors(Class beanClass, String beanName) throws BeansException { + return null; + } + + public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException { + return bean; + } + + public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException { + return null; + } + + public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { + return true; + } + + public PropertyValues postProcessPropertyValues( + PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) + throws BeansException { + + return pvs; + } + + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + return bean; + } + + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + return bean; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/ListFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/ListFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/ListFactoryBean.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,99 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.TypeConverter; +import org.springframework.core.GenericCollectionTypeResolver; +import org.springframework.core.JdkVersion; + +/** + * Simple factory for shared List instances. Allows for central setup + * of Lists via the "list" element in XML bean definitions. + * + * @author Juergen Hoeller + * @since 09.12.2003 + * @see SetFactoryBean + * @see MapFactoryBean + */ +public class ListFactoryBean extends AbstractFactoryBean { + + private List sourceList; + + private Class targetListClass; + + + /** + * Set the source List, typically populated via XML "list" elements. + */ + public void setSourceList(List sourceList) { + this.sourceList = sourceList; + } + + /** + * Set the class to use for the target List. Can be populated with a fully + * qualified class name when defined in a Spring application context. + *

    Default is a java.util.ArrayList. + * @see java.util.ArrayList + */ + public void setTargetListClass(Class targetListClass) { + if (targetListClass == null) { + throw new IllegalArgumentException("'targetListClass' must not be null"); + } + if (!List.class.isAssignableFrom(targetListClass)) { + throw new IllegalArgumentException("'targetListClass' must implement [java.util.List]"); + } + this.targetListClass = targetListClass; + } + + + public Class getObjectType() { + return List.class; + } + + protected Object createInstance() { + if (this.sourceList == null) { + throw new IllegalArgumentException("'sourceList' is required"); + } + List result = null; + if (this.targetListClass != null) { + result = (List) BeanUtils.instantiateClass(this.targetListClass); + } + else { + result = new ArrayList(this.sourceList.size()); + } + Class valueType = null; + if (this.targetListClass != null && JdkVersion.isAtLeastJava15()) { + valueType = GenericCollectionTypeResolver.getCollectionType(this.targetListClass); + } + if (valueType != null) { + TypeConverter converter = getBeanTypeConverter(); + for (Iterator it = this.sourceList.iterator(); it.hasNext();) { + result.add(converter.convertIfNecessary(it.next(), valueType)); + } + } + else { + result.addAll(this.sourceList); + } + return result; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/MapFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/MapFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/MapFactoryBean.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,104 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.TypeConverter; +import org.springframework.core.GenericCollectionTypeResolver; +import org.springframework.core.JdkVersion; + +/** + * Simple factory for shared Map instances. Allows for central setup + * of Maps via the "map" element in XML bean definitions. + * + * @author Juergen Hoeller + * @since 09.12.2003 + * @see SetFactoryBean + * @see ListFactoryBean + */ +public class MapFactoryBean extends AbstractFactoryBean { + + private Map sourceMap; + + private Class targetMapClass; + + + /** + * Set the source Map, typically populated via XML "map" elements. + */ + public void setSourceMap(Map sourceMap) { + this.sourceMap = sourceMap; + } + + /** + * Set the class to use for the target Map. Can be populated with a fully + * qualified class name when defined in a Spring application context. + *

    Default is a linked HashMap, keeping the registration order. + * @see java.util.LinkedHashMap + */ + public void setTargetMapClass(Class targetMapClass) { + if (targetMapClass == null) { + throw new IllegalArgumentException("'targetMapClass' must not be null"); + } + if (!Map.class.isAssignableFrom(targetMapClass)) { + throw new IllegalArgumentException("'targetMapClass' must implement [java.util.Map]"); + } + this.targetMapClass = targetMapClass; + } + + + public Class getObjectType() { + return Map.class; + } + + protected Object createInstance() { + if (this.sourceMap == null) { + throw new IllegalArgumentException("'sourceMap' is required"); + } + Map result = null; + if (this.targetMapClass != null) { + result = (Map) BeanUtils.instantiateClass(this.targetMapClass); + } + else { + result = new LinkedHashMap(this.sourceMap.size()); + } + Class keyType = null; + Class valueType = null; + if (this.targetMapClass != null && JdkVersion.isAtLeastJava15()) { + keyType = GenericCollectionTypeResolver.getMapKeyType(this.targetMapClass); + valueType = GenericCollectionTypeResolver.getMapValueType(this.targetMapClass); + } + if (keyType != null || valueType != null) { + TypeConverter converter = getBeanTypeConverter(); + for (Iterator it = this.sourceMap.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + Object convertedKey = converter.convertIfNecessary(entry.getKey(), keyType); + Object convertedValue = converter.convertIfNecessary(entry.getValue(), valueType); + result.put(convertedKey, convertedValue); + } + } + else { + result.putAll(this.sourceMap); + } + return result; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/MethodInvokingFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/MethodInvokingFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/MethodInvokingFactoryBean.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,205 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.lang.reflect.InvocationTargetException; + +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.FactoryBeanNotInitializedException; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.support.ArgumentConvertingMethodInvoker; +import org.springframework.util.ClassUtils; + +/** + * FactoryBean which returns a value which is the result of a static or instance + * method invocation. For most use cases it is better to just use the container's + * built-in factory method support for the same purpose, since that is smarter at + * converting arguments. This factory bean is still useful though when you need to + * call a method which doesn't return any value (for example, a static class method + * to force some sort of initialization to happen). This use case is not supported + * by factory methods, since a return value is needed to obtain the bean instance. + * + *

    Note that as it is expected to be used mostly for accessing factory methods, + * this factory by default operates in a singleton fashion. The first request + * to {@link #getObject} by the owning bean factory will cause a method invocation, + * whose return value will be cached for subsequent requests. An internal + * {@link #setSingleton singleton} property may be set to "false", to cause this + * factory to invoke the target method each time it is asked for an object. + * + *

    A static target method may be specified by setting the + * {@link #setTargetMethod targetMethod} property to a String representing the static + * method name, with {@link #setTargetClass targetClass} specifying the Class that + * the static method is defined on. Alternatively, a target instance method may be + * specified, by setting the {@link #setTargetObject targetObject} property as the target + * object, and the {@link #setTargetMethod targetMethod} property as the name of the + * method to call on that target object. Arguments for the method invocation may be + * specified by setting the {@link #setArguments arguments} property. + * + *

    This class depends on {@link #afterPropertiesSet()} being called once + * all properties have been set, as per the InitializingBean contract. + * + *

    An example (in an XML based bean factory definition) of a bean definition + * which uses this class to call a static factory method: + * + *

    + * <bean id="myObject" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    + *   <property name="staticMethod"><value>com.whatever.MyClassFactory.getInstance</value></property>
    + * </bean>
    + * + *

    An example of calling a static method then an instance method to get at a + * Java system property. Somewhat verbose, but it works. + * + *

    + * <bean id="sysProps" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    + *   <property name="targetClass"><value>java.lang.System</value></property>
    + *   <property name="targetMethod"><value>getProperties</value></property>
    + * </bean>
    + *
    + * <bean id="javaVersion" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    + *   <property name="targetObject"><ref local="sysProps"/></property>
    + *   <property name="targetMethod"><value>getProperty</value></property>
    + *   <property name="arguments">
    + *     <list>
    + *       <value>java.version</value>
    + *     </list>
    + *   </property>
    + * </bean>
    + * + * @author Colin Sampaleanu + * @author Juergen Hoeller + * @since 21.11.2003 + */ +public class MethodInvokingFactoryBean extends ArgumentConvertingMethodInvoker + implements FactoryBean, BeanClassLoaderAware, BeanFactoryAware, InitializingBean { + + private boolean singleton = true; + + private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); + + private ConfigurableBeanFactory beanFactory; + + private boolean initialized = false; + + /** Method call result in the singleton case */ + private Object singletonObject; + + + /** + * Set if a singleton should be created, or a new object on each + * request else. Default is "true". + */ + public void setSingleton(boolean singleton) { + this.singleton = singleton; + } + + public boolean isSingleton() { + return this.singleton; + } + + public void setBeanClassLoader(ClassLoader classLoader) { + this.beanClassLoader = classLoader; + } + + protected Class resolveClassName(String className) throws ClassNotFoundException { + return ClassUtils.forName(className, this.beanClassLoader); + } + + public void setBeanFactory(BeanFactory beanFactory) { + if (beanFactory instanceof ConfigurableBeanFactory) { + this.beanFactory = (ConfigurableBeanFactory) beanFactory; + } + } + + /** + * Obtain the TypeConverter from the BeanFactory that this bean runs in, + * if possible. + * @see ConfigurableBeanFactory#getTypeConverter() + */ + protected TypeConverter getDefaultTypeConverter() { + if (this.beanFactory != null) { + return this.beanFactory.getTypeConverter(); + } + else { + return super.getDefaultTypeConverter(); + } + } + + + public void afterPropertiesSet() throws Exception { + prepare(); + if (this.singleton) { + this.initialized = true; + this.singletonObject = doInvoke(); + } + } + + /** + * Perform the invocation and convert InvocationTargetException + * into the underlying target exception. + */ + private Object doInvoke() throws Exception { + try { + return invoke(); + } + catch (InvocationTargetException ex) { + if (ex.getTargetException() instanceof Exception) { + throw (Exception) ex.getTargetException(); + } + if (ex.getTargetException() instanceof Error) { + throw (Error) ex.getTargetException(); + } + throw ex; + } + } + + + /** + * Returns the same value each time if the singleton property is set + * to "true", otherwise returns the value returned from invoking the + * specified method on the fly. + */ + public Object getObject() throws Exception { + if (this.singleton) { + if (!this.initialized) { + throw new FactoryBeanNotInitializedException(); + } + // Singleton: return shared object. + return this.singletonObject; + } + else { + // Prototype: new object on each call. + return doInvoke(); + } + } + + /** + * Return the type of object that this FactoryBean creates, + * or null if not known in advance. + */ + public Class getObjectType() { + if (!isPrepared()) { + // Not fully initialized yet -> return null to indicate "not known yet". + return null; + } + return getPreparedMethod().getReturnType(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBean.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,141 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.ObjectFactory; +import org.springframework.util.Assert; + +/** + * A {@link org.springframework.beans.factory.FactoryBean} implementation that + * returns a value which is an {@link org.springframework.beans.factory.ObjectFactory} + * that in turn returns a bean sourced from a {@link org.springframework.beans.factory.BeanFactory}. + * + *

    As such, this may be used to avoid having a client object directly calling + * {@link org.springframework.beans.factory.BeanFactory#getBean(String)} to get + * a (typically prototype) bean from a + * {@link org.springframework.beans.factory.BeanFactory}, which would be a + * violation of the inversion of control principle. Instead, with the use + * of this class, the client object can be fed an + * {@link org.springframework.beans.factory.ObjectFactory} instance as a + * property which directly returns only the one target bean (again, which is + * typically a prototype bean). + * + *

    A sample config in an XML-based + * {@link org.springframework.beans.factory.BeanFactory} might look as follows: + * + *

    <beans>
    + *
    + *   <!-- Prototype bean since we have state -->
    + *   <bean id="myService" class="a.b.c.MyService" singleton="false"/>
    + *
    + *   <bean id="myServiceFactory"
    + *       class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean">
    + *     <property name="targetBeanName"><idref local="myService"/></property>
    + *   </bean>
    + *
    + *   <bean id="clientBean" class="a.b.c.MyClientBean">
    + *     <property name="myServiceFactory" ref="myServiceFactory"/>
    + *   </bean>
    + *
    + *</beans>
    + * + *

    The attendant MyClientBean class implementation might look + * something like this: + * + *

    package a.b.c;
    + *
    + * import org.springframework.beans.factory.ObjectFactory;
    + *
    + * public class MyClientBean {
    + *
    + *   private ObjectFactory myServiceFactory;
    + *
    + *   public void setMyServiceFactory(ObjectFactory myServiceFactory) {
    + *     this.myServiceFactory = myServiceFactory;
    + *   }
    + *
    + *   public void someBusinessMethod() {
    + *     // get a 'fresh', brand new MyService instance
    + *     MyService service = this.myServiceFactory.getObject();
    + *     // use the service object to effect the business logic...
    + *   }
    + * }
    + * + *

    An alternate approach to this application of an object creational pattern + * would be to use the {@link ServiceLocatorFactoryBean} + * to source (prototype) beans. The {@link ServiceLocatorFactoryBean} approach + * has the advantage of the fact that one doesn't have to depend on any + * Spring-specific interface such as {@link org.springframework.beans.factory.ObjectFactory}, + * but has the disadvantage of requiring runtime class generation. Please do + * consult the {@link ServiceLocatorFactoryBean ServiceLocatorFactoryBean JavaDoc} + * for a fuller discussion of this issue. + * + * @author Colin Sampaleanu + * @author Juergen Hoeller + * @since 1.0.2 + * @see org.springframework.beans.factory.ObjectFactory + * @see ServiceLocatorFactoryBean + */ +public class ObjectFactoryCreatingFactoryBean extends AbstractFactoryBean { + + private String targetBeanName; + + + /** + * Set the name of the target bean. + *

    The target does not have to be a prototype bean, but realisticially + * always will be (because if the target bean were a singleton, then said + * singleton bean could simply be injected straight into the dependent object, + * thus obviating the need for the extra level of indirection afforded by + * the approach encapsulated by this class). Please note that no exception + * will be thrown if the supplied targetBeanName does not + * reference a prototype bean. + */ + public void setTargetBeanName(String targetBeanName) { + this.targetBeanName = targetBeanName; + } + + public void afterPropertiesSet() throws Exception { + Assert.hasText(this.targetBeanName, "Property 'targetBeanName' is required"); + super.afterPropertiesSet(); + } + + + public Class getObjectType() { + return ObjectFactory.class; + } + + protected Object createInstance() { + return new ObjectFactory() { + public Object getObject() throws BeansException { + return getTargetBean(targetBeanName); + } + }; + } + + /** + * Template method for obtaining a target bean instance. + * Called by the exposed ObjectFactory's getObject() method. + * @param targetBeanName the name of the target bean + * @return the target bean instance + */ + protected Object getTargetBean(String targetBeanName) { + return getBeanFactory().getBean(targetBeanName); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/PreferencesPlaceholderConfigurer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/PreferencesPlaceholderConfigurer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/PreferencesPlaceholderConfigurer.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,134 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.util.Properties; +import java.util.prefs.BackingStoreException; +import java.util.prefs.Preferences; + +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.InitializingBean; + +/** + * Subclass of PropertyPlaceholderConfigurer that supports JDK 1.4's + * Preferences API (java.util.prefs). + * + *

    Tries to resolve placeholders as keys first in the user preferences, + * then in the system preferences, then in this configurer's properties. + * Thus, behaves like PropertyPlaceholderConfigurer if no corresponding + * preferences defined. + * + *

    Supports custom paths for the system and user preferences trees. Also + * supports custom paths specified in placeholders ("myPath/myPlaceholderKey"). + * Uses the respective root node if not specified. + * + * @author Juergen Hoeller + * @since 16.02.2004 + * @see #setSystemTreePath + * @see #setUserTreePath + * @see java.util.prefs.Preferences + */ +public class PreferencesPlaceholderConfigurer extends PropertyPlaceholderConfigurer implements InitializingBean { + + private String systemTreePath; + + private String userTreePath; + + private Preferences systemPrefs; + + private Preferences userPrefs; + + + /** + * Set the path in the system preferences tree to use for resolving + * placeholders. Default is the root node. + */ + public void setSystemTreePath(String systemTreePath) { + this.systemTreePath = systemTreePath; + } + + /** + * Set the path in the system preferences tree to use for resolving + * placeholders. Default is the root node. + */ + public void setUserTreePath(String userTreePath) { + this.userTreePath = userTreePath; + } + + + /** + * This implementation eagerly fetches the Preferences instances + * for the required system and user tree nodes. + */ + public void afterPropertiesSet() { + this.systemPrefs = (this.systemTreePath != null) ? + Preferences.systemRoot().node(this.systemTreePath) : Preferences.systemRoot(); + this.userPrefs = (this.userTreePath != null) ? + Preferences.userRoot().node(this.userTreePath) : Preferences.userRoot(); + } + + /** + * This implementation tries to resolve placeholders as keys first + * in the user preferences, then in the system preferences, then in + * the passed-in properties. + */ + protected String resolvePlaceholder(String placeholder, Properties props) { + String path = null; + String key = placeholder; + int endOfPath = placeholder.lastIndexOf('/'); + if (endOfPath != -1) { + path = placeholder.substring(0, endOfPath); + key = placeholder.substring(endOfPath + 1); + } + String value = resolvePlaceholder(path, key, this.userPrefs); + if (value == null) { + value = resolvePlaceholder(path, key, this.systemPrefs); + if (value == null) { + value = props.getProperty(placeholder); + } + } + return value; + } + + /** + * Resolve the given path and key against the given Preferences. + * @param path the preferences path (placeholder part before '/') + * @param key the preferences key (placeholder part after '/') + * @param preferences the Preferences to resolve against + * @return the value for the placeholder, or null if none found + */ + protected String resolvePlaceholder(String path, String key, Preferences preferences) { + if (path != null) { + // Do not create the node if it does not exist... + try { + if (preferences.nodeExists(path)) { + return preferences.node(path).get(key, null); + } + else { + return null; + } + } + catch (BackingStoreException ex) { + throw new BeanDefinitionStoreException("Cannot access specified node path [" + path + "]", ex); + } + } + else { + return preferences.get(key, null); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/PropertiesFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/PropertiesFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/PropertiesFactoryBean.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,101 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.io.IOException; +import java.util.Properties; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.core.io.support.PropertiesLoaderSupport; + +/** + * Allows for making a properties file from a classpath location available + * as Properties instance in a bean factory. Can be used to populate + * any bean property of type Properties via a bean reference. + * + *

    Supports loading from a properties file and/or setting local properties + * on this FactoryBean. The created Properties instance will be merged from + * loaded and local values. If neither a location nor local properties are set, + * an exception will be thrown on initialization. + * + *

    Can create a singleton or a new object on each request. + * Default is a singleton. + * + * @author Juergen Hoeller + * @see #setLocation + * @see #setProperties + * @see #setLocalOverride + * @see java.util.Properties + */ +public class PropertiesFactoryBean extends PropertiesLoaderSupport + implements FactoryBean, InitializingBean { + + private boolean singleton = true; + + private Object singletonInstance; + + + /** + * Set whether a shared 'singleton' Properties instance should be + * created, or rather a new Properties instance on each request. + *

    Default is "true" (a shared singleton). + */ + public final void setSingleton(boolean singleton) { + this.singleton = singleton; + } + + public final boolean isSingleton() { + return this.singleton; + } + + + public final void afterPropertiesSet() throws IOException { + if (this.singleton) { + this.singletonInstance = createInstance(); + } + } + + public final Object getObject() throws IOException { + if (this.singleton) { + return this.singletonInstance; + } + else { + return createInstance(); + } + } + + public Class getObjectType() { + return Properties.class; + } + + + /** + * Template method that subclasses may override to construct the object + * returned by this factory. The default implementation returns the + * plain merged Properties instance. + *

    Invoked on initialization of this FactoryBean in case of a + * shared singleton; else, on each {@link #getObject()} call. + * @return the object returned by this factory + * @throws IOException if an exception occured during properties loading + * @see #mergeProperties() + */ + protected Object createInstance() throws IOException { + return mergeProperties(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/PropertyOverrideConfigurer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/PropertyOverrideConfigurer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/PropertyOverrideConfigurer.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,161 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanInitializationException; + +/** + * Property resource configurer that overrides bean property values in an application + * context definition. It pushes values from a properties file into bean definitions. + * + *

    Configuration lines are expected to be of the following form: + * + *

    beanName.property=value
    + * + * Example properties file: + * + *
    dataSource.driverClassName=com.mysql.jdbc.Driver
    + * dataSource.url=jdbc:mysql:mydb
    + * + * In contrast to PropertyPlaceholderConfigurer, the original definition can have default + * values or no values at all for such bean properties. If an overriding properties file does + * not have an entry for a certain bean property, the default context definition is used. + * + *

    Note that the context definition is not aware of being overridden; + * so this is not immediately obvious when looking at the XML definition file. + * Furthermore, note that specified override values are always literal values; + * they are not translated into bean references. This also applies when the original + * value in the XML bean definition specifies a bean reference. + * + *

    In case of multiple PropertyOverrideConfigurers that define different values for + * the same bean property, the last one will win (due to the overriding mechanism). + * + *

    Property values can be converted after reading them in, through overriding + * the convertPropertyValue method. For example, encrypted values + * can be detected and decrypted accordingly before processing them. + * + * @author Juergen Hoeller + * @author Rod Johnson + * @since 12.03.2003 + * @see #convertPropertyValue + * @see PropertyPlaceholderConfigurer + */ +public class PropertyOverrideConfigurer extends PropertyResourceConfigurer { + + public static final String DEFAULT_BEAN_NAME_SEPARATOR = "."; + + + private String beanNameSeparator = DEFAULT_BEAN_NAME_SEPARATOR; + + private boolean ignoreInvalidKeys = false; + + /** Contains names of beans that have overrides */ + private Set beanNames = Collections.synchronizedSet(new HashSet()); + + + /** + * Set the separator to expect between bean name and property path. + * Default is a dot ("."). + */ + public void setBeanNameSeparator(String beanNameSeparator) { + this.beanNameSeparator = beanNameSeparator; + } + + /** + * Set whether to ignore invalid keys. Default is "false". + *

    If you ignore invalid keys, keys that do not follow the + * 'beanName.property' format will just be logged as warning. + * This allows to have arbitrary other keys in a properties file. + */ + public void setIgnoreInvalidKeys(boolean ignoreInvalidKeys) { + this.ignoreInvalidKeys = ignoreInvalidKeys; + } + + + protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) + throws BeansException { + + for (Enumeration names = props.propertyNames(); names.hasMoreElements();) { + String key = (String) names.nextElement(); + try { + processKey(beanFactory, key, props.getProperty(key)); + } + catch (BeansException ex) { + String msg = "Could not process key '" + key + "' in PropertyOverrideConfigurer"; + if (!this.ignoreInvalidKeys) { + throw new BeanInitializationException(msg, ex); + } + if (logger.isDebugEnabled()) { + logger.debug(msg, ex); + } + } + } + } + + /** + * Process the given key as 'beanName.property' entry. + */ + protected void processKey(ConfigurableListableBeanFactory factory, String key, String value) + throws BeansException { + + int separatorIndex = key.indexOf(this.beanNameSeparator); + if (separatorIndex == -1) { + throw new BeanInitializationException("Invalid key '" + key + + "': expected 'beanName" + this.beanNameSeparator + "property'"); + } + String beanName = key.substring(0, separatorIndex); + String beanProperty = key.substring(separatorIndex+1); + this.beanNames.add(beanName); + applyPropertyValue(factory, beanName, beanProperty, value); + if (logger.isDebugEnabled()) { + logger.debug("Property '" + key + "' set to value [" + value + "]"); + } + } + + /** + * Apply the given property value to the corresponding bean. + */ + protected void applyPropertyValue( + ConfigurableListableBeanFactory factory, String beanName, String property, String value) { + + BeanDefinition bd = factory.getBeanDefinition(beanName); + while (bd.getOriginatingBeanDefinition() != null) { + bd = bd.getOriginatingBeanDefinition(); + } + bd.getPropertyValues().addPropertyValue(property, value); + } + + + /** + * Were there overrides for this bean? + * Only valid after processing has occurred at least once. + * @param beanName name of the bean to query status for + * @return whether there were property overrides for + * the named bean + */ + public boolean hasPropertyOverridesFor(String beanName) { + return this.beanNames.contains(beanName); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/PropertyPathFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/PropertyPathFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/PropertyPathFactoryBean.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,224 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.BeanWrapper; +import org.springframework.beans.BeansException; +import org.springframework.beans.PropertyAccessorFactory; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.BeanNameAware; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.util.StringUtils; + +/** + * {@link FactoryBean} that evaluates a property path on a given target object. + * + *

    The target object can be specified directly or via a bean name. + * + *

    Usage examples: + * + *

    <!-- target bean to be referenced by name -->
    + * <bean id="tb" class="org.springframework.beans.TestBean" singleton="false">
    + *   <property name="age" value="10"/>
    + *   <property name="spouse">
    + *     <bean class="org.springframework.beans.TestBean">
    + *       <property name="age" value="11"/>
    + *     </bean>
    + *   </property>
    + * </bean>
    + *
    + * <!-- will result in 12, which is the value of property 'age' of the inner bean -->
    + * <bean id="propertyPath1" class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
    + *   <property name="targetObject">
    + *     <bean class="org.springframework.beans.TestBean">
    + *       <property name="age" value="12"/>
    + *     </bean>
    + *   </property>
    + *   <property name="propertyPath" value="age"/>
    + * </bean>
    + *
    + * <!-- will result in 11, which is the value of property 'spouse.age' of bean 'tb' -->
    + * <bean id="propertyPath2" class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
    + *   <property name="targetBeanName" value="tb"/>
    + *   <property name="propertyPath" value="spouse.age"/>
    + * </bean>
    + *
    + * <!-- will result in 10, which is the value of property 'age' of bean 'tb' -->
    + * <bean id="tb.age" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>
    + * + *

    If you are using Spring 2.0 and XML Schema support in your configuration file(s), + * you can also use the following style of configuration for property path access. + * (See also the appendix entitled 'XML Schema-based configuration' in the Spring + * reference manual for more examples.) + * + *

     <!-- will result in 10, which is the value of property 'age' of bean 'tb' -->
    + * <util:property-path id="name" path="testBean.age"/>
    + * + * Thanks to Matthias Ernst for the suggestion and initial prototype! + * + * @author Juergen Hoeller + * @since 1.1.2 + * @see #setTargetObject + * @see #setTargetBeanName + * @see #setPropertyPath + */ +public class PropertyPathFactoryBean implements FactoryBean, BeanNameAware, BeanFactoryAware { + + private static final Log logger = LogFactory.getLog(PropertyPathFactoryBean.class); + + private BeanWrapper targetBeanWrapper; + + private String targetBeanName; + + private String propertyPath; + + private Class resultType; + + private String beanName; + + private BeanFactory beanFactory; + + + /** + * Specify a target object to apply the property path to. + * Alternatively, specify a target bean name. + * @param targetObject a target object, for example a bean reference + * or an inner bean + * @see #setTargetBeanName + */ + public void setTargetObject(Object targetObject) { + this.targetBeanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(targetObject); + } + + /** + * Specify the name of a target bean to apply the property path to. + * Alternatively, specify a target object directly. + * @param targetBeanName the bean name to be looked up in the + * containing bean factory (e.g. "testBean") + * @see #setTargetObject + */ + public void setTargetBeanName(String targetBeanName) { + this.targetBeanName = StringUtils.trimAllWhitespace(targetBeanName); + } + + /** + * Specify the property path to apply to the target. + * @param propertyPath the property path, potentially nested + * (e.g. "age" or "spouse.age") + */ + public void setPropertyPath(String propertyPath) { + this.propertyPath = StringUtils.trimAllWhitespace(propertyPath); + } + + /** + * Specify the type of the result from evaluating the property path. + *

    Note: This is not necessary for directly specified target objects + * or singleton target beans, where the type can be determined through + * introspection. Just specify this in case of a prototype target, + * provided that you need matching by type (for example, for autowiring). + * @param resultType the result type, for example "java.lang.Integer" + */ + public void setResultType(Class resultType) { + this.resultType = resultType; + } + + /** + * The bean name of this PropertyPathFactoryBean will be interpreted + * as "beanName.property" pattern, if neither "targetObject" nor + * "targetBeanName" nor "propertyPath" have been specified. + * This allows for concise bean definitions with just an id/name. + */ + public void setBeanName(String beanName) { + this.beanName = StringUtils.trimAllWhitespace(BeanFactoryUtils.originalBeanName(beanName)); + } + + + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + + if (this.targetBeanWrapper != null && this.targetBeanName != null) { + throw new IllegalArgumentException("Specify either 'targetObject' or 'targetBeanName', not both"); + } + + if (this.targetBeanWrapper == null && this.targetBeanName == null) { + if (this.propertyPath != null) { + throw new IllegalArgumentException( + "Specify 'targetObject' or 'targetBeanName' in combination with 'propertyPath'"); + } + + // No other properties specified: check bean name. + int dotIndex = this.beanName.indexOf('.'); + if (dotIndex == -1) { + throw new IllegalArgumentException( + "Neither 'targetObject' nor 'targetBeanName' specified, and PropertyPathFactoryBean " + + "bean name '" + this.beanName + "' does not follow 'beanName.property' syntax"); + } + this.targetBeanName = this.beanName.substring(0, dotIndex); + this.propertyPath = this.beanName.substring(dotIndex + 1); + } + + else if (this.propertyPath == null) { + // either targetObject or targetBeanName specified + throw new IllegalArgumentException("'propertyPath' is required"); + } + + if (this.targetBeanWrapper == null && this.beanFactory.isSingleton(this.targetBeanName)) { + // Eagerly fetch singleton target bean, and determine result type. + Object bean = this.beanFactory.getBean(this.targetBeanName); + this.targetBeanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean); + this.resultType = this.targetBeanWrapper.getPropertyType(this.propertyPath); + } + } + + + public Object getObject() throws BeansException { + BeanWrapper target = this.targetBeanWrapper; + if (target != null) { + if (logger.isWarnEnabled() && this.beanFactory instanceof ConfigurableBeanFactory && + ((ConfigurableBeanFactory) this.beanFactory).isCurrentlyInCreation(this.targetBeanName)) { + logger.warn("Target bean '" + this.targetBeanName + "' is still in creation due to a circular " + + "reference - obtained value for property '" + this.propertyPath + "' may be outdated!"); + } + } + else { + // Fetch prototype target bean... + Object bean = this.beanFactory.getBean(this.targetBeanName); + target = PropertyAccessorFactory.forBeanPropertyAccess(bean); + } + return target.getPropertyValue(this.propertyPath); + } + + public Class getObjectType() { + return this.resultType; + } + + /** + * While this FactoryBean will often be used for singleton targets, + * the invoked getters for the property path might return a new object + * for each call, so we have to assume that we're not returning the + * same object for each {@link #getObject()} call. + */ + public boolean isSingleton() { + return false; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,450 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.BeanNameAware; +import org.springframework.core.Constants; +import org.springframework.util.StringUtils; +import org.springframework.util.StringValueResolver; + +/** + * A property resource configurer that resolves placeholders in bean property values of + * context definitions. It pulls values from a properties file into bean definitions. + * + *

    The default placeholder syntax follows the Ant / Log4J / JSP EL style: + * + *

    ${...}
    + * + * Example XML context definition: + * + *
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    + *   <property name="driverClassName"><value>${driver}</value></property>
    + *   <property name="url"><value>jdbc:${dbname}</value></property>
    + * </bean>
    + * + * Example properties file: + * + *
    driver=com.mysql.jdbc.Driver
    + * dbname=mysql:mydb
    + * + * PropertyPlaceholderConfigurer checks simple property values, lists, maps, + * props, and bean names in bean references. Furthermore, placeholder values can + * also cross-reference other placeholders, like: + * + *
    rootPath=myrootdir
    + * subPath=${rootPath}/subdir
    + * + * In contrast to PropertyOverrideConfigurer, this configurer allows to fill in + * explicit placeholders in context definitions. Therefore, the original definition + * cannot specify any default values for such bean properties, and the placeholder + * properties file is supposed to contain an entry for each defined placeholder. + * + *

    If a configurer cannot resolve a placeholder, a BeanDefinitionStoreException + * will be thrown. If you want to check against multiple properties files, specify + * multiple resources via the "locations" setting. You can also define multiple + * PropertyPlaceholderConfigurers, each with its own placeholder syntax. + * + *

    Default property values can be defined via "properties", to make overriding + * definitions in properties files optional. A configurer will also check against + * system properties (e.g. "user.dir") if it cannot resolve a placeholder with any + * of the specified properties. This can be customized via "systemPropertiesMode". + * + *

    Note that the context definition is aware of being incomplete; + * this is immediately obvious to users when looking at the XML definition file. + * Hence, placeholders have to be resolved; any desired defaults have to be + * defined as placeholder values as well (for example in a default properties file). + * + *

    Property values can be converted after reading them in, through overriding + * the {@link #convertPropertyValue} method. For example, encrypted values can + * be detected and decrypted accordingly before processing them. + * + * @author Juergen Hoeller + * @since 02.10.2003 + * @see #setLocations + * @see #setProperties + * @see #setPlaceholderPrefix + * @see #setPlaceholderSuffix + * @see #setSystemPropertiesModeName + * @see System#getProperty(String) + * @see #convertPropertyValue + * @see PropertyOverrideConfigurer + */ +public class PropertyPlaceholderConfigurer extends PropertyResourceConfigurer + implements BeanNameAware, BeanFactoryAware { + + /** Default placeholder prefix: "${" */ + public static final String DEFAULT_PLACEHOLDER_PREFIX = "${"; + + /** Default placeholder suffix: "}" */ + public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}"; + + + /** Never check system properties. */ + public static final int SYSTEM_PROPERTIES_MODE_NEVER = 0; + + /** + * Check system properties if not resolvable in the specified properties. + * This is the default. + */ + public static final int SYSTEM_PROPERTIES_MODE_FALLBACK = 1; + + /** + * Check system properties first, before trying the specified properties. + * This allows system properties to override any other property source. + */ + public static final int SYSTEM_PROPERTIES_MODE_OVERRIDE = 2; + + + private static final Constants constants = new Constants(PropertyPlaceholderConfigurer.class); + + private String placeholderPrefix = DEFAULT_PLACEHOLDER_PREFIX; + + private String placeholderSuffix = DEFAULT_PLACEHOLDER_SUFFIX; + + private int systemPropertiesMode = SYSTEM_PROPERTIES_MODE_FALLBACK; + + private boolean searchSystemEnvironment = true; + + private boolean ignoreUnresolvablePlaceholders = false; + + private String nullValue; + + private String beanName; + + private BeanFactory beanFactory; + + + /** + * Set the prefix that a placeholder string starts with. + * The default is "${". + * @see #DEFAULT_PLACEHOLDER_PREFIX + */ + public void setPlaceholderPrefix(String placeholderPrefix) { + this.placeholderPrefix = placeholderPrefix; + } + + /** + * Set the suffix that a placeholder string ends with. + * The default is "}". + * @see #DEFAULT_PLACEHOLDER_SUFFIX + */ + public void setPlaceholderSuffix(String placeholderSuffix) { + this.placeholderSuffix = placeholderSuffix; + } + + /** + * Set the system property mode by the name of the corresponding constant, + * e.g. "SYSTEM_PROPERTIES_MODE_OVERRIDE". + * @param constantName name of the constant + * @throws java.lang.IllegalArgumentException if an invalid constant was specified + * @see #setSystemPropertiesMode + */ + public void setSystemPropertiesModeName(String constantName) throws IllegalArgumentException { + this.systemPropertiesMode = constants.asNumber(constantName).intValue(); + } + + /** + * Set how to check system properties: as fallback, as override, or never. + * For example, will resolve ${user.dir} to the "user.dir" system property. + *

    The default is "fallback": If not being able to resolve a placeholder + * with the specified properties, a system property will be tried. + * "override" will check for a system property first, before trying the + * specified properties. "never" will not check system properties at all. + * @see #SYSTEM_PROPERTIES_MODE_NEVER + * @see #SYSTEM_PROPERTIES_MODE_FALLBACK + * @see #SYSTEM_PROPERTIES_MODE_OVERRIDE + * @see #setSystemPropertiesModeName + */ + public void setSystemPropertiesMode(int systemPropertiesMode) { + this.systemPropertiesMode = systemPropertiesMode; + } + + /** + * Set whether to search for a matching system environment variable + * if no matching system property has been found. Only applied when + * "systemPropertyMode" is active (i.e. "fallback" or "override"), right + * after checking JVM system properties. + *

    Default is "true". Switch this setting off to never resolve placeholders + * against system environment variables. Note that it is generally recommended + * to pass external values in as JVM system properties: This can easily be + * achieved in a startup script, even for existing environment variables. + *

    NOTE: Access to environment variables does not work on the + * Sun VM 1.4, where the corresponding {@link System#getenv} support was + * disabled - before it eventually got re-enabled for the Sun VM 1.5. + * Please upgrade to 1.5 (or higher) if you intend to rely on the + * environment variable support. + * @see #setSystemPropertiesMode + * @see java.lang.System#getProperty(String) + * @see java.lang.System#getenv(String) + */ + public void setSearchSystemEnvironment(boolean searchSystemEnvironment) { + this.searchSystemEnvironment = searchSystemEnvironment; + } + + /** + * Set whether to ignore unresolvable placeholders. Default is "false": + * An exception will be thrown if a placeholder cannot be resolved. + */ + public void setIgnoreUnresolvablePlaceholders(boolean ignoreUnresolvablePlaceholders) { + this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders; + } + + /** + * Set a value that should be treated as null when + * resolved as a placeholder value: e.g. "" (empty String) or "null". + *

    Note that this will only apply to full property values, + * not to parts of concatenated values. + *

    By default, no such null value is defined. This means that + * there is no way to express null as a property + * value unless you explictly map a corresponding value here. + */ + public void setNullValue(String nullValue) { + this.nullValue = nullValue; + } + + /** + * Only necessary to check that we're not parsing our own bean definition, + * to avoid failing on unresolvable placeholders in properties file locations. + * The latter case can happen with placeholders for system properties in + * resource locations. + * @see #setLocations + * @see org.springframework.core.io.ResourceEditor + */ + public void setBeanName(String beanName) { + this.beanName = beanName; + } + + /** + * Only necessary to check that we're not parsing our own bean definition, + * to avoid failing on unresolvable placeholders in properties file locations. + * The latter case can happen with placeholders for system properties in + * resource locations. + * @see #setLocations + * @see org.springframework.core.io.ResourceEditor + */ + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + + + protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) + throws BeansException { + + StringValueResolver valueResolver = new PlaceholderResolvingStringValueResolver(props); + BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver); + + String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames(); + for (int i = 0; i < beanNames.length; i++) { + // Check that we're not parsing our own bean definition, + // to avoid failing on unresolvable placeholders in properties file locations. + if (!(beanNames[i].equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) { + BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(beanNames[i]); + try { + visitor.visitBeanDefinition(bd); + } + catch (BeanDefinitionStoreException ex) { + throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanNames[i], ex.getMessage()); + } + } + } + + // New in Spring 2.5: resolve placeholders in alias target names and aliases as well. + beanFactoryToProcess.resolveAliases(valueResolver); + } + + /** + * Parse the given String value recursively, to be able to resolve + * nested placeholders (when resolved property values in turn contain + * placeholders again). + * @param strVal the String value to parse + * @param props the Properties to resolve placeholders against + * @param visitedPlaceholders the placeholders that have already been visited + * during the current resolution attempt (used to detect circular references + * between placeholders). Only non-null if we're parsing a nested placeholder. + * @throws BeanDefinitionStoreException if invalid values are encountered + * @see #resolvePlaceholder(String, java.util.Properties, int) + */ + protected String parseStringValue(String strVal, Properties props, Set visitedPlaceholders) + throws BeanDefinitionStoreException { + + StringBuffer buf = new StringBuffer(strVal); + + int startIndex = strVal.indexOf(this.placeholderPrefix); + while (startIndex != -1) { + int endIndex = findPlaceholderEndIndex(buf, startIndex); + if (endIndex != -1) { + String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex); + if (!visitedPlaceholders.add(placeholder)) { + throw new BeanDefinitionStoreException( + "Circular placeholder reference '" + placeholder + "' in property definitions"); + } + // Recursive invocation, parsing placeholders contained in the placeholder key. + placeholder = parseStringValue(placeholder, props, visitedPlaceholders); + // Now obtain the value for the fully resolved key... + String propVal = resolvePlaceholder(placeholder, props, this.systemPropertiesMode); + if (propVal != null) { + // Recursive invocation, parsing placeholders contained in the + // previously resolved placeholder value. + propVal = parseStringValue(propVal, props, visitedPlaceholders); + buf.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal); + if (logger.isTraceEnabled()) { + logger.trace("Resolved placeholder '" + placeholder + "'"); + } + startIndex = buf.indexOf(this.placeholderPrefix, startIndex + propVal.length()); + } + else if (this.ignoreUnresolvablePlaceholders) { + // Proceed with unprocessed value. + startIndex = buf.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length()); + } + else { + throw new BeanDefinitionStoreException("Could not resolve placeholder '" + placeholder + "'"); + } + visitedPlaceholders.remove(placeholder); + } + else { + startIndex = -1; + } + } + + return buf.toString(); + } + + private int findPlaceholderEndIndex(CharSequence buf, int startIndex) { + int index = startIndex + this.placeholderPrefix.length(); + int withinNestedPlaceholder = 0; + while (index < buf.length()) { + if (StringUtils.substringMatch(buf, index, this.placeholderSuffix)) { + if (withinNestedPlaceholder > 0) { + withinNestedPlaceholder--; + index = index + this.placeholderSuffix.length(); + } + else { + return index; + } + } + else if (StringUtils.substringMatch(buf, index, this.placeholderPrefix)) { + withinNestedPlaceholder++; + index = index + this.placeholderPrefix.length(); + } + else { + index++; + } + } + return -1; + } + + /** + * Resolve the given placeholder using the given properties, performing + * a system properties check according to the given mode. + *

    Default implementation delegates to resolvePlaceholder + * (placeholder, props) before/after the system properties check. + *

    Subclasses can override this for custom resolution strategies, + * including customized points for the system properties check. + * @param placeholder the placeholder to resolve + * @param props the merged properties of this configurer + * @param systemPropertiesMode the system properties mode, + * according to the constants in this class + * @return the resolved value, of null if none + * @see #setSystemPropertiesMode + * @see System#getProperty + * @see #resolvePlaceholder(String, java.util.Properties) + */ + protected String resolvePlaceholder(String placeholder, Properties props, int systemPropertiesMode) { + String propVal = null; + if (systemPropertiesMode == SYSTEM_PROPERTIES_MODE_OVERRIDE) { + propVal = resolveSystemProperty(placeholder); + } + if (propVal == null) { + propVal = resolvePlaceholder(placeholder, props); + } + if (propVal == null && systemPropertiesMode == SYSTEM_PROPERTIES_MODE_FALLBACK) { + propVal = resolveSystemProperty(placeholder); + } + return propVal; + } + + /** + * Resolve the given placeholder using the given properties. + * The default implementation simply checks for a corresponding property key. + *

    Subclasses can override this for customized placeholder-to-key mappings + * or custom resolution strategies, possibly just using the given properties + * as fallback. + *

    Note that system properties will still be checked before respectively + * after this method is invoked, according to the system properties mode. + * @param placeholder the placeholder to resolve + * @param props the merged properties of this configurer + * @return the resolved value, of null if none + * @see #setSystemPropertiesMode + */ + protected String resolvePlaceholder(String placeholder, Properties props) { + return props.getProperty(placeholder); + } + + /** + * Resolve the given key as JVM system property, and optionally also as + * system environment variable if no matching system property has been found. + * @param key the placeholder to resolve as system property key + * @return the system property value, or null if not found + * @see #setSearchSystemEnvironment + * @see java.lang.System#getProperty(String) + * @see java.lang.System#getenv(String) + */ + protected String resolveSystemProperty(String key) { + try { + String value = System.getProperty(key); + if (value == null && this.searchSystemEnvironment) { + value = System.getenv(key); + } + return value; + } + catch (Throwable ex) { + if (logger.isDebugEnabled()) { + logger.debug("Could not access system property '" + key + "': " + ex); + } + return null; + } + } + + + /** + * BeanDefinitionVisitor that resolves placeholders in String values, + * delegating to the parseStringValue method of the + * containing class. + */ + private class PlaceholderResolvingStringValueResolver implements StringValueResolver { + + private final Properties props; + + public PlaceholderResolvingStringValueResolver(Properties props) { + this.props = props; + } + + public String resolveStringValue(String strVal) throws BeansException { + String value = parseStringValue(strVal, this.props, new HashSet()); + return (value.equals(nullValue) ? null : value); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/PropertyResourceConfigurer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/PropertyResourceConfigurer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/PropertyResourceConfigurer.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,128 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.io.IOException; +import java.util.Enumeration; +import java.util.Properties; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanInitializationException; +import org.springframework.core.Ordered; +import org.springframework.core.PriorityOrdered; +import org.springframework.core.io.support.PropertiesLoaderSupport; +import org.springframework.util.ObjectUtils; + +/** + * Allows for configuration of individual bean property values from a property resource, + * i.e. a properties file. Useful for custom config files targetted at system + * administrators that override bean properties configured in the application context. + * + *

    Two concrete implementations are provided in the distribution: + *

      + *
    • {@link PropertyOverrideConfigurer} for "beanName.property=value" style overriding + * (pushing values from a properties file into bean definitions) + *
    • {@link PropertyPlaceholderConfigurer} for replacing "${...}" placeholders + * (pulling values from a properties file into bean definitions) + *
    + * + *

    Property values can be converted after reading them in, through overriding + * the {@link #convertPropertyValue} method. For example, encrypted values + * can be detected and decrypted accordingly before processing them. + * + * @author Juergen Hoeller + * @since 02.10.2003 + * @see PropertyOverrideConfigurer + * @see PropertyPlaceholderConfigurer + */ +public abstract class PropertyResourceConfigurer extends PropertiesLoaderSupport + implements BeanFactoryPostProcessor, PriorityOrdered { + + private int order = Ordered.LOWEST_PRECEDENCE; // default: same as non-Ordered + + + public void setOrder(int order) { + this.order = order; + } + + public int getOrder() { + return this.order; + } + + + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + try { + Properties mergedProps = mergeProperties(); + + // Convert the merged properties, if necessary. + convertProperties(mergedProps); + + // Let the subclass process the properties. + processProperties(beanFactory, mergedProps); + } + catch (IOException ex) { + throw new BeanInitializationException("Could not load properties", ex); + } + } + + /** + * Convert the given merged properties, converting property values + * if necessary. The result will then be processed. + *

    The default implementation will invoke {@link #convertPropertyValue} + * for each property value, replacing the original with the converted value. + * @param props the Properties to convert + * @see #processProperties + */ + protected void convertProperties(Properties props) { + Enumeration propertyNames = props.propertyNames(); + while (propertyNames.hasMoreElements()) { + String propertyName = (String) propertyNames.nextElement(); + String propertyValue = props.getProperty(propertyName); + String convertedValue = convertPropertyValue(propertyValue); + if (!ObjectUtils.nullSafeEquals(propertyValue, convertedValue)) { + props.setProperty(propertyName, convertedValue); + } + } + } + + /** + * Convert the given property value from the properties source + * to the value that should be applied. + *

    The default implementation simply returns the original value. + * Can be overridden in subclasses, for example to detect + * encrypted values and decrypt them accordingly. + * @param originalValue the original value from the properties source + * (properties file or local "properties") + * @return the converted value, to be used for processing + * @see #setProperties + * @see #setLocations + * @see #setLocation + */ + protected String convertPropertyValue(String originalValue) { + return originalValue; + } + + /** + * Apply the given Properties to the given BeanFactory. + * @param beanFactory the BeanFactory used by the application context + * @param props the Properties to apply + * @throws org.springframework.beans.BeansException in case of errors + */ + protected abstract void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) + throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/RuntimeBeanNameReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/RuntimeBeanNameReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/RuntimeBeanNameReference.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.util.Assert; + +/** + * Immutable placeholder class used for a property value object when it's a + * reference to another bean name in the factory, to be resolved at runtime. + * + * @author Juergen Hoeller + * @since 2.0 + * @see RuntimeBeanReference + * @see BeanDefinition#getPropertyValues() + * @see org.springframework.beans.factory.BeanFactory#getBean + */ +public class RuntimeBeanNameReference implements BeanReference { + + private final String beanName; + + private Object source; + + + /** + * Create a new RuntimeBeanNameReference to the given bean name. + * @param beanName name of the target bean + */ + public RuntimeBeanNameReference(String beanName) { + Assert.hasText(beanName, "'beanName' must not be empty"); + this.beanName = beanName; + } + + public String getBeanName() { + return this.beanName; + } + + /** + * Set the configuration source Object for this metadata element. + *

    The exact type of the object will depend on the configuration mechanism used. + */ + public void setSource(Object source) { + this.source = source; + } + + public Object getSource() { + return this.source; + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof RuntimeBeanNameReference)) { + return false; + } + RuntimeBeanNameReference that = (RuntimeBeanNameReference) other; + return this.beanName.equals(that.beanName); + } + + public int hashCode() { + return this.beanName.hashCode(); + } + + public String toString() { + return '<' + getBeanName() + '>'; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/RuntimeBeanReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/RuntimeBeanReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/RuntimeBeanReference.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,110 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.util.Assert; + +/** + * Immutable placeholder class used for a property value object when it's + * a reference to another bean in the factory, to be resolved at runtime. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see BeanDefinition#getPropertyValues() + * @see org.springframework.beans.factory.BeanFactory#getBean + */ +public class RuntimeBeanReference implements BeanReference { + + private final String beanName; + + private final boolean toParent; + + private Object source; + + + /** + * Create a new RuntimeBeanReference to the given bean name, + * without explicitly marking it as reference to a bean in + * the parent factory. + * @param beanName name of the target bean + */ + public RuntimeBeanReference(String beanName) { + this(beanName, false); + } + + /** + * Create a new RuntimeBeanReference to the given bean name, + * with the option to mark it as reference to a bean in + * the parent factory. + * @param beanName name of the target bean + * @param toParent whether this is an explicit reference to + * a bean in the parent factory + */ + public RuntimeBeanReference(String beanName, boolean toParent) { + Assert.hasText(beanName, "'beanName' must not be empty"); + this.beanName = beanName; + this.toParent = toParent; + } + + + public String getBeanName() { + return this.beanName; + } + + /** + * Return whether this is an explicit reference to a bean + * in the parent factory. + */ + public boolean isToParent() { + return this.toParent; + } + + /** + * Set the configuration source Object for this metadata element. + *

    The exact type of the object will depend on the configuration mechanism used. + */ + public void setSource(Object source) { + this.source = source; + } + + public Object getSource() { + return this.source; + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof RuntimeBeanReference)) { + return false; + } + RuntimeBeanReference that = (RuntimeBeanReference) other; + return (this.beanName.equals(that.beanName) && this.toParent == that.toParent); + } + + public int hashCode() { + int result = this.beanName.hashCode(); + result = 29 * result + (this.toParent ? 1 : 0); + return result; + } + + public String toString() { + return '<' + getBeanName() + '>'; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/Scope.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/Scope.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/Scope.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,137 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.beans.factory.ObjectFactory; + +/** + * Strategy interface used by a {@link ConfigurableBeanFactory}, + * representing a target scope to hold bean instances in. + * This allows for extending the BeanFactory's standard scopes + * {@link ConfigurableBeanFactory#SCOPE_SINGLETON "singleton"} and + * {@link ConfigurableBeanFactory#SCOPE_PROTOTYPE "prototype"} + * with custom further scopes, registered for a + * {@link ConfigurableBeanFactory#registerScope(String, Scope) specific key}. + * + *

    {@link org.springframework.context.ApplicationContext} implementations + * such as a {@link org.springframework.web.context.WebApplicationContext} + * may register additional standard scopes specific to their environment, + * e.g. {@link org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST "request"} + * and {@link org.springframework.web.context.WebApplicationContext#SCOPE_SESSION "session"}, + * based on this Scope SPI. + * + *

    Even if its primary use is for extended scopes in a web environment, + * this SPI is completely generic: It provides the ability to get and put + * objects from any underlying storage mechanism, such as an HTTP session + * or a custom conversation mechanism. The name passed into this class's + * get and remove methods will identify the + * target object in the current scope. + * + *

    Scope implementations are expected to be thread-safe. + * One Scope instance can be used with multiple bean factories + * at the same time, if desired (unless it explicitly wants to be aware of + * the containing BeanFactory), with any number of threads accessing + * the Scope concurrently from any number of factories. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @since 2.0 + * @see ConfigurableBeanFactory#registerScope + * @see CustomScopeConfigurer + * @see org.springframework.aop.scope.ScopedProxyFactoryBean + * @see org.springframework.web.context.request.RequestScope + * @see org.springframework.web.context.request.SessionScope + */ +public interface Scope { + + /** + * Return the object with the given name from the underlying scope, + * {@link org.springframework.beans.factory.ObjectFactory#getObject() creating it} + * if not found in the underlying storage mechanism. + *

    This is the central operation of a Scope, and the only operation + * that is absolutely required. + * @param name the name of the object to retrieve + * @param objectFactory the {@link ObjectFactory} to use to create the scoped + * object if it is not present in the underlying storage mechanism + * @return the desired object (never null) + */ + Object get(String name, ObjectFactory objectFactory); + + /** + * Remove the object with the given name from the underlying scope. + *

    Returns null if no object was found; otherwise + * returns the removed Object. + *

    Note that an implementation should also remove a registered destruction + * callback for the specified object, if any. It does, however, not + * need to execute a registered destruction callback in this case, + * since the object will be destroyed by the caller (if appropriate). + *

    Note: This is an optional operation. Implementations may throw + * {@link UnsupportedOperationException} if they do not support explicitly + * removing an object. + * @param name the name of the object to remove + * @return the removed object, or null if no object was present + * @see #registerDestructionCallback + */ + Object remove(String name); + + /** + * Register a callback to be executed on destruction of the specified + * object in the scope (or at destruction of the entire scope, if the + * scope does not destroy individual objects but rather only terminates + * in its entirety). + *

    Note: This is an optional operation. This method will only + * be called for scoped beans with actual destruction configuration + * (DisposableBean, destroy-method, DestructionAwareBeanPostProcessor). + * Implementations should do their best to execute a given callback + * at the appropriate time. If such a callback is not supported by the + * underlying runtime environment at all, the callback must be + * ignored and a corresponding warning should be logged. + *

    Note that 'destruction' refers to to automatic destruction of + * the object as part of the scope's own lifecycle, not to the individual + * scoped object having been explicitly removed by the application. + * If a scoped object gets removed via this facade's {@link #remove(String)} + * method, any registered destruction callback should be removed as well, + * assuming that the removed object will be reused or manually destroyed. + * @param name the name of the object to execute the destruction callback for + * @param callback the destruction callback to be executed. + * Note that the passed-in Runnable will never throw an exception, + * so it can safely be executed without an enclosing try-catch block. + * Furthermore, the Runnable will usually be serializable, provided + * that its target object is serializable as well. + * @see org.springframework.beans.factory.DisposableBean + * @see org.springframework.beans.factory.support.AbstractBeanDefinition#getDestroyMethodName() + * @see DestructionAwareBeanPostProcessor + */ + void registerDestructionCallback(String name, Runnable callback); + + /** + * Return the conversation ID for the current underlying scope, if any. + *

    The exact meaning of the conversation ID depends on the underlying + * storage mechanism. In the case of session-scoped objects, the + * conversation ID would typically be equal to (or derived from) the + * {@link javax.servlet.http.HttpSession#getId() session ID}; in the + * case of a custom conversation that sits within the overall session, + * the specific ID for the current conversation would be appropriate. + *

    Note: This is an optional operation. It is perfectly valid to + * return null in an implementation of this method if the + * underlying storage mechanism has no obvious candidate for such an ID. + * @return the conversation ID, or null if there is no + * conversation ID for the current scope + */ + String getConversationId(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,416 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Properties; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.FatalBeanException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; + +/** + * A {@link org.springframework.beans.factory.FactoryBean} implementation that + * takes an interface which must have one or more methods with + * the signatures MyType xxx() or MyType xxx(MyIdType id) + * (typically, MyService getService() or MyService getService(String id)) + * and creates a dynamic proxy which implements that interface, delegating to an + * underlying {@link org.springframework.beans.factory.BeanFactory}. + * + *

    Such service locators permit the decoupling of calling code from + * the {@link org.springframework.beans.factory.BeanFactory} API, by using an + * appropriate custom locator interface. They will typically be used for + * prototype beans, i.e. for factory methods that are supposed to + * return a new instance for each call. The client receives a reference to the + * service locator via setter or constructor injection, to be able to invoke + * the locator's factory methods on demand. For singleton beans, direct + * setter or constructor injection of the target bean is preferable. + * + *

    On invocation of the no-arg factory method, or the single-arg factory + * method with a String id of null or empty String, if exactly + * one bean in the factory matches the return type of the factory + * method, that bean is returned, otherwise a + * {@link org.springframework.beans.factory.NoSuchBeanDefinitionException} + * is thrown. + * + *

    On invocation of the single-arg factory method with a non-null (and + * non-empty) argument, the proxy returns the result of a + * {@link org.springframework.beans.factory.BeanFactory#getBean(String)} call, + * using a stringified version of the passed-in id as bean name. + * + *

    A factory method argument will usually be a String, but can also be an + * int or a custom enumeration type, for example, stringified via + * toString. The resulting String can be used as bean name as-is, + * provided that corresponding beans are defined in the bean factory. + * Alternatively, {@link #setServiceMappings(java.util.Properties) a custom mapping} + * between service ids and bean names can be defined. + * + *

    By way of an example, consider the following service locator interface. + * Note that this interface is not dependant on any Spring APIs. + * + *

    package a.b.c;
    + *
    + *public interface ServiceFactory {
    + *
    + *    public MyService getService ();
    + *}
    + * + *

    A sample config in an XML-based + * {@link org.springframework.beans.factory.BeanFactory} might look as follows: + * + *

    <beans>
    + *
    + *   <!-- Prototype bean since we have state -->
    + *   <bean id="myService" class="a.b.c.MyService" singleton="false"/>
    + *
    + *   <!-- will lookup the above 'myService' bean by *TYPE* -->
    + *   <bean id="myServiceFactory"
    + *            class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean">
    + *     <property name="serviceLocatorInterface" value="a.b.c.ServiceFactory"/>
    + *   </bean>
    + *
    + *   <bean id="clientBean" class="a.b.c.MyClientBean">
    + *     <property name="myServiceFactory" ref="myServiceFactory"/>
    + *   </bean>
    + *
    + *</beans>
    + * + *

    The attendant MyClientBean class implementation might then + * look something like this: + * + *

    package a.b.c;
    + *
    + *public class MyClientBean {
    + *
    + *    private ServiceFactory myServiceFactory;
    + *
    + *    // actual implementation provided by the Spring container
    + *    public void setServiceFactory(ServiceFactory myServiceFactory) {
    + *        this.myServiceFactory = myServiceFactory;
    + *    }
    + *
    + *    public void someBusinessMethod() {
    + *        // get a 'fresh', brand new MyService instance
    + *        MyService service = this.myServiceFactory.getService();
    + *        // use the service object to effect the business logic...
    + *    }
    + *}
    + * + *

    By way of an example that looks up a bean by name, consider + * the following service locator interface. Again, note that this + * interface is not dependant on any Spring APIs. + * + *

    package a.b.c;
    + *
    + *public interface ServiceFactory {
    + *
    + *    public MyService getService (String serviceName);
    + *}
    + * + *

    A sample config in an XML-based + * {@link org.springframework.beans.factory.BeanFactory} might look as follows: + * + *

    <beans>
    + *
    + *   <!-- Prototype beans since we have state (both extend MyService) -->
    + *   <bean id="specialService" class="a.b.c.SpecialService" singleton="false"/>
    + *   <bean id="anotherService" class="a.b.c.AnotherService" singleton="false"/>
    + *
    + *   <bean id="myServiceFactory"
    + *            class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean">
    + *     <property name="serviceLocatorInterface" value="a.b.c.ServiceFactory"/>
    + *   </bean>
    + *
    + *   <bean id="clientBean" class="a.b.c.MyClientBean">
    + *     <property name="myServiceFactory" ref="myServiceFactory"/>
    + *   </bean>
    + *
    + *</beans>
    + * + *

    The attendant MyClientBean class implementation might then + * look something like this: + * + *

    package a.b.c;
    + *
    + *public class MyClientBean {
    + *
    + *    private ServiceFactory myServiceFactory;
    + *
    + *    // actual implementation provided by the Spring container
    + *    public void setServiceFactory(ServiceFactory myServiceFactory) {
    + *        this.myServiceFactory = myServiceFactory;
    + *    }
    + *
    + *    public void someBusinessMethod() {
    + *        // get a 'fresh', brand new MyService instance
    + *        MyService service = this.myServiceFactory.getService("specialService");
    + *        // use the service object to effect the business logic...
    + *    }
    + *
    + *    public void anotherBusinessMethod() {
    + *        // get a 'fresh', brand new MyService instance
    + *        MyService service = this.myServiceFactory.getService("anotherService");
    + *        // use the service object to effect the business logic...
    + *    }
    + *}
    + * + *

    See {@link ObjectFactoryCreatingFactoryBean} for an alternate approach. + * + * @author Colin Sampaleanu + * @author Juergen Hoeller + * @since 1.1.4 + * @see #setServiceLocatorInterface + * @see #setServiceMappings + * @see ObjectFactoryCreatingFactoryBean + */ +public class ServiceLocatorFactoryBean implements FactoryBean, BeanFactoryAware, InitializingBean { + + private Class serviceLocatorInterface; + + private Constructor serviceLocatorExceptionConstructor; + + private Properties serviceMappings; + + private ListableBeanFactory beanFactory; + + private Object proxy; + + + /** + * Set the service locator interface to use, which must have one or more methods with + * the signatures MyType xxx() or MyType xxx(MyIdType id) + * (typically, MyService getService() or MyService getService(String id)). + * See the {@link ServiceLocatorFactoryBean class-level Javadoc} for + * information on the semantics of such methods. + */ + public void setServiceLocatorInterface(Class interfaceType) { + this.serviceLocatorInterface = interfaceType; + } + + /** + * Set the exception class that the service locator should throw if service + * lookup failed. The specified exception class must have a constructor + * with one of the following parameter types: (String, Throwable) + * or (Throwable) or (String). + *

    If not specified, subclasses of Spring's BeansException will be thrown, + * for example NoSuchBeanDefinitionException. As those are unchecked, the + * caller does not need to handle them, so it might be acceptable that + * Spring exceptions get thrown as long as they are just handled generically. + * @see #determineServiceLocatorExceptionConstructor + * @see #createServiceLocatorException + */ + public void setServiceLocatorExceptionClass(Class serviceLocatorExceptionClass) { + if (serviceLocatorExceptionClass != null && !Exception.class.isAssignableFrom(serviceLocatorExceptionClass)) { + throw new IllegalArgumentException( + "serviceLocatorException [" + serviceLocatorExceptionClass.getName() + "] is not a subclass of Exception"); + } + this.serviceLocatorExceptionConstructor = + determineServiceLocatorExceptionConstructor(serviceLocatorExceptionClass); + } + + /** + * Set mappings between service ids (passed into the service locator) + * and bean names (in the bean factory). Service ids that are not defined + * here will be treated as bean names as-is. + *

    The empty string as service id key defines the mapping for null and + * empty string, and for factory methods without parameter. If not defined, + * a single matching bean will be retrieved from the bean factory. + * @param serviceMappings mappings between service ids and bean names, + * with service ids as keys as bean names as values + */ + public void setServiceMappings(Properties serviceMappings) { + this.serviceMappings = serviceMappings; + } + + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + if (!(beanFactory instanceof ListableBeanFactory)) { + throw new FatalBeanException( + "ServiceLocatorFactoryBean needs to run in a BeanFactory that is a ListableBeanFactory"); + } + this.beanFactory = (ListableBeanFactory) beanFactory; + } + + public void afterPropertiesSet() { + if (this.serviceLocatorInterface == null) { + throw new IllegalArgumentException("Property 'serviceLocatorInterface' is required"); + } + + // Create service locator proxy. + this.proxy = Proxy.newProxyInstance( + this.serviceLocatorInterface.getClassLoader(), + new Class[] {this.serviceLocatorInterface}, + new ServiceLocatorInvocationHandler()); + } + + + /** + * Determine the constructor to use for the given service locator exception + * class. Only called in case of a custom service locator exception. + *

    The default implementation looks for a constructor with one of the + * following parameter types: (String, Throwable) + * or (Throwable) or (String). + * @param exceptionClass the exception class + * @return the constructor to use + * @see #setServiceLocatorExceptionClass + */ + protected Constructor determineServiceLocatorExceptionConstructor(Class exceptionClass) { + try { + return exceptionClass.getConstructor(new Class[] {String.class, Throwable.class}); + } + catch (NoSuchMethodException ex) { + try { + return exceptionClass.getConstructor(new Class[] {Throwable.class}); + } + catch (NoSuchMethodException ex2) { + try { + return exceptionClass.getConstructor(new Class[] {String.class}); + } + catch (NoSuchMethodException ex3) { + throw new IllegalArgumentException( + "Service locator exception [" + exceptionClass.getName() + + "] neither has a (String, Throwable) constructor nor a (String) constructor"); + } + } + } + } + + /** + * Create a service locator exception for the given cause. + * Only called in case of a custom service locator exception. + *

    The default implementation can handle all variations of + * message and exception arguments. + * @param exceptionConstructor the constructor to use + * @param cause the cause of the service lookup failure + * @return the service locator exception to throw + * @see #setServiceLocatorExceptionClass + */ + protected Exception createServiceLocatorException(Constructor exceptionConstructor, BeansException cause) { + Class[] paramTypes = exceptionConstructor.getParameterTypes(); + Object[] args = new Object[paramTypes.length]; + for (int i = 0; i < paramTypes.length; i++) { + if (paramTypes[i].equals(String.class)) { + args[i] = cause.getMessage(); + } + else if (paramTypes[i].isInstance(cause)) { + args[i] = cause; + } + } + return (Exception) BeanUtils.instantiateClass(exceptionConstructor, args); + } + + + public Object getObject() { + return this.proxy; + } + + public Class getObjectType() { + return this.serviceLocatorInterface; + } + + public boolean isSingleton() { + return true; + } + + + /** + * Invocation handler that delegates service locator calls to the bean factory. + */ + private class ServiceLocatorInvocationHandler implements InvocationHandler { + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (ReflectionUtils.isEqualsMethod(method)) { + // Only consider equal when proxies are identical. + return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE); + } + else if (ReflectionUtils.isHashCodeMethod(method)) { + // Use hashCode of service locator proxy. + return new Integer(System.identityHashCode(proxy)); + } + else if (ReflectionUtils.isToStringMethod(method)) { + return "Service locator: " + serviceLocatorInterface.getName(); + } + else { + return invokeServiceLocatorMethod(method, args); + } + } + + private Object invokeServiceLocatorMethod(Method method, Object[] args) throws Exception { + Class serviceLocatorMethodReturnType = getServiceLocatorMethodReturnType(method); + try { + String beanName = tryGetBeanName(args); + if (StringUtils.hasLength(beanName)) { + // Service locator for a specific bean name. + return beanFactory.getBean(beanName, serviceLocatorMethodReturnType); + } + else { + // Service locator for a bean type. + return BeanFactoryUtils.beanOfTypeIncludingAncestors(beanFactory, serviceLocatorMethodReturnType); + } + } + catch (BeansException ex) { + if (serviceLocatorExceptionConstructor != null) { + throw createServiceLocatorException(serviceLocatorExceptionConstructor, ex); + } + throw ex; + } + } + + /** + * Check whether a service id was passed in. + */ + private String tryGetBeanName(Object[] args) { + String beanName = ""; + if (args != null && args.length == 1 && args[0] != null) { + beanName = args[0].toString(); + } + // Look for explicit serviceId-to-beanName mappings. + if (serviceMappings != null) { + String mappedName = serviceMappings.getProperty(beanName); + if (mappedName != null) { + beanName = mappedName; + } + } + return beanName; + } + + private Class getServiceLocatorMethodReturnType(Method method) throws NoSuchMethodException { + Class[] paramTypes = method.getParameterTypes(); + Method interfaceMethod = serviceLocatorInterface.getMethod(method.getName(), paramTypes); + Class serviceLocatorReturnType = interfaceMethod.getReturnType(); + + // Check whether the method is a valid service locator. + if (paramTypes.length > 1 || void.class.equals(serviceLocatorReturnType)) { + throw new UnsupportedOperationException( + "May only call methods with signature ' xxx()' or ' xxx( id)' " + + "on factory interface, but tried to call: " + interfaceMethod); + } + return serviceLocatorReturnType; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/SetFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/SetFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/SetFactoryBean.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,99 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Set; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.TypeConverter; +import org.springframework.core.GenericCollectionTypeResolver; +import org.springframework.core.JdkVersion; + +/** + * Simple factory for shared Set instances. Allows for central setup + * of Sets via the "set" element in XML bean definitions. + * + * @author Juergen Hoeller + * @since 09.12.2003 + * @see ListFactoryBean + * @see MapFactoryBean + */ +public class SetFactoryBean extends AbstractFactoryBean { + + private Set sourceSet; + + private Class targetSetClass; + + + /** + * Set the source Set, typically populated via XML "set" elements. + */ + public void setSourceSet(Set sourceSet) { + this.sourceSet = sourceSet; + } + + /** + * Set the class to use for the target Set. Can be populated with a fully + * qualified class name when defined in a Spring application context. + *

    Default is a linked HashSet, keeping the registration order. + * @see java.util.LinkedHashSet + */ + public void setTargetSetClass(Class targetSetClass) { + if (targetSetClass == null) { + throw new IllegalArgumentException("'targetSetClass' must not be null"); + } + if (!Set.class.isAssignableFrom(targetSetClass)) { + throw new IllegalArgumentException("'targetSetClass' must implement [java.util.Set]"); + } + this.targetSetClass = targetSetClass; + } + + + public Class getObjectType() { + return Set.class; + } + + protected Object createInstance() { + if (this.sourceSet == null) { + throw new IllegalArgumentException("'sourceSet' is required"); + } + Set result = null; + if (this.targetSetClass != null) { + result = (Set) BeanUtils.instantiateClass(this.targetSetClass); + } + else { + result = new LinkedHashSet(this.sourceSet.size()); + } + Class valueType = null; + if (this.targetSetClass != null && JdkVersion.isAtLeastJava15()) { + valueType = GenericCollectionTypeResolver.getCollectionType(this.targetSetClass); + } + if (valueType != null) { + TypeConverter converter = getBeanTypeConverter(); + for (Iterator it = this.sourceSet.iterator(); it.hasNext();) { + result.add(converter.convertIfNecessary(it.next(), valueType)); + } + } + else { + result.addAll(this.sourceSet); + } + return result; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/SingletonBeanRegistry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/SingletonBeanRegistry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/SingletonBeanRegistry.java 17 Aug 2012 15:11:36 -0000 1.1 @@ -0,0 +1,121 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +/** + * Interface that defines a registry for shared bean instances. + * Can be implemented by {@link org.springframework.beans.factory.BeanFactory} + * implementations in order to expose their singleton management facility + * in a uniform manner. + * + *

    The {@link ConfigurableBeanFactory} interface extends this interface. + * + * @author Juergen Hoeller + * @since 2.0 + * @see ConfigurableBeanFactory + * @see org.springframework.beans.factory.support.DefaultSingletonBeanRegistry + * @see org.springframework.beans.factory.support.AbstractBeanFactory + */ +public interface SingletonBeanRegistry { + + /** + * Register the given existing object as singleton in the bean registry, + * under the given bean name. + *

    The given instance is supposed to be fully initialized; the registry + * will not perform any initialization callbacks (in particular, it won't + * call InitializingBean's afterPropertiesSet method). + * The given instance will not receive any destruction callbacks + * (like DisposableBean's destroy method) either. + *

    If running within a full BeanFactory: Register a bean definition + * instead of an existing instance if your bean is supposed to receive + * initialization and/or destruction callbacks. + *

    Typically invoked during registry configuration, but can also be used + * for runtime registration of singletons. As a consequence, a registry + * implementation should synchronize singleton access; it will have to do + * this anyway if it supports a BeanFactory's lazy initialization of singletons. + * @param beanName the name of the bean + * @param singletonObject the existing singleton object + * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet + * @see org.springframework.beans.factory.DisposableBean#destroy + * @see org.springframework.beans.factory.support.BeanDefinitionRegistry#registerBeanDefinition + */ + void registerSingleton(String beanName, Object singletonObject); + + /** + * Return the (raw) singleton object registered under the given name. + *

    Only checks already instantiated singletons; does not return an Object + * for singleton bean definitions which have not been instantiated yet. + *

    The main purpose of this method is to access manually registered singletons + * (see {@link #registerSingleton}). Can also be used to access a singleton + * defined by a bean definition that already been created, in a raw fashion. + * @param beanName the name of the bean to look for + * @return the registered singleton object, or null if none found + * @see ConfigurableListableBeanFactory#getBeanDefinition + */ + Object getSingleton(String beanName); + + /** + * Check if this registry contains a singleton instance with the given name. + *

    Only checks already instantiated singletons; does not return true + * for singleton bean definitions which have not been instantiated yet. + *

    The main purpose of this method is to check manually registered singletons + * (see {@link #registerSingleton}). Can also be used to check whether a + * singleton defined by a bean definition has already been created. + *

    To check whether a bean factory contains a bean definition with a given name, + * use ListableBeanFactory's containsBeanDefinition. Calling both + * containsBeanDefinition and containsSingleton answers + * whether a specific bean factory contains an own bean with the given name. + *

    Use BeanFactory's containsBean for general checks whether the + * factory knows about a bean with a given name (whether manually registered singleton + * instance or created by bean definition), also checking ancestor factories. + * @param beanName the name of the bean to look for + * @return if this bean factory contains a singleton instance with the given name + * @see #registerSingleton + * @see org.springframework.beans.factory.ListableBeanFactory#containsBeanDefinition + * @see org.springframework.beans.factory.BeanFactory#containsBean + */ + boolean containsSingleton(String beanName); + + /** + * Return the names of singleton beans registered in this registry. + *

    Only checks already instantiated singletons; does not return names + * for singleton bean definitions which have not been instantiated yet. + *

    The main purpose of this method is to check manually registered singletons + * (see {@link #registerSingleton}). Can also be used to check which + * singletons defined by a bean definition have already been created. + * @return the list of names as String array (never null) + * @see #registerSingleton + * @see org.springframework.beans.factory.support.BeanDefinitionRegistry#getBeanDefinitionNames + * @see org.springframework.beans.factory.ListableBeanFactory#getBeanDefinitionNames + */ + String[] getSingletonNames(); + + /** + * Return the number of singleton beans registered in this registry. + *

    Only checks already instantiated singletons; does not count + * singleton bean definitions which have not been instantiated yet. + *

    The main purpose of this method is to check manually registered singletons + * (see {@link #registerSingleton}). Can also be used to count the number of + * singletons defined by a bean definition that have already been created. + * @return the number of singleton beans + * @see #registerSingleton + * @see org.springframework.beans.factory.support.BeanDefinitionRegistry#getBeanDefinitionCount + * @see org.springframework.beans.factory.ListableBeanFactory#getBeanDefinitionCount + */ + int getSingletonCount(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/SmartInstantiationAwareBeanPostProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/SmartInstantiationAwareBeanPostProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/SmartInstantiationAwareBeanPostProcessor.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import java.lang.reflect.Constructor; + +import org.springframework.beans.BeansException; + +/** + * Extension of the {@link InstantiationAwareBeanPostProcessor} interface, + * adding a callback for predicting the eventual type of a processed bean. + * + *

    NOTE: This interface is a special purpose interface, mainly for + * internal use within the framework. In general, application-provided + * post-processors should simply implement the plain {@link BeanPostProcessor} + * interface or derive from the {@link InstantiationAwareBeanPostProcessorAdapter} + * class. New methods might be added to this interface even in point releases. + * + * @author Juergen Hoeller + * @since 2.0.3 + * @see InstantiationAwareBeanPostProcessorAdapter + */ +public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor { + + /** + * Predict the type of the bean to be eventually returned from this + * processor's {@link #postProcessBeforeInstantiation} callback. + * @param beanClass the raw class of the bean + * @param beanName the name of the bean + * @return the type of the bean, or null if not predictable + * @throws org.springframework.beans.BeansException in case of errors + */ + Class predictBeanType(Class beanClass, String beanName) throws BeansException; + + /** + * Determine the candidate constructors to use for the given bean. + * @param beanClass the raw class of the bean (never null) + * @param beanName the name of the bean + * @return the candidate constructors, or null if none specified + * @throws org.springframework.beans.BeansException in case of errors + */ + Constructor[] determineCandidateConstructors(Class beanClass, String beanName) throws BeansException; + + /** + * Obtain a reference for early access to the specified bean, + * typically for the purpose of resolving a circular reference. + *

    This callback gives post-processors a chance to expose a wrapper + * early - that is, before the target bean instance is fully initialized. + * The exposed object should be equivalent to the what + * {@link #postProcessBeforeInitialization} / {@link #postProcessAfterInitialization} + * would expose otherwise. Note that the object returned by this method will + * be used as bean reference unless the post-processor returns a different + * wrapper from said post-process callbacks. In other words: Those post-process + * callbacks may either eventually expose the same reference or alternatively + * return the raw bean instance from those subsequent callbacks (if the wrapper + * for the affected bean has been built for a call to this method already, + * it will be exposes as final bean reference by default). + * @param bean the raw bean instance + * @param beanName the name of the bean + * @return the object to expose as bean reference + * (typically with the passed-in bean instance as default) + * @throws org.springframework.beans.BeansException in case of errors + */ + Object getEarlyBeanReference(Object bean, String beanName) throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/TypedStringValue.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/TypedStringValue.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/TypedStringValue.java 17 Aug 2012 15:11:35 -0000 1.1 @@ -0,0 +1,193 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.config; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; + +/** + * Holder for a typed String value. Can be added to bean definitions + * in order to explicitly specify a target type for a String value, + * for example for collection elements. + * + *

    This holder will just store the String value and the target type. + * The actual conversion will be performed by the bean factory. + * + * @author Juergen Hoeller + * @since 1.2 + * @see BeanDefinition#getPropertyValues + * @see org.springframework.beans.MutablePropertyValues#addPropertyValue + */ +public class TypedStringValue implements BeanMetadataElement { + + private String value; + + private Object targetType; + + private Object source; + + + /** + * Create a new {@link TypedStringValue} for the given String value. + * @param value the String value + */ + public TypedStringValue(String value) { + setValue(value); + } + + /** + * Create a new {@link TypedStringValue} for the given String value + * and target type. + * @param value the String value + * @param targetType the type to convert to + */ + public TypedStringValue(String value, Class targetType) { + setValue(value); + setTargetType(targetType); + } + + /** + * Create a new {@link TypedStringValue} for the given String value + * and target type. + * @param value the String value + * @param targetTypeName the type to convert to + */ + public TypedStringValue(String value, String targetTypeName) { + setValue(value); + setTargetTypeName(targetTypeName); + } + + + /** + * Set the String value. + *

    Only necessary for manipulating a registered value, + * for example in BeanFactoryPostProcessors. + * @see PropertyPlaceholderConfigurer + */ + public void setValue(String value) { + this.value = value; + } + + /** + * Return the String value. + */ + public String getValue() { + return this.value; + } + + /** + * Set the type to convert to. + *

    Only necessary for manipulating a registered value, + * for example in BeanFactoryPostProcessors. + * @see PropertyPlaceholderConfigurer + */ + public void setTargetType(Class targetType) { + Assert.notNull(targetType, "'targetType' must not be null"); + this.targetType = targetType; + } + + /** + * Return the type to convert to. + */ + public Class getTargetType() { + if (!(this.targetType instanceof Class)) { + throw new IllegalStateException("Typed String value does not carry a resolved target type"); + } + return (Class) this.targetType; + } + + /** + * Specify the type to convert to. + */ + public void setTargetTypeName(String targetTypeName) { + Assert.notNull(targetTypeName, "'targetTypeName' must not be null"); + this.targetType = targetTypeName; + } + + /** + * Return the type to convert to. + */ + public String getTargetTypeName() { + if (this.targetType instanceof Class) { + return ((Class) this.targetType).getName(); + } + else { + return (String) this.targetType; + } + } + + /** + * Return whether this typed String value carries a target type . + */ + public boolean hasTargetType() { + return (this.targetType instanceof Class); + } + + /** + * Determine the type to convert to, resolving it from a specified class name + * if necessary. Will also reload a specified Class from its name when called + * with the target type already resolved. + * @param classLoader the ClassLoader to use for resolving a (potential) class name + * @return the resolved type to convert to + * @throws ClassNotFoundException if the type cannot be resolved + */ + public Class resolveTargetType(ClassLoader classLoader) throws ClassNotFoundException { + if (this.targetType == null) { + return null; + } + Class resolvedClass = ClassUtils.forName(getTargetTypeName(), classLoader); + this.targetType = resolvedClass; + return resolvedClass; + } + + + /** + * Set the configuration source Object for this metadata element. + *

    The exact type of the object will depend on the configuration mechanism used. + */ + public void setSource(Object source) { + this.source = source; + } + + public Object getSource() { + return this.source; + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof TypedStringValue)) { + return false; + } + TypedStringValue otherValue = (TypedStringValue) other; + return (ObjectUtils.nullSafeEquals(this.value, otherValue.value) && + ObjectUtils.nullSafeEquals(this.targetType, otherValue.targetType)); + } + + public int hashCode() { + return ObjectUtils.nullSafeHashCode(this.value) * 29 + ObjectUtils.nullSafeHashCode(this.targetType); + } + + public String toString() { + return "TypedStringValue: value [" + this.value + "], target type [" + this.targetType + "]"; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/config/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/config/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/config/package.html 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,7 @@ + + + +SPI interfaces and configuration-related convenience classes for bean factories. + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/generic/GenericBeanFactoryAccessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/generic/GenericBeanFactoryAccessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/generic/GenericBeanFactoryAccessor.java 17 Aug 2012 15:11:50 -0000 1.1 @@ -0,0 +1,140 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.generic; + +import java.lang.annotation.Annotation; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.util.Assert; + +/** + * Simple wrapper around a {@link ListableBeanFactory} that provides typed, generics-based + * access to key methods. This removes the need for casting in many cases and should + * increase compile-time type safety. + * + *

    Provides a simple mechanism for accessing all beans with a particular {@link Annotation}. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public class GenericBeanFactoryAccessor { + + /** + * The {@link ListableBeanFactory} being wrapped. + */ + private final ListableBeanFactory beanFactory; + + + /** + * Constructs a GenericBeanFactoryAccessor that wraps the supplied {@link ListableBeanFactory}. + */ + public GenericBeanFactoryAccessor(ListableBeanFactory beanFactory) { + Assert.notNull(beanFactory, "Bean factory must not be null"); + this.beanFactory = beanFactory; + } + + /** + * Return the wrapped {@link ListableBeanFactory}. + */ + public final ListableBeanFactory getBeanFactory() { + return this.beanFactory; + } + + + /** + * @see org.springframework.beans.factory.BeanFactory#getBean(String) + */ + public T getBean(String name) throws BeansException { + return (T) this.beanFactory.getBean(name); + } + + /** + * @see org.springframework.beans.factory.BeanFactory#getBean(String, Class) + */ + public T getBean(String name, Class requiredType) throws BeansException { + return (T) this.beanFactory.getBean(name, requiredType); + } + + /** + * @see ListableBeanFactory#getBeansOfType(Class) + */ + public Map getBeansOfType(Class type) throws BeansException { + return this.beanFactory.getBeansOfType(type); + } + + /** + * @see ListableBeanFactory#getBeansOfType(Class, boolean, boolean) + */ + public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException { + + return this.beanFactory.getBeansOfType(type, includeNonSingletons, allowEagerInit); + } + + /** + * Find all beans whose Class has the supplied {@link Annotation} type. + * @param annotationType the type of annotation to look for + * @return a Map with the matching beans, containing the bean names as + * keys and the corresponding bean instances as values + */ + public Map getBeansWithAnnotation(Class annotationType) { + Map results = new LinkedHashMap(); + for (String beanName : this.beanFactory.getBeanNamesForType(Object.class)) { + if (findAnnotationOnBean(beanName, annotationType) != null) { + results.put(beanName, this.beanFactory.getBean(beanName)); + } + } + return results; + } + + /** + * Find a {@link Annotation} of annotationType on the specified + * bean, traversing its interfaces and super classes if no annotation can be + * found on the given class itself, as well as checking its raw bean class + * if not found on the exposed bean reference (e.g. in case of a proxy). + * @param beanName the name of the bean to look for annotations on + * @param annotationType the annotation class to look for + * @return the annotation of the given type found, or null + * @see org.springframework.core.annotation.AnnotationUtils#findAnnotation(Class, Class) + */ + public A findAnnotationOnBean(String beanName, Class annotationType) { + Class handlerType = this.beanFactory.getType(beanName); + A ann = AnnotationUtils.findAnnotation(handlerType, annotationType); + if (ann == null && this.beanFactory instanceof ConfigurableBeanFactory && + this.beanFactory.containsBeanDefinition(beanName)) { + ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) this.beanFactory; + BeanDefinition bd = cbf.getMergedBeanDefinition(beanName); + if (bd instanceof AbstractBeanDefinition) { + AbstractBeanDefinition abd = (AbstractBeanDefinition) bd; + if (abd.hasBeanClass()) { + Class beanClass = abd.getBeanClass(); + ann = AnnotationUtils.findAnnotation(beanClass, annotationType); + } + } + } + return ann; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/generic/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/generic/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/generic/package.html 17 Aug 2012 15:11:50 -0000 1.1 @@ -0,0 +1,8 @@ + + + +Support package for generic BeanFactory access, +leveraging Java 5 generics in the accessor API. + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/AbstractComponentDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/AbstractComponentDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/AbstractComponentDefinition.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanReference; + +/** + * Base implementation of {@link ComponentDefinition} that provides a basic implementation of + * {@link #getDescription} which delegates to {@link #getName}. Also provides a base implementation + * of {@link #toString} which delegates to {@link #getDescription} in keeping with the recommended + * implementation strategy. Also provides default implementations of {@link #getInnerBeanDefinitions} + * and {@link #getBeanReferences} that return an empty array. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public abstract class AbstractComponentDefinition implements ComponentDefinition { + + /** + * Delegates to {@link #getName}. + */ + public String getDescription() { + return getName(); + } + + /** + * Returns an empty array. + */ + public BeanDefinition[] getBeanDefinitions() { + return new BeanDefinition[0]; + } + + /** + * Returns an empty array. + */ + public BeanDefinition[] getInnerBeanDefinitions() { + return new BeanDefinition[0]; + } + + /** + * Returns an empty array. + */ + public BeanReference[] getBeanReferences() { + return new BeanReference[0]; + } + + /** + * Delegates to {@link #getDescription}. + */ + public String toString() { + return getDescription(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/AliasDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/AliasDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/AliasDefinition.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.util.Assert; + +/** + * Representation of an alias that has been registered during the parsing process. + * + * @author Juergen Hoeller + * @since 2.0 + * @see ReaderEventListener#aliasRegistered(AliasDefinition) + */ +public class AliasDefinition implements BeanMetadataElement { + + private final String beanName; + + private final String alias; + + private final Object source; + + + /** + * Create a new AliasDefinition. + * @param beanName the canonical name of the bean + * @param alias the alias registered for the bean + */ + public AliasDefinition(String beanName, String alias) { + this(beanName, alias, null); + } + + /** + * Create a new AliasDefinition. + * @param beanName the canonical name of the bean + * @param alias the alias registered for the bean + * @param source the source object (may be null) + */ + public AliasDefinition(String beanName, String alias, Object source) { + Assert.notNull(beanName, "Bean name must not be null"); + Assert.notNull(alias, "Alias must not be null"); + this.beanName = beanName; + this.alias = alias; + this.source = source; + } + + + /** + * Return the canonical name of the bean. + */ + public final String getBeanName() { + return this.beanName; + } + + /** + * Return the alias registered for the bean. + */ + public final String getAlias() { + return this.alias; + } + + public final Object getSource() { + return this.source; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/BeanComponentDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/BeanComponentDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/BeanComponentDefinition.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,134 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.PropertyValue; +import org.springframework.beans.PropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.config.BeanReference; + +/** + * ComponentDefinition based on a standard BeanDefinition, exposing the given bean + * definition as well as inner bean definitions and bean references for the given bean. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public class BeanComponentDefinition extends BeanDefinitionHolder implements ComponentDefinition { + + private BeanDefinition[] innerBeanDefinitions; + + private BeanReference[] beanReferences; + + + /** + * Create a new BeanComponentDefinition for the given bean. + * @param beanDefinition the BeanDefinition + * @param beanName the name of the bean + */ + public BeanComponentDefinition(BeanDefinition beanDefinition, String beanName) { + super(beanDefinition, beanName); + findInnerBeanDefinitionsAndBeanReferences(beanDefinition); + } + + /** + * Create a new BeanComponentDefinition for the given bean. + * @param beanDefinition the BeanDefinition + * @param beanName the name of the bean + * @param aliases alias names for the bean, or null if none + */ + public BeanComponentDefinition(BeanDefinition beanDefinition, String beanName, String[] aliases) { + super(beanDefinition, beanName, aliases); + findInnerBeanDefinitionsAndBeanReferences(beanDefinition); + } + + /** + * Create a new BeanComponentDefinition for the given bean. + * @param holder the BeanDefinitionHolder encapsulating the + * bean definition as well as the name of the bean + */ + public BeanComponentDefinition(BeanDefinitionHolder holder) { + super(holder); + findInnerBeanDefinitionsAndBeanReferences(holder.getBeanDefinition()); + } + + + private void findInnerBeanDefinitionsAndBeanReferences(BeanDefinition beanDefinition) { + List innerBeans = new ArrayList(); + List references = new ArrayList(); + PropertyValues propertyValues = beanDefinition.getPropertyValues(); + for (int i = 0; i < propertyValues.getPropertyValues().length; i++) { + PropertyValue propertyValue = propertyValues.getPropertyValues()[i]; + Object value = propertyValue.getValue(); + if (value instanceof BeanDefinitionHolder) { + innerBeans.add(((BeanDefinitionHolder) value).getBeanDefinition()); + } + else if (value instanceof BeanDefinition) { + innerBeans.add(value); + } + else if (value instanceof BeanReference) { + references.add(value); + } + } + this.innerBeanDefinitions = (BeanDefinition[]) innerBeans.toArray(new BeanDefinition[innerBeans.size()]); + this.beanReferences = (BeanReference[]) references.toArray(new BeanReference[references.size()]); + } + + + public String getName() { + return getBeanName(); + } + + public String getDescription() { + return getShortDescription(); + } + + public BeanDefinition[] getBeanDefinitions() { + return new BeanDefinition[] {getBeanDefinition()}; + } + + public BeanDefinition[] getInnerBeanDefinitions() { + return this.innerBeanDefinitions; + } + + public BeanReference[] getBeanReferences() { + return this.beanReferences; + } + + + /** + * This implementation returns this ComponentDefinition's description. + * @see #getDescription() + */ + public String toString() { + return getDescription(); + } + + /** + * This implementations expects the other object to be of type BeanComponentDefinition + * as well, in addition to the superclass's equality requirements. + */ + public boolean equals(Object other) { + return (this == other || (other instanceof BeanComponentDefinition && super.equals(other))); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/BeanDefinitionParsingException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/BeanDefinitionParsingException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/BeanDefinitionParsingException.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.beans.factory.BeanDefinitionStoreException; + +/** + * Exception thrown when a bean definition reader encounters an error + * during the parsing process. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @since 2.0 + */ +public class BeanDefinitionParsingException extends BeanDefinitionStoreException { + + /** + * Create a new BeanDefinitionParsingException. + * @param problem the configuration problem that was detected during the parsing process + */ + public BeanDefinitionParsingException(Problem problem) { + super(problem.getResourceDescription(), problem.toString(), problem.getRootCause()); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/BeanEntry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/BeanEntry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/BeanEntry.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +/** + * {@link ParseState} entry representing a bean definition. + * + * @author Rob Harrop + * @since 2.0 + */ +public class BeanEntry implements ParseState.Entry { + + private String beanDefinitionName; + + + /** + * Creates a new instance of {@link BeanEntry} class. + * @param beanDefinitionName the name of the associated bean definition + */ + public BeanEntry(String beanDefinitionName) { + this.beanDefinitionName = beanDefinitionName; + } + + + public String toString() { + return "Bean '" + this.beanDefinitionName + "'"; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ComponentDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/ComponentDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ComponentDefinition.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,123 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanReference; + +/** + * Interface that describes the logical view of a set of {@link BeanDefinition BeanDefinitions} + * and {@link BeanReference BeanReferences} as presented in some configuration context. + * + *

    With the introduction of {@link org.springframework.beans.factory.xml.NamespaceHandler pluggable custom XML tags}, + * it is now possible for a single logical configuration entity, in this case an XML tag, to + * create multiple {@link BeanDefinition BeanDefinitions} and {@link BeanReference RuntimeBeanReferences} + * in order to provide more succinct configuration and greater convenience to end users. As such, it can + * no longer be assumed that each configuration entity (e.g. XML tag) maps to one {@link BeanDefinition}. + * For tool vendors and other users who wish to present visualization or support for configuring Spring + * applications it is important that there is some mechanism in place to tie the {@link BeanDefinition BeanDefinitions} + * in the {@link org.springframework.beans.factory.BeanFactory} back to the configuration data in a way + * that has concrete meaning to the end user. As such, {@link org.springframework.beans.factory.xml.NamespaceHandler} + * implementations are able to publish events in the form of a ComponentDefinition for each + * logical entity being configured. Third parties can then {@link org.springframework.beans.factory.parsing.ReaderEventListener subscribe to these events}, + * allowing for a user-centric view of the bean metadata. + * + *

    Each ComponentDefinition has a {@link #getSource source object} which is configuration-specific. + * In the case of XML-based configuration this is typically the {@link org.w3c.dom.Node} which contains the user + * supplied configuration information. In addition to this, each {@link BeanDefinition} enclosed in a + * ComponentDefinition has its own {@link BeanDefinition#getSource() source object} which may point + * to a different, more specific, set of configuration data. Beyond this, individual pieces of bean metadata such + * as the {@link org.springframework.beans.PropertyValue PropertyValues} may also have a source object giving an + * even greater level of detail. Source object extraction is handled through the + * {@link org.springframework.beans.factory.parsing.SourceExtractor} which can be customized as required. + * + *

    Whilst direct access to important {@link BeanReference BeanReferences} is provided through + * {@link #getBeanReferences}, tools may wish to inspect all {@link BeanDefinition BeanDefinitions} to gather + * the full set of {@link BeanReference BeanReferences}. Implementations are required to provide + * all {@link BeanReference BeanReferences} that are required to validate the configuration of the + * overall logical entity as well as those required to provide full user visualisation of the configuration. + * It is expected that certain {@link BeanReference BeanReferences} will not be important to + * validation or to the user view of the configuration and as such these may be ommitted. A tool may wish to + * display any additional {@link BeanReference BeanReferences} sourced through the supplied + * {@link BeanDefinition BeanDefinitions} but this is not considered to be a typical case. + * + *

    Tools can determine the important of contained {@link BeanDefinition BeanDefinitions} by checking the + * {@link BeanDefinition#getRole role identifier}. The role is essentially a hint to the tool as to how + * important the configuration provider believes a {@link BeanDefinition} is to the end user. It is expected + * that tools will not display all {@link BeanDefinition BeanDefinitions} for a given + * ComponentDefinition choosing instead to filter based on the role. Tools may choose to make + * this filtering user configurable. Particular notice should be given to the + * {@link BeanDefinition#ROLE_INFRASTRUCTURE INFRASTRUCTURE role identifier}. {@link BeanDefinition BeanDefinitions} + * classified with this role are completely unimportant to the end user and are required only for + * internal implementation reasons. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + * @see AbstractComponentDefinition + * @see CompositeComponentDefinition + * @see BeanComponentDefinition + * @see ReaderEventListener#componentRegistered(ComponentDefinition) + */ +public interface ComponentDefinition extends BeanMetadataElement { + + /** + * Get the user-visible name of this ComponentDefinition. + *

    This should link back directly to the corresponding configuration data + * for this component in a given context. + */ + String getName(); + + /** + * Return a friendly description of the described component. + *

    Implementations are encouraged to return the same value from + * toString(). + */ + String getDescription(); + + /** + * Return the {@link BeanDefinition BeanDefinitions} that were registered + * to form this ComponentDefinition. + *

    It should be noted that a ComponentDefinition may well be related with + * other {@link BeanDefinition BeanDefinitions} via {@link BeanReference references}, + * however these are not included as they may be not available immediately. + * Important {@link BeanReference BeanReferences} are available from {@link #getBeanReferences()}. + * @return the array of BeanDefinitions, or an empty array if none + */ + BeanDefinition[] getBeanDefinitions(); + + /** + * Return the {@link BeanDefinition BeanDefinitions} that represent all relevant + * inner beans within this component. + *

    Other inner beans may exist within the associated {@link BeanDefinition BeanDefinitions}, + * however these are not considered to be needed for validation or for user visualization. + * @return the array of BeanDefinitions, or an empty array if none + */ + BeanDefinition[] getInnerBeanDefinitions(); + + /** + * Return the set of {@link BeanReference BeanReferences} that are considered + * to be important to this ComponentDefinition. + *

    Other {@link BeanReference BeanReferences} may exist within the associated + * {@link BeanDefinition BeanDefinitions}, however these are not considered + * to be needed for validation or for user visualization. + * @return the array of BeanReferences, or an empty array if none + */ + BeanReference[] getBeanReferences(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/CompositeComponentDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/CompositeComponentDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/CompositeComponentDefinition.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import java.util.LinkedList; +import java.util.List; + +import org.springframework.util.Assert; + +/** + * {@link ComponentDefinition} implementation that holds one or more nested + * {@link ComponentDefinition} instances, aggregating them into a named group + * of components. + * + * @author Juergen Hoeller + * @since 2.0.1 + * @see #getNestedComponents() + */ +public class CompositeComponentDefinition extends AbstractComponentDefinition { + + private final String name; + + private final Object source; + + private final List nestedComponents = new LinkedList(); + + + /** + * Create a new CompositeComponentDefinition. + * @param name the name of the composite component + * @param source the source element that defines the root of the composite component + */ + public CompositeComponentDefinition(String name, Object source) { + Assert.notNull(name, "Name must not be null"); + this.name = name; + this.source = source; + } + + + public String getName() { + return this.name; + } + + public Object getSource() { + return this.source; + } + + + /** + * Add the given component as nested element of this composite component. + * @param component the nested component to add + */ + public void addNestedComponent(ComponentDefinition component) { + Assert.notNull(component, "ComponentDefinition must not be null"); + this.nestedComponents.add(component); + } + + /** + * Return the nested components that this composite component holds. + * @return the array of nested components, or an empty array if none + */ + public ComponentDefinition[] getNestedComponents() { + return (ComponentDefinition[]) + this.nestedComponents.toArray(new ComponentDefinition[this.nestedComponents.size()]); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ConstructorArgumentEntry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/ConstructorArgumentEntry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ConstructorArgumentEntry.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.util.Assert; + +/** + * {@link ParseState} entry representing a (possibly indexed) + * constructor argument. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public class ConstructorArgumentEntry implements ParseState.Entry { + + private final int index; + + + /** + * Creates a new instance of the {@link ConstructorArgumentEntry} class + * representing a constructor argument with a (currently) unknown index. + */ + public ConstructorArgumentEntry() { + this.index = -1; + } + + /** + * Creates a new instance of the {@link ConstructorArgumentEntry} class + * representing a constructor argument at the supplied index. + * @param index the index of the constructor argument + * @throws IllegalArgumentException if the supplied index + * is less than zero + */ + public ConstructorArgumentEntry(int index) { + Assert.isTrue(index >= 0, "Constructor argument index must be greater than or equal to zero"); + this.index = index; + } + + + public String toString() { + return "Constructor-arg" + (this.index >= 0 ? " #" + this.index : ""); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/DefaultsDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/DefaultsDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/DefaultsDefinition.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.beans.BeanMetadataElement; + +/** + * Marker interface for a defaults definition, + * extending BeanMetadataElement to inherit source exposure. + * + *

    Concrete implementations are typically based on 'document defaults', + * for example specified at the root tag level within an XML document. + * + * @author Juergen Hoeller + * @since 2.0.2 + * @see org.springframework.beans.factory.xml.DocumentDefaultsDefinition + * @see ReaderEventListener#defaultsRegistered(DefaultsDefinition) + */ +public interface DefaultsDefinition extends BeanMetadataElement { + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/EmptyReaderEventListener.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/EmptyReaderEventListener.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/EmptyReaderEventListener.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +/** + * Empty implementation of the ReaderEventListener interface, + * providing no-op implementations of all callback methods. + * + * @author Juergen Hoeller + * @since 2.0 + */ +public class EmptyReaderEventListener implements ReaderEventListener { + + public void defaultsRegistered(DefaultsDefinition defaultsDefinition) { + // no-op + } + + public void componentRegistered(ComponentDefinition componentDefinition) { + // no-op + } + + public void aliasRegistered(AliasDefinition aliasDefinition) { + // no-op + } + + public void importProcessed(ImportDefinition importDefinition) { + // no-op + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/FailFastProblemReporter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/FailFastProblemReporter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/FailFastProblemReporter.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,79 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Simple {@link ProblemReporter} implementation that exhibits fail-fast + * behavior when errors are encountered. + * + *

    The first error encountered results in a {@link BeanDefinitionParsingException} + * being thrown. + * + *

    Warnings are written to + * {@link #setLogger(org.apache.commons.logging.Log) the log} for this class. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @author Rick Evans + * @since 2.0 + */ +public class FailFastProblemReporter implements ProblemReporter { + + private Log logger = LogFactory.getLog(getClass()); + + + /** + * Set the {@link Log logger} that is to be used to report warnings. + *

    If set to null then a default {@link Log logger} set to + * the name of the instance class will be used. + * @param logger the {@link Log logger} that is to be used to report warnings + */ + public void setLogger(Log logger) { + this.logger = (logger != null ? logger : LogFactory.getLog(getClass())); + } + + + /** + * Throws a {@link BeanDefinitionParsingException} detailing the error + * that has occurred. + * @param problem the source of the error + */ + public void fatal(Problem problem) { + throw new BeanDefinitionParsingException(problem); + } + + /** + * Throws a {@link BeanDefinitionParsingException} detailing the error + * that has occurred. + * @param problem the source of the error + */ + public void error(Problem problem) { + throw new BeanDefinitionParsingException(problem); + } + + /** + * Writes the supplied {@link Problem} to the {@link Log} at WARN level. + * @param problem the source of the warning + */ + public void warning(Problem problem) { + this.logger.warn(problem, problem.getRootCause()); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ImportDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/ImportDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ImportDefinition.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.core.io.Resource; +import org.springframework.util.Assert; + +/** + * Representation of an import that has been processed during the parsing process. + * + * @author Juergen Hoeller + * @since 2.0 + * @see ReaderEventListener#importProcessed(ImportDefinition) + */ +public class ImportDefinition implements BeanMetadataElement { + + private final String importedResource; + + private final Resource[] actualResources; + + private final Object source; + + + /** + * Create a new ImportDefinition. + * @param importedResource the location of the imported resource + */ + public ImportDefinition(String importedResource) { + this(importedResource, null, null); + } + + /** + * Create a new ImportDefinition. + * @param importedResource the location of the imported resource + * @param source the source object (may be null) + */ + public ImportDefinition(String importedResource, Object source) { + this(importedResource, null, source); + } + + /** + * Create a new ImportDefinition. + * @param importedResource the location of the imported resource + * @param source the source object (may be null) + */ + public ImportDefinition(String importedResource, Resource[] actualResources, Object source) { + Assert.notNull(importedResource, "Imported resource must not be null"); + this.importedResource = importedResource; + this.actualResources = actualResources; + this.source = source; + } + + + /** + * Return the location of the imported resource. + */ + public final String getImportedResource() { + return this.importedResource; + } + + public final Resource[] getActualResources() { + return this.actualResources; + } + + public final Object getSource() { + return this.source; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/Location.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/Location.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/Location.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.core.io.Resource; +import org.springframework.util.Assert; + +/** + * Class that models an arbitrary location in a {@link Resource resource}. + * + *

    Typically used to track the location of problematic or erroneous + * metadata in XML configuration files. For example, a + * {@link #getSource() source} location might be 'The bean defined on + * line 76 of beans.properties has an invalid Class'; another source might + * be the actual DOM Element from a parsed XML {@link org.w3c.dom.Document}; + * or the source object might simply be null. + * + * @author Rob Harrop + * @since 2.0 + */ +public class Location { + + private final Resource resource; + + private final Object source; + + + /** + * Create a new instance of the {@link Location} class. + * @param resource the resource with which this location is associated + */ + public Location(Resource resource) { + this(resource, null); + } + + /** + * Create a new instance of the {@link Location} class. + * @param resource the resource with which this location is associated + * @param source the actual location within the associated resource + * (may be null) + */ + public Location(Resource resource, Object source) { + Assert.notNull(resource, "Resource must not be null"); + this.resource = resource; + this.source = source; + } + + + /** + * Get the resource with which this location is associated. + */ + public Resource getResource() { + return this.resource; + } + + /** + * Get the actual location within the associated {@link #getResource() resource} + * (may be null). + *

    See the {@link Location class level javadoc for this class} for examples + * of what the actual type of the returned object may be. + */ + public Object getSource() { + return this.source; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/NullSourceExtractor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/NullSourceExtractor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/NullSourceExtractor.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.core.io.Resource; + +/** + * Simple implementation of {@link SourceExtractor} that returns null + * as the source metadata. + * + *

    This is the default implementation and prevents too much metadata from being + * held in memory during normal (non-tooled) runtime usage. + * + * @author Rob Harrop + * @since 2.0 + */ +public class NullSourceExtractor implements SourceExtractor { + + /** + * This implementation simply returns null for any input. + */ + public Object extractSource(Object sourceCandidate, Resource definitionResource) { + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ParseState.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/ParseState.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ParseState.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,119 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import java.util.Stack; + +/** + * Simple {@link Stack}-based structure for tracking the logical position during + * a parsing process. {@link Entry entries} are added to the stack at + * each point during the parse phase in a reader-specific manner. + * + *

    Calling {@link #toString()} will render a tree-style view of the current logical + * position in the parse phase. This representation is intended for use in + * error messages. + * + * @author Rob Harrop + * @since 2.0 + */ +public final class ParseState { + + /** + * Tab character used when rendering the tree-style representation. + */ + private static final char TAB = '\t'; + + /** + * Internal {@link Stack} storage. + */ + private final Stack state; + + + /** + * Create a new ParseState with an empty {@link Stack}. + */ + public ParseState() { + this.state = new Stack(); + } + + /** + * Create a new ParseState whose {@link Stack} is a {@link Object#clone clone} + * of that of the passed in ParseState. + */ + private ParseState(ParseState other) { + this.state = (Stack) other.state.clone(); + } + + + /** + * Add a new {@link Entry} to the {@link Stack}. + */ + public void push(Entry entry) { + this.state.push(entry); + } + + /** + * Remove an {@link Entry} from the {@link Stack}. + */ + public void pop() { + this.state.pop(); + } + + /** + * Return the {@link Entry} currently at the top of the {@link Stack} or + * null if the {@link Stack} is empty. + */ + public Entry peek() { + return (Entry) (this.state.empty() ? null : this.state.peek()); + } + + /** + * Create a new instance of {@link ParseState} which is an independent snapshot + * of this instance. + */ + public ParseState snapshot() { + return new ParseState(this); + } + + + /** + * Returns a tree-style representation of the current ParseState. + */ + public String toString() { + StringBuffer sb = new StringBuffer(); + for (int x = 0; x < this.state.size(); x++) { + if (x > 0) { + sb.append('\n'); + for (int y = 0; y < x; y++) { + sb.append(TAB); + } + sb.append("-> "); + } + sb.append(this.state.get(x)); + } + return sb.toString(); + } + + + /** + * Marker interface for entries into the {@link ParseState}. + */ + public interface Entry { + + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/PassThroughSourceExtractor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/PassThroughSourceExtractor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/PassThroughSourceExtractor.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.core.io.Resource; + +/** + * Simple {@link SourceExtractor} implementation that just passes + * the candidate source metadata object through for attachment. + * + *

    Using this implementation means that tools will get raw access to the + * underlying configuration source metadata provided by the tool. + * + *

    This implementation should not be used in a production + * application since it is likely to keep too much metadata in memory + * (unnecessarily). + * + * @author Rob Harrop + * @since 2.0 + */ +public class PassThroughSourceExtractor implements SourceExtractor { + + /** + * Simply returns the supplied sourceCandidate as-is. + * @param sourceCandidate the source metadata + * @return the supplied sourceCandidate + */ + public Object extractSource(Object sourceCandidate, Resource definingResource) { + return sourceCandidate; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/Problem.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/Problem.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/Problem.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,128 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.util.Assert; + +/** + * Represents a problem with a bean definition configuration. + * Mainly serves as common argument passed into a {@link ProblemReporter}. + * + *

    May indicate a potentially fatal problem (an error) or just a warning. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + * @see ProblemReporter + */ +public class Problem { + + private final String message; + + private final Location location; + + private final ParseState parseState; + + private final Throwable rootCause; + + + /** + * Create a new instance of the {@link Problem} class. + * @param message a message detailing the problem + * @param location the location within a bean configuration source that triggered the error + */ + public Problem(String message, Location location) { + this(message, location, null, null); + } + + /** + * Create a new instance of the {@link Problem} class. + * @param message a message detailing the problem + * @param parseState the {@link ParseState} at the time of the error + * @param location the location within a bean configuration source that triggered the error + */ + public Problem(String message, Location location, ParseState parseState) { + this(message, location, parseState, null); + } + + /** + * Create a new instance of the {@link Problem} class. + * @param message a message detailing the problem + * @param rootCause the underlying expection that caused the error (may be null) + * @param parseState the {@link ParseState} at the time of the error + * @param location the location within a bean configuration source that triggered the error + */ + public Problem(String message, Location location, ParseState parseState, Throwable rootCause) { + Assert.notNull(message, "Message must not be null"); + Assert.notNull(location, "Location must not be null"); + this.message = message; + this.location = location; + this.parseState = parseState; + this.rootCause = rootCause; + } + + + /** + * Get the message detailing the problem. + */ + public String getMessage() { + return this.message; + } + + /** + * Get the location within a bean configuration source that triggered the error. + */ + public Location getLocation() { + return this.location; + } + + /** + * Get the description of the bean configuration source that triggered the error, + * as contained within this Problem's Location object. + * @see #getLocation() + */ + public String getResourceDescription() { + return getLocation().getResource().getDescription(); + } + + /** + * Get the {@link ParseState} at the time of the error (may be null). + */ + public ParseState getParseState() { + return this.parseState; + } + + /** + * Get the underlying expection that caused the error (may be null). + */ + public Throwable getRootCause() { + return this.rootCause; + } + + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("Configuration problem: "); + sb.append(getMessage()); + sb.append("\nOffending resource: ").append(getResourceDescription()); + if (getParseState() != null) { + sb.append('\n').append(getParseState()); + } + return sb.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ProblemReporter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/ProblemReporter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ProblemReporter.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +/** + * SPI interface allowing tools and other external processes to handle errors + * and warnings reported during bean definition parsing. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + * @see Problem + */ +public interface ProblemReporter { + + /** + * Called when a fatal error is encountered during the parsing process. + *

    Implementations must treat the given problem as fatal, + * i.e. they have to eventually raise an exception. + * @param problem the source of the error (never null) + */ + void fatal(Problem problem); + + /** + * Called when an error is encountered during the parsing process. + *

    Implementations may choose to treat errors as fatal. + * @param problem the source of the error (never null) + */ + void error(Problem problem); + + /** + * Called when a warning is raised during the parsing process. + *

    Warnings are never considered to be fatal. + * @param problem the source of the warning (never null) + */ + void warning(Problem problem); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/PropertyEntry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/PropertyEntry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/PropertyEntry.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.util.StringUtils; + +/** + * {@link ParseState} entry representing a JavaBean property. + * + * @author Rob Harrop + * @since 2.0 + */ +public class PropertyEntry implements ParseState.Entry { + + private final String name; + + + /** + * Creates a new instance of the {@link PropertyEntry} class. + * @param name the name of the JavaBean property represented by this instance + * @throws IllegalArgumentException if the supplied name is null + * or consists wholly of whitespace + */ + public PropertyEntry(String name) { + if (!StringUtils.hasText(name)) { + throw new IllegalArgumentException("Invalid property name '" + name + "'."); + } + this.name = name; + } + + + public String toString() { + return "Property '" + this.name + "'"; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/QualifierEntry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/QualifierEntry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/QualifierEntry.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.util.StringUtils; + +/** + * {@link ParseState} entry representing an autowire candidate qualifier. + * + * @author Mark Fisher + * @since 2.5 + */ +public class QualifierEntry implements ParseState.Entry { + + private String typeName; + + + public QualifierEntry(String typeName) { + if (!StringUtils.hasText(typeName)) { + throw new IllegalArgumentException("Invalid qualifier type '" + typeName + "'."); + } + this.typeName = typeName; + } + + public String toString() { + return "Qualifier '" + this.typeName + "'"; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ReaderContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/ReaderContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ReaderContext.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,135 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.core.io.Resource; + +/** + * Context that gets passed along a bean definition reading process, + * encapsulating all relevant configuration as well as state. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public class ReaderContext { + + private final Resource resource; + + private final ProblemReporter problemReporter; + + private final ReaderEventListener eventListener; + + private final SourceExtractor sourceExtractor; + + + public ReaderContext(Resource resource, ProblemReporter problemReporter, + ReaderEventListener eventListener, SourceExtractor sourceExtractor) { + + this.resource = resource; + this.problemReporter = problemReporter; + this.eventListener = eventListener; + this.sourceExtractor = sourceExtractor; + } + + public final Resource getResource() { + return this.resource; + } + + + public void fatal(String message, Object source) { + fatal(message, source, null, null); + } + + public void fatal(String message, Object source, Throwable ex) { + fatal(message, source, null, ex); + } + + public void fatal(String message, Object source, ParseState parseState) { + fatal(message, source, parseState, null); + } + + public void fatal(String message, Object source, ParseState parseState, Throwable cause) { + Location location = new Location(getResource(), source); + this.problemReporter.fatal(new Problem(message, location, parseState, cause)); + } + + public void error(String message, Object source) { + error(message, source, null, null); + } + + public void error(String message, Object source, Throwable ex) { + error(message, source, null, ex); + } + + public void error(String message, Object source, ParseState parseState) { + error(message, source, parseState, null); + } + + public void error(String message, Object source, ParseState parseState, Throwable cause) { + Location location = new Location(getResource(), source); + this.problemReporter.error(new Problem(message, location, parseState, cause)); + } + + public void warning(String message, Object source) { + warning(message, source, null, null); + } + + public void warning(String message, Object source, Throwable ex) { + warning(message, source, null, ex); + } + + public void warning(String message, Object source, ParseState parseState) { + warning(message, source, parseState, null); + } + + public void warning(String message, Object source, ParseState parseState, Throwable cause) { + Location location = new Location(getResource(), source); + this.problemReporter.warning(new Problem(message, location, parseState, cause)); + } + + + public void fireDefaultsRegistered(DefaultsDefinition defaultsDefinition) { + this.eventListener.defaultsRegistered(defaultsDefinition); + } + + public void fireComponentRegistered(ComponentDefinition componentDefinition) { + this.eventListener.componentRegistered(componentDefinition); + } + + public void fireAliasRegistered(String beanName, String alias, Object source) { + this.eventListener.aliasRegistered(new AliasDefinition(beanName, alias, source)); + } + + public void fireImportProcessed(String importedResource, Object source) { + this.eventListener.importProcessed(new ImportDefinition(importedResource, source)); + } + + public void fireImportProcessed(String importedResource, Resource[] actualResources, Object source) { + this.eventListener.importProcessed(new ImportDefinition(importedResource, actualResources, source)); + } + + + public SourceExtractor getSourceExtractor() { + return this.sourceExtractor; + } + + public Object extractSource(Object sourceCandidate) { + return this.sourceExtractor.extractSource(sourceCandidate, this.resource); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ReaderEventListener.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/ReaderEventListener.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/ReaderEventListener.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import java.util.EventListener; + +/** + * Interface that receives callbacks for component, alias and import + * registrations during a bean definition reading process. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + * @see ReaderContext + */ +public interface ReaderEventListener extends EventListener { + + /** + * Notification that the given defaults has been registered. + * @param defaultsDefinition a descriptor for the defaults + * @see org.springframework.beans.factory.xml.DocumentDefaultsDefinition + */ + void defaultsRegistered(DefaultsDefinition defaultsDefinition); + + /** + * Notification that the given component has been registered. + * @param componentDefinition a descriptor for the new component + * @see BeanComponentDefinition + */ + void componentRegistered(ComponentDefinition componentDefinition); + + /** + * Notification that the given alias has been registered. + * @param aliasDefinition a descriptor for the new alias + */ + void aliasRegistered(AliasDefinition aliasDefinition); + + /** + * Notification that the given import has been processed. + * @param importDefinition a descriptor for the import + */ + void importProcessed(ImportDefinition importDefinition); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/SourceExtractor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/SourceExtractor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/SourceExtractor.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.parsing; + +import org.springframework.core.io.Resource; + +/** + * Simple strategy allowing tools to control how source metadata is attached + * to the bean definition metadata. + * + *

    Configuration parsers may provide the ability to attach + * source metadata during the parse phase. They will offer this metadata in a + * generic format which can be further modified by a {@link SourceExtractor} + * before being attached to the bean definition metadata. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + * @see org.springframework.beans.BeanMetadataElement#getSource() + * @see org.springframework.beans.factory.config.BeanDefinition + */ +public interface SourceExtractor { + + /** + * Extract the source metadata from the candidate object supplied + * by the configuration parser. + * @param sourceCandidate the original source metadata (never null) + * @param definingResource the resource that defines the given source object + * (may be null) + * @return the source metadata object to store (may be null) + */ + Object extractSource(Object sourceCandidate, Resource definingResource); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/parsing/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/parsing/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/parsing/package.html 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,7 @@ + + + +Support infrastructure for bean definition parsing. + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/AbstractServiceLoaderBasedFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/AbstractServiceLoaderBasedFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/AbstractServiceLoaderBasedFactoryBean.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.serviceloader; + +import java.util.ServiceLoader; + +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.beans.factory.config.AbstractFactoryBean; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; + +/** + * Abstract base class for FactoryBeans operating on the + * JDK 1.6 {@link java.util.ServiceLoader} facility. + * + * @author Juergen Hoeller + * @since 2.5 + * @see java.util.ServiceLoader + */ +public abstract class AbstractServiceLoaderBasedFactoryBean extends AbstractFactoryBean + implements BeanClassLoaderAware { + + private Class serviceType; + + private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); + + + /** + * Specify the desired service type (typically the service's public API). + */ + public void setServiceType(Class serviceType) { + this.serviceType = serviceType; + } + + /** + * Return the desired service type. + */ + public Class getServiceType() { + return this.serviceType; + } + + public void setBeanClassLoader(ClassLoader beanClassLoader) { + this.beanClassLoader = beanClassLoader; + } + + + /** + * Delegates to {@link #getObjectToExpose(java.util.ServiceLoader)}. + * @return the object to expose + */ + protected Object createInstance() { + Assert.notNull(getServiceType(), "Property 'serviceType' is required"); + return getObjectToExpose(ServiceLoader.load(getServiceType(), this.beanClassLoader)); + } + + /** + * Determine the actual object to expose for the given ServiceLoader. + *

    Left to concrete subclasses. + * @param serviceLoader the ServiceLoader for the configured service class + * @return the object to expose + */ + protected abstract Object getObjectToExpose(ServiceLoader serviceLoader); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/ServiceFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/ServiceFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/ServiceFactoryBean.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.serviceloader; + +import java.util.Iterator; +import java.util.ServiceLoader; + +import org.springframework.beans.factory.BeanClassLoaderAware; + +/** + * {@link org.springframework.beans.factory.FactoryBean} that exposes the + * 'primary' service for the configured service class, obtained through + * the JDK 1.6 {@link java.util.ServiceLoader} facility. + * + * @author Juergen Hoeller + * @since 2.5 + * @see java.util.ServiceLoader + */ +public class ServiceFactoryBean extends AbstractServiceLoaderBasedFactoryBean implements BeanClassLoaderAware { + + protected Object getObjectToExpose(ServiceLoader serviceLoader) { + Iterator it = serviceLoader.iterator(); + if (!it.hasNext()) { + throw new IllegalStateException( + "ServiceLoader could not find service for type [" + getServiceType() + "]"); + } + return it.next(); + } + + public Class getObjectType() { + return getServiceType(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/ServiceListFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/ServiceListFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/ServiceListFactoryBean.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.serviceloader; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.ServiceLoader; + +import org.springframework.beans.factory.BeanClassLoaderAware; + +/** + * {@link org.springframework.beans.factory.FactoryBean} that exposes all + * services for the configured service class, represented as a List of service objects, + * obtained through the JDK 1.6 {@link java.util.ServiceLoader} facility. + * + * @author Juergen Hoeller + * @since 2.5 + * @see java.util.ServiceLoader + */ +public class ServiceListFactoryBean extends AbstractServiceLoaderBasedFactoryBean implements BeanClassLoaderAware { + + protected Object getObjectToExpose(ServiceLoader serviceLoader) { + List result = new LinkedList(); + Iterator it = serviceLoader.iterator(); + while (it.hasNext()) { + result.add(it.next()); + } + return result; + } + + public Class getObjectType() { + return List.class; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/ServiceLoaderFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/ServiceLoaderFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/ServiceLoaderFactoryBean.java 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.serviceloader; + +import java.util.ServiceLoader; + +import org.springframework.beans.factory.BeanClassLoaderAware; + +/** + * {@link org.springframework.beans.factory.FactoryBean} that exposes the + * JDK 1.6 {@link java.util.ServiceLoader} for the configured service class. + * + * @author Juergen Hoeller + * @since 2.5 + * @see java.util.ServiceLoader + */ +public class ServiceLoaderFactoryBean extends AbstractServiceLoaderBasedFactoryBean implements BeanClassLoaderAware { + + protected Object getObjectToExpose(ServiceLoader serviceLoader) { + return serviceLoader; + } + + public Class getObjectType() { + return ServiceLoader.class; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/serviceloader/package.html 17 Aug 2012 15:11:49 -0000 1.1 @@ -0,0 +1,7 @@ + + + +Support package for the JDK 1.6 ServiceLoader facility. + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,1440 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.security.AccessControlContext; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.BeanWrapper; +import org.springframework.beans.BeanWrapperImpl; +import org.springframework.beans.BeansException; +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.PropertyAccessorUtils; +import org.springframework.beans.PropertyValue; +import org.springframework.beans.PropertyValues; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanCurrentlyInCreationException; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.BeanNameAware; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.ObjectFactory; +import org.springframework.beans.factory.UnsatisfiedDependencyException; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.beans.factory.config.DependencyDescriptor; +import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; +import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor; +import org.springframework.beans.factory.config.TypedStringValue; +import org.springframework.core.CollectionFactory; +import org.springframework.core.MethodParameter; +import org.springframework.core.PriorityOrdered; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; + +/** + * Abstract bean factory superclass that implements default bean creation, + * with the full capabilities specified by the {@link RootBeanDefinition} class. + * Implements the {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory} + * interface in addition to AbstractBeanFactory's {@link #createBean} method. + * + *

    Provides bean creation (with constructor resolution), property population, + * wiring (including autowiring), and initialization. Handles runtime bean + * references, resolves managed collections, calls initialization methods, etc. + * Supports autowiring constructors, properties by name, and properties by type. + * + *

    The main template method to be implemented by subclasses is + * {@link #resolveDependency(DependencyDescriptor, String, Set, TypeConverter)}, + * used for autowiring by type. In case of a factory which is capable of searching + * its bean definitions, matching beans will typically be implemented through such + * a search. For other factory styles, simplified matching algorithms can be implemented. + * + *

    Note that this class does not assume or implement bean definition + * registry capabilities. See {@link DefaultListableBeanFactory} for an implementation + * of the {@link org.springframework.beans.factory.ListableBeanFactory} and + * {@link BeanDefinitionRegistry} interfaces, which represent the API and SPI + * view of such a factory, respectively. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + * @author Mark Fisher + * @since 13.02.2004 + * @see RootBeanDefinition + * @see DefaultListableBeanFactory + * @see BeanDefinitionRegistry + */ +public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory + implements AutowireCapableBeanFactory { + + private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy(); + + /** Whether to automatically try to resolve circular references between beans */ + private boolean allowCircularReferences = true; + + /** + * Whether to resort to injecting a raw bean instance in case of circular reference, + * even if the injected bean eventually got wrapped. + */ + private boolean allowRawInjectionDespiteWrapping = false; + + /** + * Dependency types to ignore on dependency check and autowire, as Set of + * Class objects: for example, String. Default is none. + */ + private final Set ignoredDependencyTypes = new HashSet(); + + /** + * Dependency interfaces to ignore on dependency check and autowire, as Set of + * Class objects. By default, only the BeanFactory interface is ignored. + */ + private final Set ignoredDependencyInterfaces = new HashSet(); + + /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */ + private final Map factoryBeanInstanceCache = CollectionFactory.createConcurrentMapIfPossible(16); + + /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */ + private final Map filteredPropertyDescriptorsCache = new HashMap(); + + + /** + * Create a new AbstractAutowireCapableBeanFactory. + */ + public AbstractAutowireCapableBeanFactory() { + super(); + ignoreDependencyInterface(BeanNameAware.class); + ignoreDependencyInterface(BeanFactoryAware.class); + ignoreDependencyInterface(BeanClassLoaderAware.class); + } + + /** + * Create a new AbstractAutowireCapableBeanFactory with the given parent. + * @param parentBeanFactory parent bean factory, or null if none + */ + public AbstractAutowireCapableBeanFactory(BeanFactory parentBeanFactory) { + this(); + setParentBeanFactory(parentBeanFactory); + } + + + /** + * Set the instantiation strategy to use for creating bean instances. + * Default is CglibSubclassingInstantiationStrategy. + * @see CglibSubclassingInstantiationStrategy + */ + public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) { + this.instantiationStrategy = instantiationStrategy; + } + + /** + * Return the instantiation strategy to use for creating bean instances. + */ + protected InstantiationStrategy getInstantiationStrategy() { + return this.instantiationStrategy; + } + + /** + * Set whether to allow circular references between beans - and automatically + * try to resolve them. + *

    Note that circular reference resolution means that one of the involved beans + * will receive a reference to another bean that is not fully initialized yet. + * This can lead to subtle and not-so-subtle side effects on initialization; + * it does work fine for many scenarios, though. + *

    Default is "true". Turn this off to throw an exception when encountering + * a circular reference, disallowing them completely. + *

    NOTE: It is generally recommended to not rely on circular references + * between your beans. Refactor your application logic to have the two beans + * involved delegate to a third bean that encapsulates their common logic. + */ + public void setAllowCircularReferences(boolean allowCircularReferences) { + this.allowCircularReferences = allowCircularReferences; + } + + /** + * Set whether to allow the raw injection of a bean instance into some other + * bean's property, despite the injected bean eventually getting wrapped + * (for example, through AOP auto-proxying). + *

    This will only be used as a last resort in case of a circular reference + * that cannot be resolved otherwise: essentially, preferring a raw instance + * getting injected over a failure of the entire bean wiring process. + *

    Default is "false", as of Spring 2.0. Turn this on to allow for non-wrapped + * raw beans injected into some of your references, which was Spring 1.2's + * (arguably unclean) default behavior. + *

    NOTE: It is generally recommended to not rely on circular references + * between your beans, in particular with auto-proxying involved. + * @see #setAllowCircularReferences + */ + public void setAllowRawInjectionDespiteWrapping(boolean allowRawInjectionDespiteWrapping) { + this.allowRawInjectionDespiteWrapping = allowRawInjectionDespiteWrapping; + } + + /** + * Ignore the given dependency type for autowiring: + * for example, String. Default is none. + */ + public void ignoreDependencyType(Class type) { + this.ignoredDependencyTypes.add(type); + } + + /** + * Ignore the given dependency interface for autowiring. + *

    This will typically be used by application contexts to register + * dependencies that are resolved in other ways, like BeanFactory through + * BeanFactoryAware or ApplicationContext through ApplicationContextAware. + *

    By default, only the BeanFactoryAware interface is ignored. + * For further types to ignore, invoke this method for each type. + * @see org.springframework.beans.factory.BeanFactoryAware + * @see org.springframework.context.ApplicationContextAware + */ + public void ignoreDependencyInterface(Class ifc) { + this.ignoredDependencyInterfaces.add(ifc); + } + + + public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { + super.copyConfigurationFrom(otherFactory); + if (otherFactory instanceof AbstractAutowireCapableBeanFactory) { + AbstractAutowireCapableBeanFactory otherAutowireFactory = + (AbstractAutowireCapableBeanFactory) otherFactory; + this.instantiationStrategy = otherAutowireFactory.instantiationStrategy; + this.allowCircularReferences = otherAutowireFactory.allowCircularReferences; + this.ignoredDependencyTypes.addAll(otherAutowireFactory.ignoredDependencyTypes); + this.ignoredDependencyInterfaces.addAll(otherAutowireFactory.ignoredDependencyInterfaces); + } + } + + + //------------------------------------------------------------------------- + // Typical methods for creating and populating external bean instances + //------------------------------------------------------------------------- + + public Object createBean(Class beanClass) throws BeansException { + // Use prototype bean definition, to avoid registering bean as dependent bean. + RootBeanDefinition bd = new RootBeanDefinition(beanClass); + bd.setScope(SCOPE_PROTOTYPE); + return createBean(beanClass.getName(), bd, null); + } + + public void autowireBean(Object existingBean) { + // Use non-singleton bean definition, to avoid registering bean as dependent bean. + RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean)); + bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); + BeanWrapper bw = new BeanWrapperImpl(existingBean); + initBeanWrapper(bw); + populateBean(bd.getBeanClass().getName(), bd, bw); + } + + public Object configureBean(Object existingBean, String beanName) throws BeansException { + markBeanAsCreated(beanName); + BeanDefinition mbd = getMergedBeanDefinition(beanName); + RootBeanDefinition bd = null; + if (mbd instanceof RootBeanDefinition) { + RootBeanDefinition rbd = (RootBeanDefinition) mbd; + if (SCOPE_PROTOTYPE.equals(rbd.getScope())) { + bd = rbd; + } + } + if (bd == null) { + bd = new RootBeanDefinition(mbd); + bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); + } + BeanWrapper bw = new BeanWrapperImpl(existingBean); + initBeanWrapper(bw); + populateBean(beanName, bd, bw); + return initializeBean(beanName, existingBean, bd); + } + + public Object resolveDependency(DependencyDescriptor descriptor, String beanName) throws BeansException { + return resolveDependency(descriptor, beanName, null, null); + } + + + //------------------------------------------------------------------------- + // Specialized methods for fine-grained control over the bean lifecycle + //------------------------------------------------------------------------- + + public Object createBean(Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException { + // Use non-singleton bean definition, to avoid registering bean as dependent bean. + RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck); + bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); + return createBean(beanClass.getName(), bd, null); + } + + public Object autowire(Class beanClass, int autowireMode, boolean dependencyCheck) throws BeansException { + // Use non-singleton bean definition, to avoid registering bean as dependent bean. + RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck); + bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); + if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) { + return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance(); + } + else { + Object bean = getInstantiationStrategy().instantiate(bd, null, this); + populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean)); + return bean; + } + } + + public void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) + throws BeansException { + + if (autowireMode == AUTOWIRE_CONSTRUCTOR) { + throw new IllegalArgumentException("AUTOWIRE_CONSTRUCTOR not supported for existing bean instance"); + } + // Use non-singleton bean definition, to avoid registering bean as dependent bean. + RootBeanDefinition bd = + new RootBeanDefinition(ClassUtils.getUserClass(existingBean), autowireMode, dependencyCheck); + bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); + BeanWrapper bw = new BeanWrapperImpl(existingBean); + initBeanWrapper(bw); + populateBean(bd.getBeanClass().getName(), bd, bw); + } + + public void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException { + markBeanAsCreated(beanName); + BeanDefinition bd = getMergedBeanDefinition(beanName); + BeanWrapper bw = new BeanWrapperImpl(existingBean); + initBeanWrapper(bw); + applyPropertyValues(beanName, bd, bw, bd.getPropertyValues()); + } + + public Object initializeBean(Object existingBean, String beanName) { + return initializeBean(beanName, existingBean, null); + } + + public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) + throws BeansException { + + Object result = existingBean; + for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) { + BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); + result = beanProcessor.postProcessBeforeInitialization(result, beanName); + } + return result; + } + + public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) + throws BeansException { + + Object result = existingBean; + for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) { + BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); + result = beanProcessor.postProcessAfterInitialization(result, beanName); + } + return result; + } + + + //--------------------------------------------------------------------- + // Implementation of relevant AbstractBeanFactory template methods + //--------------------------------------------------------------------- + + /** + * Central method of this class: creates a bean instance, + * populates the bean instance, applies post-processors, etc. + * @see #doCreateBean + */ + protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) + throws BeanCreationException { + + AccessControlContext acc = AccessController.getContext(); + return AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + if (logger.isDebugEnabled()) { + logger.debug("Creating instance of bean '" + beanName + "'"); + } + // Make sure bean class is actually resolved at this point. + resolveBeanClass(mbd, beanName); + + // Prepare method overrides. + try { + mbd.prepareMethodOverrides(); + } + catch (BeanDefinitionValidationException ex) { + throw new BeanDefinitionStoreException(mbd.getResourceDescription(), + beanName, "Validation of method overrides failed", ex); + } + + try { + // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. + Object bean = resolveBeforeInstantiation(beanName, mbd); + if (bean != null) { + return bean; + } + } + catch (Throwable ex) { + throw new BeanCreationException(mbd.getResourceDescription(), beanName, + "BeanPostProcessor before instantiation of bean failed", ex); + } + + Object beanInstance = doCreateBean(beanName, mbd, args); + if (logger.isDebugEnabled()) { + logger.debug("Finished creating instance of bean '" + beanName + "'"); + } + return beanInstance; + } + }, acc); + } + + /** + * Actually create the specified bean. Pre-creation processing has already happened + * at this point, e.g. checking postProcessBeforeInstantiation callbacks. + *

    Differentiates between default bean instantiation, use of a + * factory method, and autowiring a constructor. + * @param beanName the name of the bean + * @param mbd the merged bean definition for the bean + * @param args arguments to use if creating a prototype using explicit arguments to a + * static factory method. This parameter must be null except in this case. + * @return a new instance of the bean + * @throws BeanCreationException if the bean could not be created + * @see #instantiateBean + * @see #instantiateUsingFactoryMethod + * @see #autowireConstructor + */ + protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) { + // Instantiate the bean. + BeanWrapper instanceWrapper = null; + if (mbd.isSingleton()) { + instanceWrapper = (BeanWrapper) this.factoryBeanInstanceCache.remove(beanName); + } + if (instanceWrapper == null) { + instanceWrapper = createBeanInstance(beanName, mbd, args); + } + final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null); + Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); + + // Allow post-processors to modify the merged bean definition. + synchronized (mbd.postProcessingLock) { + if (!mbd.postProcessed) { + applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); + mbd.postProcessed = true; + } + } + + // Eagerly cache singletons to be able to resolve circular references + // even when triggered by lifecycle interfaces like BeanFactoryAware. + boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && + isSingletonCurrentlyInCreation(beanName)); + if (earlySingletonExposure) { + if (logger.isDebugEnabled()) { + logger.debug("Eagerly caching bean '" + beanName + + "' to allow for resolving potential circular references"); + } + addSingletonFactory(beanName, new ObjectFactory() { + public Object getObject() throws BeansException { + return getEarlyBeanReference(beanName, mbd, bean); + } + }); + } + + // Initialize the bean instance. + Object exposedObject = bean; + try { + populateBean(beanName, mbd, instanceWrapper); + exposedObject = initializeBean(beanName, exposedObject, mbd); + } + catch (Throwable ex) { + if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { + throw (BeanCreationException) ex; + } + else { + throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); + } + } + + if (earlySingletonExposure) { + Object earlySingletonReference = getSingleton(beanName, false); + if (earlySingletonReference != null) { + if (exposedObject == bean) { + exposedObject = earlySingletonReference; + } + else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { + String[] dependentBeans = getDependentBeans(beanName); + Set actualDependentBeans = new LinkedHashSet(dependentBeans.length); + for (int i = 0; i < dependentBeans.length; i++) { + String dependentBean = dependentBeans[i]; + if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { + actualDependentBeans.add(dependentBean); + } + } + if (!actualDependentBeans.isEmpty()) { + throw new BeanCurrentlyInCreationException(beanName, + "Bean with name '" + beanName + "' has been injected into other beans [" + + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + + "] in its raw version as part of a circular reference, but has eventually been " + + "wrapped. This means that said other beans do not use the final version of the " + + "bean. This is often the result of over-eager type matching - consider using " + + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); + } + } + } + } + + // Register bean as disposable. + registerDisposableBeanIfNecessary(beanName, bean, mbd); + + return exposedObject; + } + + protected Class predictBeanType(String beanName, RootBeanDefinition mbd, Class[] typesToMatch) { + Class beanClass = null; + if (mbd.getFactoryMethodName() != null) { + beanClass = getTypeForFactoryMethod(beanName, mbd, typesToMatch); + } + else { + beanClass = resolveBeanClass(mbd, beanName, typesToMatch); + } + // Apply SmartInstantiationAwareBeanPostProcessors to predict the + // eventual type after a before-instantiation shortcut. + if (beanClass != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { + for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) { + BeanPostProcessor bp = (BeanPostProcessor) it.next(); + if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { + SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; + Class processedType = ibp.predictBeanType(beanClass, beanName); + if (processedType != null) { + return processedType; + } + } + } + } + return beanClass; + } + + /** + * Determine the bean type for the given bean definition which is based on + * a factory method. Only called if there is no singleton instance registered + * for the target bean already. + *

    This implementation determines the type matching {@link #createBean}'s + * different creation strategies. As far as possible, we'll perform static + * type checking to avoid creation of the target bean. + * @param beanName the name of the bean (for error handling purposes) + * @param mbd the merged bean definition for the bean + * @param typesToMatch the types to match in case of internal type matching purposes + * (also signals that the returned Class will never be exposed to application code) + * @return the type for the bean if determinable, or null else + * @see #createBean + */ + protected Class getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class[] typesToMatch) { + Class factoryClass = null; + boolean isStatic = true; + + String factoryBeanName = mbd.getFactoryBeanName(); + if (factoryBeanName != null) { + if (factoryBeanName.equals(beanName)) { + throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, + "factory-bean reference points back to the same bean definition"); + } + // Check declared factory method return type on factory class. + factoryClass = getType(factoryBeanName); + isStatic = false; + } + else { + // Check declared factory method return type on bean class. + factoryClass = resolveBeanClass(mbd, beanName, typesToMatch); + } + + if (factoryClass == null) { + return null; + } + + // If all factory methods have the same return type, return that type. + // Can't clearly figure out exact method due to type converting / autowiring! + int minNrOfArgs = mbd.getConstructorArgumentValues().getArgumentCount(); + Method[] candidates = ReflectionUtils.getAllDeclaredMethods(factoryClass); + Set returnTypes = new HashSet(1); + for (int i = 0; i < candidates.length; i++) { + Method factoryMethod = candidates[i]; + if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic && + factoryMethod.getName().equals(mbd.getFactoryMethodName()) && + factoryMethod.getParameterTypes().length >= minNrOfArgs) { + returnTypes.add(factoryMethod.getReturnType()); + } + } + + if (returnTypes.size() == 1) { + // Clear return type found: all factory methods return same type. + return (Class) returnTypes.iterator().next(); + } + else { + // Ambiguous return types found: return null to indicate "not determinable". + return null; + } + } + + /** + * This implementation checks the FactoryBean's getObjectType method + * on a plain instance of the FactoryBean, without bean properties applied yet. + * If this doesn't return a type yet, a full creation of the FactoryBean is + * used as fallback (through delegation to the superclass's implementation). + *

    The shortcut check for a FactoryBean is only applied in case of a singleton + * FactoryBean. If the FactoryBean instance itself is not kept as singleton, + * it will be fully created to check the type of its exposed object. + */ + protected Class getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) { + FactoryBean fb = (mbd.isSingleton() ? + getSingletonFactoryBeanForTypeCheck(beanName, mbd) : + getNonSingletonFactoryBeanForTypeCheck(beanName, mbd)); + + if (fb != null) { + // Try to obtain the FactoryBean's object type from this early stage of the instance. + Class objectType = getTypeForFactoryBean(fb); + if (objectType != null) { + return objectType; + } + } + + // No type found - fall back to full creation of the FactoryBean instance. + return super.getTypeForFactoryBean(beanName, mbd); + } + + /** + * Obtain a reference for early access to the specified bean, + * typically for the purpose of resolving a circular reference. + * @param beanName the name of the bean (for error handling purposes) + * @param mbd the merged bean definition for the bean + * @param bean the raw bean instance + * @return the object to expose as bean reference + */ + protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) { + Object exposedObject = bean; + if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { + for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) { + BeanPostProcessor bp = (BeanPostProcessor) it.next(); + if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { + SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; + exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName); + } + } + } + return exposedObject; + } + + + //--------------------------------------------------------------------- + // Implementation methods + //--------------------------------------------------------------------- + + /** + * Obtain a "shortcut" singleton FactoryBean instance to use for a + * getObjectType() call, without full initialization + * of the FactoryBean. + * @param beanName the name of the bean + * @param mbd the bean definition for the bean + * @return the FactoryBean instance, or null to indicate + * that we couldn't obtain a shortcut FactoryBean instance + */ + private FactoryBean getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) { + synchronized (getSingletonMutex()) { + BeanWrapper bw = (BeanWrapper) this.factoryBeanInstanceCache.get(beanName); + if (bw != null) { + return (FactoryBean) bw.getWrappedInstance(); + } + if (isSingletonCurrentlyInCreation(beanName)) { + return null; + } + Object instance = null; + try { + // Mark this bean as currently in creation, even if just partially. + beforeSingletonCreation(beanName); + // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. + instance = resolveBeforeInstantiation(beanName, mbd); + if (instance == null) { + bw = createBeanInstance(beanName, mbd, null); + instance = bw.getWrappedInstance(); + } + } + finally { + // Finished partial creation of this bean. + afterSingletonCreation(beanName); + } + FactoryBean fb = getFactoryBean(beanName, instance); + if (bw != null) { + this.factoryBeanInstanceCache.put(beanName, bw); + } + return fb; + } + } + + /** + * Obtain a "shortcut" non-singleton FactoryBean instance to use for a + * getObjectType() call, without full initialization + * of the FactoryBean. + * @param beanName the name of the bean + * @param mbd the bean definition for the bean + * @return the FactoryBean instance, or null to indicate + * that we couldn't obtain a shortcut FactoryBean instance + */ + private FactoryBean getNonSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) { + if (isPrototypeCurrentlyInCreation(beanName)) { + return null; + } + Object instance = null; + try { + // Mark this bean as currently in creation, even if just partially. + beforePrototypeCreation(beanName); + // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. + instance = resolveBeforeInstantiation(beanName, mbd); + if (instance == null) { + BeanWrapper bw = createBeanInstance(beanName, mbd, null); + instance = bw.getWrappedInstance(); + } + } + finally { + // Finished partial creation of this bean. + afterPrototypeCreation(beanName); + } + return getFactoryBean(beanName, instance); + } + + /** + * Apply MergedBeanDefinitionPostProcessors to the specified bean definition, + * invoking their postProcessMergedBeanDefinition methods. + * @param mbd the merged bean definition for the bean + * @param beanType the actual type of the managed bean instance + * @param beanName the name of the bean + * @throws BeansException if any post-processing failed + * @see MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition + */ + protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class beanType, String beanName) + throws BeansException { + + for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) { + BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); + if (beanProcessor instanceof MergedBeanDefinitionPostProcessor) { + MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) beanProcessor; + bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName); + } + } + } + + /** + * Apply before-instantiation post-processors, resolving whether there is a + * before-instantiation shortcut for the specified bean. + * @param beanName the name of the bean + * @param mbd the bean definition for the bean + * @return the shortcut-determined bean instance, or null if none + */ + protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) { + Object bean = null; + if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { + // Make sure bean class is actually resolved at this point. + if (mbd.hasBeanClass() && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { + bean = applyBeanPostProcessorsBeforeInstantiation(mbd.getBeanClass(), beanName); + if (bean != null) { + bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); + } + } + mbd.beforeInstantiationResolved = Boolean.valueOf(bean != null); + } + return bean; + } + + /** + * Apply InstantiationAwareBeanPostProcessors to the specified bean definition + * (by class and name), invoking their postProcessBeforeInstantiation methods. + *

    Any returned object will be used as the bean instead of actually instantiating + * the target bean. A null return value from the post-processor will + * result in the target bean being instantiated. + * @param beanClass the class of the bean to be instantiated + * @param beanName the name of the bean + * @return the bean object to use instead of a default instance of the target bean, or null + * @throws BeansException if any post-processing failed + * @see InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation + */ + protected Object applyBeanPostProcessorsBeforeInstantiation(Class beanClass, String beanName) + throws BeansException { + + for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) { + BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); + if (beanProcessor instanceof InstantiationAwareBeanPostProcessor) { + InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) beanProcessor; + Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName); + if (result != null) { + return result; + } + } + } + return null; + } + + /** + * Create a new instance for the specified bean, using an appropriate instantiation strategy: + * factory method, constructor autowiring, or simple instantiation. + * @param beanName the name of the bean + * @param mbd the bean definition for the bean + * @param args arguments to use if creating a prototype using explicit arguments to a + * static factory method. It is invalid to use a non-null args value in any other case. + * @return BeanWrapper for the new instance + * @see #instantiateUsingFactoryMethod + * @see #autowireConstructor + * @see #instantiateBean + */ + protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) { + // Make sure bean class is actually resolved at this point. + Class beanClass = resolveBeanClass(mbd, beanName); + + if (mbd.getFactoryMethodName() != null) { + return instantiateUsingFactoryMethod(beanName, mbd, args); + } + + // Shortcut when re-creating the same bean... + if (mbd.resolvedConstructorOrFactoryMethod != null) { + if (mbd.constructorArgumentsResolved) { + return autowireConstructor(beanName, mbd, null, args); + } + else { + return instantiateBean(beanName, mbd); + } + } + + // Need to determine the constructor... + Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); + if (ctors != null || + mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR || + mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { + return autowireConstructor(beanName, mbd, ctors, args); + } + + // No special handling: simply use no-arg constructor. + return instantiateBean(beanName, mbd); + } + + /** + * Determine candidate constructors to use for the given bean, checking all registered + * {@link SmartInstantiationAwareBeanPostProcessor SmartInstantiationAwareBeanPostProcessors}. + * @param beanClass the raw class of the bean + * @param beanName the name of the bean + * @return the candidate constructors, or null if none specified + * @throws org.springframework.beans.BeansException in case of errors + * @see org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors + */ + protected Constructor[] determineConstructorsFromBeanPostProcessors(Class beanClass, String beanName) + throws BeansException { + + if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) { + for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) { + BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); + if (beanProcessor instanceof SmartInstantiationAwareBeanPostProcessor) { + SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) beanProcessor; + Constructor[] ctors = ibp.determineCandidateConstructors(beanClass, beanName); + if (ctors != null) { + return ctors; + } + } + } + } + return null; + } + + /** + * Instantiate the given bean using its default constructor. + * @param beanName the name of the bean + * @param mbd the bean definition for the bean + * @return BeanWrapper for the new instance + */ + protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) { + try { + Object beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this); + BeanWrapper bw = new BeanWrapperImpl(beanInstance); + initBeanWrapper(bw); + return bw; + } + catch (Throwable ex) { + throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex); + } + } + + /** + * Instantiate the bean using a named factory method. The method may be static, if the + * mbd parameter specifies a class, rather than a factoryBean, or an instance variable + * on a factory object itself configured using Dependency Injection. + * @param beanName the name of the bean + * @param mbd the bean definition for the bean + * @param explicitArgs argument values passed in programmatically via the getBean method, + * or null if none (-> use constructor argument values from bean definition) + * @return BeanWrapper for the new instance + * @see #getBean(String, Object[]) + */ + protected BeanWrapper instantiateUsingFactoryMethod( + String beanName, RootBeanDefinition mbd, Object[] explicitArgs) { + + ConstructorResolver constructorResolver = + new ConstructorResolver(this, this, getInstantiationStrategy(), getCustomTypeConverter()); + return constructorResolver.instantiateUsingFactoryMethod(beanName, mbd, explicitArgs); + } + + /** + * "autowire constructor" (with constructor arguments by type) behavior. + * Also applied if explicit constructor argument values are specified, + * matching all remaining arguments with beans from the bean factory. + *

    This corresponds to constructor injection: In this mode, a Spring + * bean factory is able to host components that expect constructor-based + * dependency resolution. + * @param beanName the name of the bean + * @param mbd the bean definition for the bean + * @param ctors the chosen candidate constructors + * @param explicitArgs argument values passed in programmatically via the getBean method, + * or null if none (-> use constructor argument values from bean definition) + * @return BeanWrapper for the new instance + */ + protected BeanWrapper autowireConstructor( + String beanName, RootBeanDefinition mbd, Constructor[] ctors, Object[] explicitArgs) { + + ConstructorResolver constructorResolver = + new ConstructorResolver(this, this, getInstantiationStrategy(), getCustomTypeConverter()); + return constructorResolver.autowireConstructor(beanName, mbd, ctors, explicitArgs); + } + + /** + * Populate the bean instance in the given BeanWrapper with the property values + * from the bean definition. + * @param beanName the name of the bean + * @param mbd the bean definition for the bean + * @param bw BeanWrapper with bean instance + */ + protected void populateBean(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw) { + PropertyValues pvs = mbd.getPropertyValues(); + + if (bw == null) { + if (!pvs.isEmpty()) { + throw new BeanCreationException( + mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); + } + else { + // Skip property population phase for null instance. + return; + } + } + + // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the + // state of the bean before properties are set. This can be used, for example, + // to support styles of field injection. + boolean continueWithPropertyPopulation = true; + + if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { + for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) { + BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); + if (beanProcessor instanceof InstantiationAwareBeanPostProcessor) { + InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) beanProcessor; + if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { + continueWithPropertyPopulation = false; + break; + } + } + } + } + + if (!continueWithPropertyPopulation) { + return; + } + + if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME || + mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { + MutablePropertyValues newPvs = new MutablePropertyValues(pvs); + + // Add property values based on autowire by name if applicable. + if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) { + autowireByName(beanName, mbd, bw, newPvs); + } + + // Add property values based on autowire by type if applicable. + if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { + autowireByType(beanName, mbd, bw, newPvs); + } + + pvs = newPvs; + } + + boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); + boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE); + + if (hasInstAwareBpps || needsDepCheck) { + PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw); + if (hasInstAwareBpps) { + for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) { + BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next(); + if (beanProcessor instanceof InstantiationAwareBeanPostProcessor) { + InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) beanProcessor; + pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); + if (pvs == null) { + return; + } + } + } + } + if (needsDepCheck) { + checkDependencies(beanName, mbd, filteredPds, pvs); + } + } + + applyPropertyValues(beanName, mbd, bw, pvs); + } + + /** + * Fill in any missing property values with references to + * other beans in this factory if autowire is set to "byName". + * @param beanName the name of the bean we're wiring up. + * Useful for debugging messages; not used functionally. + * @param mbd bean definition to update through autowiring + * @param bw BeanWrapper from which we can obtain information about the bean + * @param pvs the PropertyValues to register wired objects with + */ + protected void autowireByName( + String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { + + String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); + for (int i = 0; i < propertyNames.length; i++) { + String propertyName = propertyNames[i]; + if (containsBean(propertyName)) { + Object bean = getBean(propertyName); + pvs.addPropertyValue(propertyName, bean); + registerDependentBean(propertyName, beanName); + if (logger.isDebugEnabled()) { + logger.debug("Added autowiring by name from bean name '" + beanName + + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); + } + } + else { + if (logger.isTraceEnabled()) { + logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + + "' by name: no matching bean found"); + } + } + } + } + + /** + * Abstract method defining "autowire by type" (bean properties by type) behavior. + *

    This is like PicoContainer default, in which there must be exactly one bean + * of the property type in the bean factory. This makes bean factories simple to + * configure for small namespaces, but doesn't work as well as standard Spring + * behavior for bigger applications. + * @param beanName the name of the bean to autowire by type + * @param mbd the merged bean definition to update through autowiring + * @param bw BeanWrapper from which we can obtain information about the bean + * @param pvs the PropertyValues to register wired objects with + */ + protected void autowireByType( + String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { + + TypeConverter converter = getCustomTypeConverter(); + if (converter == null) { + converter = bw; + } + + Set autowiredBeanNames = new LinkedHashSet(4); + String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); + for (int i = 0; i < propertyNames.length; i++) { + String propertyName = propertyNames[i]; + try { + PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); + MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); + // Do not allow eager init for type matching in case of a prioritized post-processor. + boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass()); + DependencyDescriptor desc = new DependencyDescriptor(methodParam, false, eager); + + Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter); + if (autowiredArgument != null) { + pvs.addPropertyValue(propertyName, autowiredArgument); + } + for (Iterator it = autowiredBeanNames.iterator(); it.hasNext();) { + String autowiredBeanName = (String) it.next(); + registerDependentBean(autowiredBeanName, beanName); + if (logger.isDebugEnabled()) { + logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" + + propertyName + "' to bean named '" + autowiredBeanName + "'"); + } + } + autowiredBeanNames.clear(); + } + catch (BeansException ex) { + throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex); + } + } + } + + + /** + * Return an array of non-simple bean properties that are unsatisfied. + * These are probably unsatisfied references to other beans in the + * factory. Does not include simple properties like primitives or Strings. + * @param mbd the merged bean definition the bean was created with + * @param bw the BeanWrapper the bean was created with + * @return an array of bean property names + * @see org.springframework.beans.BeanUtils#isSimpleProperty + */ + protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) { + Set result = new TreeSet(); + PropertyValues pvs = mbd.getPropertyValues(); + PropertyDescriptor[] pds = bw.getPropertyDescriptors(); + for (int i = 0; i < pds.length; i++) { + if (pds[i].getWriteMethod() != null && !isExcludedFromDependencyCheck(pds[i]) && + !pvs.contains(pds[i].getName()) && !BeanUtils.isSimpleProperty(pds[i].getPropertyType())) { + result.add(pds[i].getName()); + } + } + return StringUtils.toStringArray(result); + } + + /** + * Extract a filtered set of PropertyDescriptors from the given BeanWrapper, + * excluding ignored dependency types or properties defined on ignored + * dependency interfaces. + * @param bw the BeanWrapper the bean was created with + * @return the filtered PropertyDescriptors + * @see #isExcludedFromDependencyCheck + */ + protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw) { + synchronized (this.filteredPropertyDescriptorsCache) { + PropertyDescriptor[] filtered = (PropertyDescriptor[]) + this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass()); + if (filtered == null) { + List pds = new LinkedList(Arrays.asList(bw.getPropertyDescriptors())); + for (Iterator it = pds.iterator(); it.hasNext();) { + PropertyDescriptor pd = (PropertyDescriptor) it.next(); + if (isExcludedFromDependencyCheck(pd)) { + it.remove(); + } + } + filtered = (PropertyDescriptor[]) pds.toArray(new PropertyDescriptor[pds.size()]); + this.filteredPropertyDescriptorsCache.put(bw.getWrappedClass(), filtered); + } + return filtered; + } + } + + /** + * Determine whether the given bean property is excluded from dependency checks. + *

    This implementation excludes properties defined by CGLIB and + * properties whose type matches an ignored dependency type or which + * are defined by an ignored dependency interface. + * @param pd the PropertyDescriptor of the bean property + * @return whether the bean property is excluded + * @see #ignoreDependencyType(Class) + * @see #ignoreDependencyInterface(Class) + */ + protected boolean isExcludedFromDependencyCheck(PropertyDescriptor pd) { + return (AutowireUtils.isExcludedFromDependencyCheck(pd) || + this.ignoredDependencyTypes.contains(pd.getPropertyType()) || + AutowireUtils.isSetterDefinedInInterface(pd, this.ignoredDependencyInterfaces)); + } + + /** + * Perform a dependency check that all properties exposed have been set, + * if desired. Dependency checks can be objects (collaborating beans), + * simple (primitives and String), or all (both). + * @param beanName the name of the bean + * @param mbd the merged bean definition the bean was created with + * @param pds the relevant property descriptors for the target bean + * @param pvs the property values to be applied to the bean + * @see #isExcludedFromDependencyCheck(java.beans.PropertyDescriptor) + */ + protected void checkDependencies( + String beanName, AbstractBeanDefinition mbd, PropertyDescriptor[] pds, PropertyValues pvs) + throws UnsatisfiedDependencyException { + + int dependencyCheck = mbd.getDependencyCheck(); + for (int i = 0; i < pds.length; i++) { + if (pds[i].getWriteMethod() != null && !pvs.contains(pds[i].getName())) { + boolean isSimple = BeanUtils.isSimpleProperty(pds[i].getPropertyType()); + boolean unsatisfied = (dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_ALL) || + (isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_SIMPLE) || + (!isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS); + if (unsatisfied) { + throw new UnsatisfiedDependencyException( + mbd.getResourceDescription(), beanName, pds[i].getName(), + "Set this property value or disable dependency checking for this bean."); + } + } + } + } + + /** + * Apply the given property values, resolving any runtime references + * to other beans in this bean factory. Must use deep copy, so we + * don't permanently modify this property. + * @param beanName the bean name passed for better exception information + * @param mbd the merged bean definition + * @param bw the BeanWrapper wrapping the target object + * @param pvs the new property values + */ + protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) { + if (pvs == null || pvs.isEmpty()) { + return; + } + + MutablePropertyValues mpvs = null; + List original = null; + + if (pvs instanceof MutablePropertyValues) { + mpvs = (MutablePropertyValues) pvs; + if (mpvs.isConverted()) { + // Shortcut: use the pre-converted values as-is. + try { + bw.setPropertyValues(mpvs); + return; + } + catch (BeansException ex) { + throw new BeanCreationException( + mbd.getResourceDescription(), beanName, "Error setting property values", ex); + } + } + original = mpvs.getPropertyValueList(); + } + else { + original = Arrays.asList(pvs.getPropertyValues()); + } + + TypeConverter converter = getCustomTypeConverter(); + if (converter == null) { + converter = bw; + } + BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter); + + // Create a deep copy, resolving any references for values. + List deepCopy = new ArrayList(original.size()); + boolean resolveNecessary = false; + for (Iterator it = original.iterator(); it.hasNext();) { + PropertyValue pv = (PropertyValue) it.next(); + if (pv.isConverted()) { + deepCopy.add(pv); + } + else { + String propertyName = pv.getName(); + Object originalValue = pv.getValue(); + Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue); + Object convertedValue = resolvedValue; + boolean convertible = bw.isWritableProperty(propertyName) && + !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName); + if (convertible) { + convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter); + } + // Possibly store converted value in merged bean definition, + // in order to avoid re-conversion for every created bean instance. + if (resolvedValue == originalValue) { + if (convertible) { + pv.setConvertedValue(convertedValue); + } + deepCopy.add(pv); + } + else if (originalValue instanceof TypedStringValue && convertible) { + pv.setConvertedValue(convertedValue); + deepCopy.add(pv); + } + else { + resolveNecessary = true; + deepCopy.add(new PropertyValue(pv, convertedValue)); + } + } + } + if (mpvs != null && !resolveNecessary) { + mpvs.setConverted(); + } + + // Set our (possibly massaged) deep copy. + try { + bw.setPropertyValues(new MutablePropertyValues(deepCopy)); + } + catch (BeansException ex) { + throw new BeanCreationException( + mbd.getResourceDescription(), beanName, "Error setting property values", ex); + } + } + + /** + * Convert the given value for the specified target property. + */ + private Object convertForProperty(Object value, String propertyName, BeanWrapper bw, TypeConverter converter) { + if (converter instanceof BeanWrapperImpl) { + return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName); + } + else { + PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); + MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); + return converter.convertIfNecessary(value, pd.getPropertyType(), methodParam); + } + } + + + /** + * Initialize the given bean instance, applying factory callbacks + * as well as init methods and bean post processors. + *

    Called from {@link #createBean} for traditionally defined beans, + * and from {@link #initializeBean} for existing bean instances. + * @param beanName the bean name in the factory (for debugging purposes) + * @param bean the new bean instance we may need to initialize + * @param mbd the bean definition that the bean was created with + * (can also be null, if given an existing bean instance) + * @return the initialized bean instance (potentially wrapped) + * @see BeanNameAware + * @see BeanClassLoaderAware + * @see BeanFactoryAware + * @see #applyBeanPostProcessorsBeforeInitialization + * @see #invokeInitMethods + * @see #applyBeanPostProcessorsAfterInitialization + */ + protected Object initializeBean(String beanName, Object bean, RootBeanDefinition mbd) { + if (bean instanceof BeanNameAware) { + ((BeanNameAware) bean).setBeanName(beanName); + } + + if (bean instanceof BeanClassLoaderAware) { + ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader()); + } + + if (bean instanceof BeanFactoryAware) { + ((BeanFactoryAware) bean).setBeanFactory(this); + } + + Object wrappedBean = bean; + if (mbd == null || !mbd.isSynthetic()) { + wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); + } + + try { + invokeInitMethods(beanName, wrappedBean, mbd); + } + catch (Throwable ex) { + throw new BeanCreationException( + (mbd != null ? mbd.getResourceDescription() : null), + beanName, "Invocation of init method failed", ex); + } + + if (mbd == null || !mbd.isSynthetic()) { + wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); + } + return wrappedBean; + } + + /** + * Give a bean a chance to react now all its properties are set, + * and a chance to know about its owning bean factory (this object). + * This means checking whether the bean implements InitializingBean or defines + * a custom init method, and invoking the necessary callback(s) if it does. + * @param beanName the bean name in the factory (for debugging purposes) + * @param bean the new bean instance we may need to initialize + * @param mbd the merged bean definition that the bean was created with + * (can also be null, if given an existing bean instance) + * @throws Throwable if thrown by init methods or by the invocation process + * @see #invokeCustomInitMethod + */ + protected void invokeInitMethods(String beanName, Object bean, RootBeanDefinition mbd) + throws Throwable { + + boolean isInitializingBean = (bean instanceof InitializingBean); + if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { + if (logger.isDebugEnabled()) { + logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); + } + ((InitializingBean) bean).afterPropertiesSet(); + } + + String initMethodName = (mbd != null ? mbd.getInitMethodName() : null); + if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) && + !mbd.isExternallyManagedInitMethod(initMethodName)) { + invokeCustomInitMethod(beanName, bean, initMethodName, mbd.isEnforceInitMethod()); + } + } + + /** + * Invoke the specified custom init method on the given bean. + * Called by invokeInitMethods. + *

    Can be overridden in subclasses for custom resolution of init + * methods with arguments. + * @param beanName the bean name in the factory (for debugging purposes) + * @param bean the new bean instance we may need to initialize + * @param initMethodName the name of the custom init method + * @param enforceInitMethod indicates whether the defined init method needs to exist + * @see #invokeInitMethods + */ + protected void invokeCustomInitMethod( + String beanName, Object bean, String initMethodName, boolean enforceInitMethod) throws Throwable { + + Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null); + if (initMethod == null) { + if (enforceInitMethod) { + throw new NoSuchMethodException("Couldn't find an init method named '" + initMethodName + + "' on bean with name '" + beanName + "'"); + } + else { + if (logger.isDebugEnabled()) { + logger.debug("No default init method named '" + initMethodName + + "' found on bean with name '" + beanName + "'"); + } + // Ignore non-existent default lifecycle methods. + return; + } + } + + if (logger.isDebugEnabled()) { + logger.debug("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'"); + } + ReflectionUtils.makeAccessible(initMethod); + try { + initMethod.invoke(bean, (Object[]) null); + } + catch (InvocationTargetException ex) { + throw ex.getTargetException(); + } + } + + + /** + * Applies the postProcessAfterInitialization callback of all + * registered BeanPostProcessors, giving them a chance to post-process the + * object obtained from FactoryBeans (for example, to auto-proxy them). + * @see #applyBeanPostProcessorsAfterInitialization + */ + protected Object postProcessObjectFromFactoryBean(Object object, String beanName) { + return applyBeanPostProcessorsAfterInitialization(object, beanName); + } + + /** + * Overridden to clear FactoryBean instance cache as well. + */ + protected void removeSingleton(String beanName) { + super.removeSingleton(beanName); + this.factoryBeanInstanceCache.remove(beanName); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/AbstractBeanDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/AbstractBeanDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/AbstractBeanDefinition.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,1000 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.lang.reflect.Constructor; +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.springframework.beans.BeanMetadataAttributeAccessor; +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConstructorArgumentValues; +import org.springframework.core.io.DescriptiveResource; +import org.springframework.core.io.Resource; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; + +/** + * Base class for concrete, full-fledged + * {@link org.springframework.beans.factory.config.BeanDefinition} classes, + * factoring out common properties of {@link RootBeanDefinition} and + * {@link ChildBeanDefinition}. + * + *

    The autowire constants match the ones defined in the + * {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory} + * interface. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + * @author Mark Fisher + * @see RootBeanDefinition + * @see ChildBeanDefinition + */ +public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccessor + implements BeanDefinition, Cloneable { + + /** + * Constant that indicates no autowiring at all. + * @see #setAutowireMode + */ + public static final int AUTOWIRE_NO = AutowireCapableBeanFactory.AUTOWIRE_NO; + + /** + * Constant that indicates autowiring bean properties by name. + * @see #setAutowireMode + */ + public static final int AUTOWIRE_BY_NAME = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; + + /** + * Constant that indicates autowiring bean properties by type. + * @see #setAutowireMode + */ + public static final int AUTOWIRE_BY_TYPE = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE; + + /** + * Constant that indicates autowiring a constructor. + * @see #setAutowireMode + */ + public static final int AUTOWIRE_CONSTRUCTOR = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR; + + /** + * Constant that indicates determining an appropriate autowire strategy + * through introspection of the bean class. + * @see #setAutowireMode + */ + public static final int AUTOWIRE_AUTODETECT = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT; + + + /** + * Constant that indicates no dependency check at all. + * @see #setDependencyCheck + */ + public static final int DEPENDENCY_CHECK_NONE = 0; + + /** + * Constant that indicates dependency checking for object references. + * @see #setDependencyCheck + */ + public static final int DEPENDENCY_CHECK_OBJECTS = 1; + + /** + * Constant that indicates dependency checking for "simple" properties. + * @see #setDependencyCheck + * @see org.springframework.beans.BeanUtils#isSimpleProperty + */ + public static final int DEPENDENCY_CHECK_SIMPLE = 2; + + /** + * Constant that indicates dependency checking for all properties + * (object references as well as "simple" properties). + * @see #setDependencyCheck + */ + public static final int DEPENDENCY_CHECK_ALL = 3; + + + private volatile Object beanClass; + + private String scope = SCOPE_SINGLETON; + + private boolean singleton = true; + + private boolean prototype = false; + + private boolean abstractFlag = false; + + private boolean lazyInit = false; + + private int autowireMode = AUTOWIRE_NO; + + private int dependencyCheck = DEPENDENCY_CHECK_NONE; + + private String[] dependsOn; + + private boolean autowireCandidate = true; + + private final Map qualifiers = new LinkedHashMap(); + + private boolean primary = false; + + private ConstructorArgumentValues constructorArgumentValues; + + private MutablePropertyValues propertyValues; + + private MethodOverrides methodOverrides = new MethodOverrides(); + + private String factoryBeanName; + + private String factoryMethodName; + + private String initMethodName; + + private String destroyMethodName; + + private boolean enforceInitMethod = true; + + private boolean enforceDestroyMethod = true; + + private boolean synthetic = false; + + private int role = BeanDefinition.ROLE_APPLICATION; + + private String description; + + private Resource resource; + + + /** + * Create a new AbstractBeanDefinition with default settings. + */ + protected AbstractBeanDefinition() { + this(null, null); + } + + /** + * Create a new AbstractBeanDefinition with the given + * constructor argument values and property values. + */ + protected AbstractBeanDefinition(ConstructorArgumentValues cargs, MutablePropertyValues pvs) { + setConstructorArgumentValues(cargs); + setPropertyValues(pvs); + } + + /** + * Create a new AbstractBeanDefinition as deep copy of the given + * bean definition. + * @param original the original bean definition to copy from + * @deprecated since Spring 2.5, in favor of {@link #AbstractBeanDefinition(BeanDefinition)} + */ + protected AbstractBeanDefinition(AbstractBeanDefinition original) { + this((BeanDefinition) original); + } + + /** + * Create a new AbstractBeanDefinition as deep copy of the given + * bean definition. + * @param original the original bean definition to copy from + */ + protected AbstractBeanDefinition(BeanDefinition original) { + setParentName(original.getParentName()); + setBeanClassName(original.getBeanClassName()); + setFactoryBeanName(original.getFactoryBeanName()); + setFactoryMethodName(original.getFactoryMethodName()); + setScope(original.getScope()); + setAbstract(original.isAbstract()); + setLazyInit(original.isLazyInit()); + setRole(original.getRole()); + setConstructorArgumentValues(new ConstructorArgumentValues(original.getConstructorArgumentValues())); + setPropertyValues(new MutablePropertyValues(original.getPropertyValues())); + setSource(original.getSource()); + copyAttributesFrom(original); + + if (original instanceof AbstractBeanDefinition) { + AbstractBeanDefinition originalAbd = (AbstractBeanDefinition) original; + if (originalAbd.hasBeanClass()) { + setBeanClass(originalAbd.getBeanClass()); + } + setAutowireMode(originalAbd.getAutowireMode()); + setDependencyCheck(originalAbd.getDependencyCheck()); + setDependsOn(originalAbd.getDependsOn()); + setAutowireCandidate(originalAbd.isAutowireCandidate()); + copyQualifiersFrom(originalAbd); + setPrimary(originalAbd.isPrimary()); + setInitMethodName(originalAbd.getInitMethodName()); + setEnforceInitMethod(originalAbd.isEnforceInitMethod()); + setDestroyMethodName(originalAbd.getDestroyMethodName()); + setEnforceDestroyMethod(originalAbd.isEnforceDestroyMethod()); + setMethodOverrides(new MethodOverrides(originalAbd.getMethodOverrides())); + setSynthetic(originalAbd.isSynthetic()); + setResource(originalAbd.getResource()); + } + else { + setResourceDescription(original.getResourceDescription()); + } + } + + + /** + * Override settings in this bean definition (assumably a copied parent + * from a parent-child inheritance relationship) from the given bean + * definition (assumably the child). + * @deprecated since Spring 2.5, in favor of {@link #overrideFrom(BeanDefinition)} + */ + public void overrideFrom(AbstractBeanDefinition other) { + overrideFrom((BeanDefinition) other); + } + + /** + * Override settings in this bean definition (assumably a copied parent + * from a parent-child inheritance relationship) from the given bean + * definition (assumably the child). + *

    + */ + public void overrideFrom(BeanDefinition other) { + if (other.getBeanClassName() != null) { + setBeanClassName(other.getBeanClassName()); + } + if (other.getFactoryBeanName() != null) { + setFactoryBeanName(other.getFactoryBeanName()); + } + if (other.getFactoryMethodName() != null) { + setFactoryMethodName(other.getFactoryMethodName()); + } + setScope(other.getScope()); + setAbstract(other.isAbstract()); + setLazyInit(other.isLazyInit()); + setRole(other.getRole()); + getConstructorArgumentValues().addArgumentValues(other.getConstructorArgumentValues()); + getPropertyValues().addPropertyValues(other.getPropertyValues()); + setSource(other.getSource()); + copyAttributesFrom(other); + + if (other instanceof AbstractBeanDefinition) { + AbstractBeanDefinition otherAbd = (AbstractBeanDefinition) other; + if (otherAbd.hasBeanClass()) { + setBeanClass(otherAbd.getBeanClass()); + } + setAutowireCandidate(otherAbd.isAutowireCandidate()); + setAutowireMode(otherAbd.getAutowireMode()); + copyQualifiersFrom(otherAbd); + setPrimary(otherAbd.isPrimary()); + setDependencyCheck(otherAbd.getDependencyCheck()); + setDependsOn(otherAbd.getDependsOn()); + if (otherAbd.getInitMethodName() != null) { + setInitMethodName(otherAbd.getInitMethodName()); + setEnforceInitMethod(otherAbd.isEnforceInitMethod()); + } + if (otherAbd.getDestroyMethodName() != null) { + setDestroyMethodName(otherAbd.getDestroyMethodName()); + setEnforceDestroyMethod(otherAbd.isEnforceDestroyMethod()); + } + getMethodOverrides().addOverrides(otherAbd.getMethodOverrides()); + setSynthetic(otherAbd.isSynthetic()); + setResource(otherAbd.getResource()); + } + else { + setResourceDescription(other.getResourceDescription()); + } + } + + /** + * Apply the provided default values to this bean. + * @param defaults the defaults to apply + */ + public void applyDefaults(BeanDefinitionDefaults defaults) { + setLazyInit(defaults.isLazyInit()); + setDependencyCheck(defaults.getDependencyCheck()); + setAutowireMode(defaults.getAutowireMode()); + setInitMethodName(defaults.getInitMethodName()); + setEnforceInitMethod(false); + setDestroyMethodName(defaults.getDestroyMethodName()); + setEnforceDestroyMethod(false); + } + + + /** + * Return whether this definition specifies a bean class. + */ + public boolean hasBeanClass() { + return (this.beanClass instanceof Class); + } + + /** + * Specify the class for this bean. + */ + public void setBeanClass(Class beanClass) { + this.beanClass = beanClass; + } + + /** + * Return the class of the wrapped bean, if already resolved. + * @return the bean class, or null if none defined + * @throws IllegalStateException if the bean definition does not define a bean class, + * or a specified bean class name has not been resolved into an actual Class + */ + public Class getBeanClass() throws IllegalStateException { + Object beanClassObject = this.beanClass; + if (beanClassObject == null) { + throw new IllegalStateException("No bean class specified on bean definition"); + } + if (!(beanClassObject instanceof Class)) { + throw new IllegalStateException( + "Bean class name [" + beanClassObject + "] has not been resolved into an actual Class"); + } + return (Class) beanClassObject; + } + + public void setBeanClassName(String beanClassName) { + this.beanClass = beanClassName; + } + + public String getBeanClassName() { + Object beanClassObject = this.beanClass; + if (beanClassObject instanceof Class) { + return ((Class) beanClassObject).getName(); + } + else { + return (String) beanClassObject; + } + } + + /** + * Determine the class of the wrapped bean, resolving it from a + * specified class name if necessary. Will also reload a specified + * Class from its name when called with the bean class already resolved. + * @param classLoader the ClassLoader to use for resolving a (potential) class name + * @return the resolved bean class + * @throws ClassNotFoundException if the class name could be resolved + */ + public Class resolveBeanClass(ClassLoader classLoader) throws ClassNotFoundException { + String className = getBeanClassName(); + if (className == null) { + return null; + } + Class resolvedClass = ClassUtils.forName(className, classLoader); + this.beanClass = resolvedClass; + return resolvedClass; + } + + + /** + * Set the name of the target scope for the bean. + *

    Default is "singleton"; the out-of-the-box alternative is "prototype". + * Extended bean factories might support further scopes. + * @see #SCOPE_SINGLETON + * @see #SCOPE_PROTOTYPE + */ + public void setScope(String scope) { + Assert.notNull(scope, "Scope must not be null"); + this.scope = scope; + this.singleton = SCOPE_SINGLETON.equals(scope); + this.prototype = SCOPE_PROTOTYPE.equals(scope); + } + + /** + * Return the name of the target scope for the bean. + */ + public String getScope() { + return this.scope; + } + + /** + * Set if this a Singleton, with a single, shared instance returned + * on all calls. In case of "false", the BeanFactory will apply the Prototype + * design pattern, with each caller requesting an instance getting an independent + * instance. How this is exactly defined will depend on the BeanFactory. + *

    "Singletons" are the commoner type, so the default is "true". + * Note that as of Spring 2.0, this flag is just an alternative way to + * specify scope="singleton" or scope="prototype". + * @deprecated since Spring 2.5, in favor of {@link #setScope} + * @see #setScope + * @see #SCOPE_SINGLETON + * @see #SCOPE_PROTOTYPE + */ + public void setSingleton(boolean singleton) { + this.scope = (singleton ? SCOPE_SINGLETON : SCOPE_PROTOTYPE); + this.singleton = singleton; + this.prototype = !singleton; + } + + /** + * Return whether this a Singleton, with a single shared instance + * returned from all calls. + * @see #SCOPE_SINGLETON + */ + public boolean isSingleton() { + return this.singleton; + } + + /** + * Return whether this a Prototype, with an independent instance + * returned for each call. + * @see #SCOPE_PROTOTYPE + */ + public boolean isPrototype() { + return this.prototype; + } + + /** + * Set if this bean is "abstract", i.e. not meant to be instantiated itself but + * rather just serving as parent for concrete child bean definitions. + *

    Default is "false". Specify true to tell the bean factory to not try to + * instantiate that particular bean in any case. + */ + public void setAbstract(boolean abstractFlag) { + this.abstractFlag = abstractFlag; + } + + /** + * Return whether this bean is "abstract", i.e. not meant to be instantiated + * itself but rather just serving as parent for concrete child bean definitions. + */ + public boolean isAbstract() { + return this.abstractFlag; + } + + /** + * Set whether this bean should be lazily initialized. + *

    If false, the bean will get instantiated on startup by bean + * factories that perform eager initialization of singletons. + */ + public void setLazyInit(boolean lazyInit) { + this.lazyInit = lazyInit; + } + + /** + * Return whether this bean should be lazily initialized, i.e. not + * eagerly instantiated on startup. Only applicable to a singleton bean. + */ + public boolean isLazyInit() { + return this.lazyInit; + } + + + /** + * Set the autowire mode. This determines whether any automagical detection + * and setting of bean references will happen. Default is AUTOWIRE_NO, + * which means there's no autowire. + * @param autowireMode the autowire mode to set. + * Must be one of the constants defined in this class. + * @see #AUTOWIRE_NO + * @see #AUTOWIRE_BY_NAME + * @see #AUTOWIRE_BY_TYPE + * @see #AUTOWIRE_CONSTRUCTOR + * @see #AUTOWIRE_AUTODETECT + */ + public void setAutowireMode(int autowireMode) { + this.autowireMode = autowireMode; + } + + /** + * Return the autowire mode as specified in the bean definition. + */ + public int getAutowireMode() { + return this.autowireMode; + } + + /** + * Return the resolved autowire code, + * (resolving AUTOWIRE_AUTODETECT to AUTOWIRE_CONSTRUCTOR or AUTOWIRE_BY_TYPE). + * @see #AUTOWIRE_AUTODETECT + * @see #AUTOWIRE_CONSTRUCTOR + * @see #AUTOWIRE_BY_TYPE + */ + public int getResolvedAutowireMode() { + if (this.autowireMode == AUTOWIRE_AUTODETECT) { + // Work out whether to apply setter autowiring or constructor autowiring. + // If it has a no-arg constructor it's deemed to be setter autowiring, + // otherwise we'll try constructor autowiring. + Constructor[] constructors = getBeanClass().getConstructors(); + for (int i = 0; i < constructors.length; i++) { + if (constructors[i].getParameterTypes().length == 0) { + return AUTOWIRE_BY_TYPE; + } + } + return AUTOWIRE_CONSTRUCTOR; + } + else { + return this.autowireMode; + } + } + + /** + * Set the dependency check code. + * @param dependencyCheck the code to set. + * Must be one of the four constants defined in this class. + * @see #DEPENDENCY_CHECK_NONE + * @see #DEPENDENCY_CHECK_OBJECTS + * @see #DEPENDENCY_CHECK_SIMPLE + * @see #DEPENDENCY_CHECK_ALL + */ + public void setDependencyCheck(int dependencyCheck) { + this.dependencyCheck = dependencyCheck; + } + + /** + * Return the dependency check code. + */ + public int getDependencyCheck() { + return this.dependencyCheck; + } + + /** + * Set the names of the beans that this bean depends on being initialized. + * The bean factory will guarantee that these beans get initialized before. + *

    Note that dependencies are normally expressed through bean properties or + * constructor arguments. This property should just be necessary for other kinds + * of dependencies like statics (*ugh*) or database preparation on startup. + */ + public void setDependsOn(String[] dependsOn) { + this.dependsOn = dependsOn; + } + + /** + * Return the bean names that this bean depends on. + */ + public String[] getDependsOn() { + return this.dependsOn; + } + + /** + * Set whether this bean is a candidate for getting autowired into some other bean. + */ + public void setAutowireCandidate(boolean autowireCandidate) { + this.autowireCandidate = autowireCandidate; + } + + /** + * Return whether this bean is a candidate for getting autowired into some other bean. + */ + public boolean isAutowireCandidate() { + return this.autowireCandidate; + } + + /** + * Register a qualifier to be used for autowire candidate resolution, + * keyed by the qualifier's type name. + * @see AutowireCandidateQualifier#getTypeName() + */ + public void addQualifier(AutowireCandidateQualifier qualifier) { + this.qualifiers.put(qualifier.getTypeName(), qualifier); + } + + /** + * Return whether this bean has the specified qualifier. + */ + public boolean hasQualifier(String typeName) { + return this.qualifiers.keySet().contains(typeName); + } + + /** + * Return the qualifier mapped to the provided type name. + */ + public AutowireCandidateQualifier getQualifier(String typeName) { + return (AutowireCandidateQualifier) this.qualifiers.get(typeName); + } + + /** + * Return all registered qualifiers. + * @return the Set of {@link AutowireCandidateQualifier} objects. + */ + public Set getQualifiers() { + return new LinkedHashSet(this.qualifiers.values()); + } + + /** + * Copy the qualifiers from the supplied AbstractBeanDefinition to this bean definition. + * @param source the AbstractBeanDefinition to copy from + */ + protected void copyQualifiersFrom(AbstractBeanDefinition source) { + Assert.notNull(source, "Source must not be null"); + this.qualifiers.putAll(source.qualifiers); + } + + /** + * Set whether this bean is a primary autowire candidate. + * If this value is true for exactly one bean among multiple + * matching candidates, it will serve as a tie-breaker. + */ + public void setPrimary(boolean primary) { + this.primary = primary; + } + + /** + * Return whether this bean is a primary autowire candidate. + * If this value is true for exactly one bean among multiple + * matching candidates, it will serve as a tie-breaker. + */ + public boolean isPrimary() { + return this.primary; + } + + + /** + * Specify constructor argument values for this bean. + */ + public void setConstructorArgumentValues(ConstructorArgumentValues constructorArgumentValues) { + this.constructorArgumentValues = + (constructorArgumentValues != null ? constructorArgumentValues : new ConstructorArgumentValues()); + } + + /** + * Return constructor argument values for this bean (never null). + */ + public ConstructorArgumentValues getConstructorArgumentValues() { + return this.constructorArgumentValues; + } + + /** + * Return if there are constructor argument values defined for this bean. + */ + public boolean hasConstructorArgumentValues() { + return !this.constructorArgumentValues.isEmpty(); + } + + /** + * Specify property values for this bean, if any. + */ + public void setPropertyValues(MutablePropertyValues propertyValues) { + this.propertyValues = (propertyValues != null ? propertyValues : new MutablePropertyValues()); + } + + /** + * Return property values for this bean (never null). + */ + public MutablePropertyValues getPropertyValues() { + return this.propertyValues; + } + + /** + * Specify method overrides for the bean, if any. + */ + public void setMethodOverrides(MethodOverrides methodOverrides) { + this.methodOverrides = (methodOverrides != null ? methodOverrides : new MethodOverrides()); + } + + /** + * Return information about methods to be overridden by the IoC + * container. This will be empty if there are no method overrides. + * Never returns null. + */ + public MethodOverrides getMethodOverrides() { + return this.methodOverrides; + } + + + public void setFactoryBeanName(String factoryBeanName) { + this.factoryBeanName = factoryBeanName; + } + + public String getFactoryBeanName() { + return this.factoryBeanName; + } + + public void setFactoryMethodName(String factoryMethodName) { + this.factoryMethodName = factoryMethodName; + } + + public String getFactoryMethodName() { + return this.factoryMethodName; + } + + /** + * Set the name of the initializer method. The default is null + * in which case there is no initializer method. + */ + public void setInitMethodName(String initMethodName) { + this.initMethodName = initMethodName; + } + + /** + * Return the name of the initializer method. + */ + public String getInitMethodName() { + return this.initMethodName; + } + + /** + * Specify whether or not the configured init method is the default. + * Default value is false. + * @see #setInitMethodName + */ + public void setEnforceInitMethod(boolean enforceInitMethod) { + this.enforceInitMethod = enforceInitMethod; + } + + /** + * Indicate whether the configured init method is the default. + * @see #getInitMethodName() + */ + public boolean isEnforceInitMethod() { + return this.enforceInitMethod; + } + + /** + * Set the name of the destroy method. The default is null + * in which case there is no destroy method. + */ + public void setDestroyMethodName(String destroyMethodName) { + this.destroyMethodName = destroyMethodName; + } + + /** + * Return the name of the destroy method. + */ + public String getDestroyMethodName() { + return this.destroyMethodName; + } + + /** + * Specify whether or not the configured destroy method is the default. + * Default value is false. + * @see #setDestroyMethodName + */ + public void setEnforceDestroyMethod(boolean enforceDestroyMethod) { + this.enforceDestroyMethod = enforceDestroyMethod; + } + + /** + * Indicate whether the configured destroy method is the default. + * @see #getDestroyMethodName + */ + public boolean isEnforceDestroyMethod() { + return this.enforceDestroyMethod; + } + + + /** + * Set whether this bean definition is 'synthetic', that is, not defined + * by the application itself (for example, an infrastructure bean such + * as a helper for auto-proxying, created through <aop:config>). + */ + public void setSynthetic(boolean synthetic) { + this.synthetic = synthetic; + } + + /** + * Return whether this bean definition is 'synthetic', that is, + * not defined by the application itself. + */ + public boolean isSynthetic() { + return this.synthetic; + } + + /** + * Set the role hint for this BeanDefinition. + */ + public void setRole(int role) { + this.role = role; + } + + /** + * Return the role hint for this BeanDefinition. + */ + public int getRole() { + return this.role; + } + + + /** + * Set a human-readable description of this bean definition. + */ + public void setDescription(String description) { + this.description = description; + } + + public String getDescription() { + return this.description; + } + + /** + * Set the resource that this bean definition came from + * (for the purpose of showing context in case of errors). + */ + public void setResource(Resource resource) { + this.resource = resource; + } + + /** + * Return the resource that this bean definition came from. + */ + public Resource getResource() { + return this.resource; + } + + /** + * Set a description of the resource that this bean definition + * came from (for the purpose of showing context in case of errors). + */ + public void setResourceDescription(String resourceDescription) { + this.resource = new DescriptiveResource(resourceDescription); + } + + public String getResourceDescription() { + return (this.resource != null ? this.resource.getDescription() : null); + } + + /** + * Set the originating (e.g. decorated) BeanDefinition, if any. + */ + public void setOriginatingBeanDefinition(BeanDefinition originatingBd) { + this.resource = new BeanDefinitionResource(originatingBd); + } + + public BeanDefinition getOriginatingBeanDefinition() { + return (this.resource instanceof BeanDefinitionResource ? + ((BeanDefinitionResource) this.resource).getBeanDefinition() : null); + } + + /** + * Validate this bean definition. + * @throws BeanDefinitionValidationException in case of validation failure + */ + public void validate() throws BeanDefinitionValidationException { + if (!getMethodOverrides().isEmpty() && getFactoryMethodName() != null) { + throw new BeanDefinitionValidationException( + "Cannot combine static factory method with method overrides: " + + "the static factory method must create the instance"); + } + + if (hasBeanClass()) { + prepareMethodOverrides(); + } + } + + /** + * Validate and prepare the method overrides defined for this bean. + * Checks for existence of a method with the specified name. + * @throws BeanDefinitionValidationException in case of validation failure + */ + public void prepareMethodOverrides() throws BeanDefinitionValidationException { + // Check that lookup methods exists. + MethodOverrides methodOverrides = getMethodOverrides(); + if (!methodOverrides.isEmpty()) { + for (Iterator it = methodOverrides.getOverrides().iterator(); it.hasNext(); ) { + MethodOverride mo = (MethodOverride) it.next(); + prepareMethodOverride(mo); + } + } + } + + /** + * Validate and prepare the given method override. + * Checks for existence of a method with the specified name, + * marking it as not overloaded if none found. + * @param mo the MethodOverride object to validate + * @throws BeanDefinitionValidationException in case of validation failure + */ + protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException { + int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName()); + if (count == 0) { + throw new BeanDefinitionValidationException( + "Invalid method override: no method with name '" + mo.getMethodName() + + "' on class [" + getBeanClassName() + "]"); + } + else if (count == 1) { + // Mark override as not overloaded, to avoid the overhead of arg type checking. + mo.setOverloaded(false); + } + } + + + /** + * Public declaration of Object's clone() method. + * Delegates to {@link #cloneBeanDefinition()}. + * @see java.lang.Object#clone() + */ + public Object clone() { + return cloneBeanDefinition(); + } + + /** + * Clone this bean definition. + * To be implemented by concrete subclasses. + * @return the cloned bean definition object + */ + public abstract AbstractBeanDefinition cloneBeanDefinition(); + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AbstractBeanDefinition)) { + return false; + } + + AbstractBeanDefinition that = (AbstractBeanDefinition) other; + + if (!ObjectUtils.nullSafeEquals(getBeanClassName(), that.getBeanClassName())) return false; + if (!ObjectUtils.nullSafeEquals(this.scope, that.scope)) return false; + if (this.abstractFlag != that.abstractFlag) return false; + if (this.lazyInit != that.lazyInit) return false; + + if (this.autowireMode != that.autowireMode) return false; + if (this.dependencyCheck != that.dependencyCheck) return false; + if (!Arrays.equals(this.dependsOn, that.dependsOn)) return false; + if (this.autowireCandidate != that.autowireCandidate) return false; + if (!ObjectUtils.nullSafeEquals(this.qualifiers, that.qualifiers)) return false; + if (this.primary != that.primary) return false; + + if (!ObjectUtils.nullSafeEquals(this.constructorArgumentValues, that.constructorArgumentValues)) return false; + if (!ObjectUtils.nullSafeEquals(this.propertyValues, that.propertyValues)) return false; + if (!ObjectUtils.nullSafeEquals(this.methodOverrides, that.methodOverrides)) return false; + + if (!ObjectUtils.nullSafeEquals(this.factoryBeanName, that.factoryBeanName)) return false; + if (!ObjectUtils.nullSafeEquals(this.factoryMethodName, that.factoryMethodName)) return false; + if (!ObjectUtils.nullSafeEquals(this.initMethodName, that.initMethodName)) return false; + if (this.enforceInitMethod != that.enforceInitMethod) return false; + if (!ObjectUtils.nullSafeEquals(this.destroyMethodName, that.destroyMethodName)) return false; + if (this.enforceDestroyMethod != that.enforceDestroyMethod) return false; + + if (this.synthetic != that.synthetic) return false; + if (this.role != that.role) return false; + + return super.equals(other); + } + + public int hashCode() { + int hashCode = ObjectUtils.nullSafeHashCode(getBeanClassName()); + hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.scope); + hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.constructorArgumentValues); + hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.propertyValues); + hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.factoryBeanName); + hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.factoryMethodName); + hashCode = 29 * hashCode + super.hashCode(); + return hashCode; + } + + public String toString() { + StringBuffer sb = new StringBuffer("class ["); + sb.append(getBeanClassName()).append("]"); + sb.append("; scope=").append(this.scope); + sb.append("; abstract=").append(this.abstractFlag); + sb.append("; lazyInit=").append(this.lazyInit); + sb.append("; autowireMode=").append(this.autowireMode); + sb.append("; dependencyCheck=").append(this.dependencyCheck); + sb.append("; autowireCandidate=").append(this.autowireCandidate); + sb.append("; primary=").append(this.primary); + sb.append("; factoryBeanName=").append(this.factoryBeanName); + sb.append("; factoryMethodName=").append(this.factoryMethodName); + sb.append("; initMethodName=").append(this.initMethodName); + sb.append("; destroyMethodName=").append(this.destroyMethodName); + if (this.resource != null) { + sb.append("; defined in ").append(this.resource.getDescription()); + } + return sb.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/AbstractBeanDefinitionReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/AbstractBeanDefinitionReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/AbstractBeanDefinitionReader.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,217 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.io.IOException; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.util.Assert; + +/** + * Abstract base class for bean definition readers which implement + * the {@link BeanDefinitionReader} interface. + * + *

    Provides common properties like the bean factory to work on + * and the class loader to use for loading bean classes. + * + * @author Juergen Hoeller + * @since 11.12.2003 + * @see BeanDefinitionReaderUtils + */ +public abstract class AbstractBeanDefinitionReader implements BeanDefinitionReader { + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + private final BeanDefinitionRegistry registry; + + private ResourceLoader resourceLoader; + + private ClassLoader beanClassLoader; + + private BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator(); + + + /** + * Create a new AbstractBeanDefinitionReader for the given bean factory. + *

    If the passed-in bean factory does not only implement the BeanDefinitionRegistry + * interface but also the ResourceLoader interface, it will be used as default + * ResourceLoader as well. This will usually be the case for + * {@link org.springframework.context.ApplicationContext} implementations. + *

    If given a plain BeanDefinitionRegistry, the default ResourceLoader will be a + * {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}. + * @param registry the BeanFactory to load bean definitions into, + * in the form of a BeanDefinitionRegistry + * @see #setResourceLoader + */ + protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) { + Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); + this.registry = registry; + + // Determine ResourceLoader to use. + if (this.registry instanceof ResourceLoader) { + this.resourceLoader = (ResourceLoader) this.registry; + } + else { + this.resourceLoader = new PathMatchingResourcePatternResolver(); + } + } + + + public final BeanDefinitionRegistry getBeanFactory() { + return this.registry; + } + + public final BeanDefinitionRegistry getRegistry() { + return this.registry; + } + + /** + * Set the ResourceLoader to use for resource locations. + * If specifying a ResourcePatternResolver, the bean definition reader + * will be capable of resolving resource patterns to Resource arrays. + *

    Default is PathMatchingResourcePatternResolver, also capable of + * resource pattern resolving through the ResourcePatternResolver interface. + *

    Setting this to null suggests that absolute resource loading + * is not available for this bean definition reader. + * @see org.springframework.core.io.support.ResourcePatternResolver + * @see org.springframework.core.io.support.PathMatchingResourcePatternResolver + */ + public void setResourceLoader(ResourceLoader resourceLoader) { + this.resourceLoader = resourceLoader; + } + + public ResourceLoader getResourceLoader() { + return this.resourceLoader; + } + + /** + * Set the ClassLoader to use for bean classes. + *

    Default is null, which suggests to not load bean classes + * eagerly but rather to just register bean definitions with class names, + * with the corresponding Classes to be resolved later (or never). + * @see java.lang.Thread#getContextClassLoader() + */ + public void setBeanClassLoader(ClassLoader beanClassLoader) { + this.beanClassLoader = beanClassLoader; + } + + public ClassLoader getBeanClassLoader() { + return this.beanClassLoader; + } + + /** + * Set the BeanNameGenerator to use for anonymous beans + * (without explicit bean name specified). + *

    Default is a {@link DefaultBeanNameGenerator}. + */ + public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) { + this.beanNameGenerator = (beanNameGenerator != null ? beanNameGenerator : new DefaultBeanNameGenerator()); + } + + public BeanNameGenerator getBeanNameGenerator() { + return this.beanNameGenerator; + } + + + public int loadBeanDefinitions(Resource[] resources) throws BeanDefinitionStoreException { + Assert.notNull(resources, "Resource array must not be null"); + int counter = 0; + for (int i = 0; i < resources.length; i++) { + counter += loadBeanDefinitions(resources[i]); + } + return counter; + } + + public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException { + return loadBeanDefinitions(location, null); + } + + /** + * Load bean definitions from the specified resource location. + *

    The location can also be a location pattern, provided that the + * ResourceLoader of this bean definition reader is a ResourcePatternResolver. + * @param location the resource location, to be loaded with the ResourceLoader + * (or ResourcePatternResolver) of this bean definition reader + * @param actualResources a Set to be filled with the actual Resource objects + * that have been resolved during the loading process. May be null + * to indicate that the caller is not interested in those Resource objects. + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + * @see #getResourceLoader() + * @see #loadBeanDefinitions(org.springframework.core.io.Resource) + * @see #loadBeanDefinitions(org.springframework.core.io.Resource[]) + */ + public int loadBeanDefinitions(String location, Set actualResources) throws BeanDefinitionStoreException { + ResourceLoader resourceLoader = getResourceLoader(); + if (resourceLoader == null) { + throw new BeanDefinitionStoreException( + "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available"); + } + + if (resourceLoader instanceof ResourcePatternResolver) { + // Resource pattern matching available. + try { + Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location); + int loadCount = loadBeanDefinitions(resources); + if (actualResources != null) { + for (int i = 0; i < resources.length; i++) { + actualResources.add(resources[i]); + } + } + if (logger.isDebugEnabled()) { + logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]"); + } + return loadCount; + } + catch (IOException ex) { + throw new BeanDefinitionStoreException( + "Could not resolve bean definition resource pattern [" + location + "]", ex); + } + } + else { + // Can only load single resources by absolute URL. + Resource resource = resourceLoader.getResource(location); + int loadCount = loadBeanDefinitions(resource); + if (actualResources != null) { + actualResources.add(resource); + } + if (logger.isDebugEnabled()) { + logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]"); + } + return loadCount; + } + } + + public int loadBeanDefinitions(String[] locations) throws BeanDefinitionStoreException { + Assert.notNull(locations, "Location array must not be null"); + int counter = 0; + for (int i = 0; i < locations.length; i++) { + counter += loadBeanDefinitions(locations[i]); + } + return counter; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/AbstractBeanFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/AbstractBeanFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/AbstractBeanFactory.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,1411 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.beans.PropertyEditor; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.BeanWrapper; +import org.springframework.beans.BeansException; +import org.springframework.beans.PropertyEditorRegistrar; +import org.springframework.beans.PropertyEditorRegistry; +import org.springframework.beans.PropertyEditorRegistrySupport; +import org.springframework.beans.SimpleTypeConverter; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanCurrentlyInCreationException; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.BeanIsAbstractException; +import org.springframework.beans.factory.BeanIsNotAFactoryException; +import org.springframework.beans.factory.BeanNotOfRequiredTypeException; +import org.springframework.beans.factory.CannotLoadBeanClassException; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.ObjectFactory; +import org.springframework.beans.factory.SmartFactoryBean; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; +import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; +import org.springframework.beans.factory.config.Scope; +import org.springframework.core.CollectionFactory; +import org.springframework.core.DecoratingClassLoader; +import org.springframework.core.NamedThreadLocal; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +/** + * Abstract base class for {@link org.springframework.beans.factory.BeanFactory} + * implementations, providing the full capabilities of the + * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory} SPI. + * Does not assume a listable bean factory: can therefore also be used + * as base class for bean factory implementations which obtain bean definitions + * from some backend resource (where bean definition access is an expensive operation). + * + *

    This class provides a singleton cache (through its base class + * {@link org.springframework.beans.factory.support.DefaultSingletonBeanRegistry}, + * singleton/prototype determination, {@link org.springframework.beans.factory.FactoryBean} + * handling, aliases, bean definition merging for child bean definitions, + * and bean destruction ({@link org.springframework.beans.factory.DisposableBean} + * interface, custom destroy methods). Furthermore, it can manage a bean factory + * hierarchy (delegating to the parent in case of an unknown bean), through implementing + * the {@link org.springframework.beans.factory.HierarchicalBeanFactory} interface. + * + *

    The main template methods to be implemented by subclasses are + * {@link #getBeanDefinition} and {@link #createBean}, retrieving a bean definition + * for a given bean name and creating a bean instance for a given bean definition, + * respectively. Default implementations of those operations can be found in + * {@link DefaultListableBeanFactory} and {@link AbstractAutowireCapableBeanFactory}. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 15 April 2001 + * @see #getBeanDefinition + * @see #createBean + * @see AbstractAutowireCapableBeanFactory#createBean + * @see DefaultListableBeanFactory#getBeanDefinition + */ +public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory { + + /** Parent bean factory, for bean inheritance support */ + private BeanFactory parentBeanFactory; + + /** ClassLoader to resolve bean class names with, if necessary */ + private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); + + /** ClassLoader to temporarily resolve bean class names with, if necessary */ + private ClassLoader tempClassLoader; + + /** Whether to cache bean metadata or rather reobtain it for every access */ + private boolean cacheBeanMetadata = true; + + /** Custom PropertyEditorRegistrars to apply to the beans of this factory */ + private final Set propertyEditorRegistrars = new LinkedHashSet(4); + + /** Custom PropertyEditors to apply to the beans of this factory */ + private final Map customEditors = new HashMap(4); + + /** A custom TypeConverter to use, overriding the default PropertyEditor mechanism */ + private TypeConverter typeConverter; + + /** BeanPostProcessors to apply in createBean */ + private final List beanPostProcessors = new ArrayList(); + + /** Indicates whether any InstantiationAwareBeanPostProcessors have been registered */ + private boolean hasInstantiationAwareBeanPostProcessors; + + /** Indicates whether any DestructionAwareBeanPostProcessors have been registered */ + private boolean hasDestructionAwareBeanPostProcessors; + + /** Map from scope identifier String to corresponding Scope */ + private final Map scopes = new HashMap(); + + /** Map from bean name to merged RootBeanDefinition */ + private final Map mergedBeanDefinitions = CollectionFactory.createConcurrentMapIfPossible(16); + + /** Names of beans that have already been created at least once */ + private final Set alreadyCreated = Collections.synchronizedSet(new HashSet()); + + /** Names of beans that are currently in creation */ + private final ThreadLocal prototypesCurrentlyInCreation = + new NamedThreadLocal("Prototype beans currently in creation"); + + + /** + * Create a new AbstractBeanFactory. + */ + public AbstractBeanFactory() { + } + + /** + * Create a new AbstractBeanFactory with the given parent. + * @param parentBeanFactory parent bean factory, or null if none + * @see #getBean + */ + public AbstractBeanFactory(BeanFactory parentBeanFactory) { + this.parentBeanFactory = parentBeanFactory; + } + + + //--------------------------------------------------------------------- + // Implementation of BeanFactory interface + //--------------------------------------------------------------------- + + public Object getBean(String name) throws BeansException { + return getBean(name, null, null); + } + + public Object getBean(String name, Class requiredType) throws BeansException { + return getBean(name, requiredType, null); + } + + public Object getBean(String name, Object[] args) throws BeansException { + return getBean(name, null, args); + } + + /** + * Return an instance, which may be shared or independent, of the specified bean. + * @param name the name of the bean to retrieve + * @param requiredType the required type of the bean to retrieve + * @param args arguments to use if creating a prototype using explicit arguments to a + * static factory method. It is invalid to use a non-null args value in any other case. + * @return an instance of the bean + * @throws BeansException if the bean could not be created + */ + public Object getBean(String name, Class requiredType, Object[] args) throws BeansException { + return doGetBean(name, requiredType, args, false); + } + + /** + * Return an instance, which may be shared or independent, of the specified bean. + * @param name the name of the bean to retrieve + * @param requiredType the required type of the bean to retrieve + * @param args arguments to use if creating a prototype using explicit arguments to a + * static factory method. It is invalid to use a non-null args value in any other case. + * @param typeCheckOnly whether the instance is obtained for a type check, + * not for actual use + * @return an instance of the bean + * @throws BeansException if the bean could not be created + */ + protected Object doGetBean( + final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { + + final String beanName = transformedBeanName(name); + Object bean = null; + + // Eagerly check singleton cache for manually registered singletons. + Object sharedInstance = getSingleton(beanName); + if (sharedInstance != null && args == null) { + if (logger.isDebugEnabled()) { + if (isSingletonCurrentlyInCreation(beanName)) { + logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + + "' that is not fully initialized yet - a consequence of a circular reference"); + } + else { + logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); + } + } + bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); + } + + else { + // Fail if we're already creating this bean instance: + // We're assumably within a circular reference. + if (isPrototypeCurrentlyInCreation(beanName)) { + throw new BeanCurrentlyInCreationException(beanName); + } + + // Check if bean definition exists in this factory. + BeanFactory parentBeanFactory = getParentBeanFactory(); + if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { + // Not found -> check parent. + String nameToLookup = originalBeanName(name); + if (args != null) { + // Delegation to parent with explicit args. + return parentBeanFactory.getBean(nameToLookup, args); + } + else { + // No args -> delegate to standard getBean method. + return parentBeanFactory.getBean(nameToLookup, requiredType); + } + } + + if (!typeCheckOnly) { + markBeanAsCreated(beanName); + } + + final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); + checkMergedBeanDefinition(mbd, beanName, args); + + // Guarantee initialization of beans that the current bean depends on. + String[] dependsOn = mbd.getDependsOn(); + if (dependsOn != null) { + for (int i = 0; i < dependsOn.length; i++) { + String dependsOnBean = dependsOn[i]; + getBean(dependsOnBean); + registerDependentBean(dependsOnBean, beanName); + } + } + + // Create bean instance. + if (mbd.isSingleton()) { + sharedInstance = getSingleton(beanName, new ObjectFactory() { + public Object getObject() throws BeansException { + try { + return createBean(beanName, mbd, args); + } + catch (BeansException ex) { + // Explicitly remove instance from singleton cache: It might have been put there + // eagerly by the creation process, to allow for circular reference resolution. + // Also remove any beans that received a temporary reference to the bean. + destroySingleton(beanName); + throw ex; + } + } + }); + bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); + } + + else if (mbd.isPrototype()) { + // It's a prototype -> create a new instance. + Object prototypeInstance = null; + try { + beforePrototypeCreation(beanName); + prototypeInstance = createBean(beanName, mbd, args); + } + finally { + afterPrototypeCreation(beanName); + } + bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); + } + + else { + String scopeName = mbd.getScope(); + final Scope scope = (Scope) this.scopes.get(scopeName); + if (scope == null) { + throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); + } + try { + Object scopedInstance = scope.get(beanName, new ObjectFactory() { + public Object getObject() throws BeansException { + beforePrototypeCreation(beanName); + try { + return createBean(beanName, mbd, args); + } + finally { + afterPrototypeCreation(beanName); + } + } + }); + bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); + } + catch (IllegalStateException ex) { + throw new BeanCreationException(beanName, + "Scope '" + scopeName + "' is not active for the current thread; " + + "consider defining a scoped proxy for this bean if you intend to refer to it from a singleton", + ex); + } + } + } + + // Check if required type matches the type of the actual bean instance. + if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { + throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); + } + return bean; + } + + public boolean containsBean(String name) { + String beanName = transformedBeanName(name); + if (containsSingleton(beanName) || containsBeanDefinition(beanName)) { + return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name)); + } + // Not found -> check parent. + BeanFactory parentBeanFactory = getParentBeanFactory(); + return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name))); + } + + public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { + String beanName = transformedBeanName(name); + + Object beanInstance = getSingleton(beanName, false); + if (beanInstance != null) { + if (beanInstance instanceof FactoryBean) { + return (BeanFactoryUtils.isFactoryDereference(name) || ((FactoryBean) beanInstance).isSingleton()); + } + else { + return !BeanFactoryUtils.isFactoryDereference(name); + } + } + + else { + // No singleton instance found -> check bean definition. + BeanFactory parentBeanFactory = getParentBeanFactory(); + if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { + // No bean definition found in this factory -> delegate to parent. + return parentBeanFactory.isSingleton(originalBeanName(name)); + } + + RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); + + // In case of FactoryBean, return singleton status of created object if not a dereference. + if (mbd.isSingleton()) { + if (isFactoryBean(beanName, mbd)) { + if (BeanFactoryUtils.isFactoryDereference(name)) { + return true; + } + FactoryBean factoryBean = (FactoryBean) getBean(FACTORY_BEAN_PREFIX + beanName); + return factoryBean.isSingleton(); + } + else { + return !BeanFactoryUtils.isFactoryDereference(name); + } + } + else { + return false; + } + } + } + + public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { + String beanName = transformedBeanName(name); + + BeanFactory parentBeanFactory = getParentBeanFactory(); + if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { + // No bean definition found in this factory -> delegate to parent. + return parentBeanFactory.isPrototype(originalBeanName(name)); + } + + RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); + if (mbd.isPrototype()) { + // In case of FactoryBean, return singleton status of created object if not a dereference. + return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd)); + } + else { + // Singleton or scoped - not a prototype. + // However, FactoryBean may still produce a prototype object... + if (BeanFactoryUtils.isFactoryDereference(name)) { + return false; + } + if (isFactoryBean(beanName, mbd)) { + FactoryBean factoryBean = (FactoryBean) getBean(FACTORY_BEAN_PREFIX + beanName); + return ((factoryBean instanceof SmartFactoryBean && ((SmartFactoryBean) factoryBean).isPrototype()) || + !factoryBean.isSingleton()); + } + else { + return false; + } + } + } + + public boolean isTypeMatch(String name, Class targetType) throws NoSuchBeanDefinitionException { + String beanName = transformedBeanName(name); + Class typeToMatch = (targetType != null ? targetType : Object.class); + + // Check manually registered singletons. + Object beanInstance = getSingleton(beanName, false); + if (beanInstance != null) { + if (beanInstance instanceof FactoryBean) { + if (!BeanFactoryUtils.isFactoryDereference(name)) { + Class type = getTypeForFactoryBean((FactoryBean) beanInstance); + return (type != null && typeToMatch.isAssignableFrom(type)); + } + else { + return typeToMatch.isAssignableFrom(beanInstance.getClass()) ; + } + } + else { + return !BeanFactoryUtils.isFactoryDereference(name) && + typeToMatch.isAssignableFrom(beanInstance.getClass()); + } + } + + else { + // No singleton instance found -> check bean definition. + BeanFactory parentBeanFactory = getParentBeanFactory(); + if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { + // No bean definition found in this factory -> delegate to parent. + return parentBeanFactory.isTypeMatch(originalBeanName(name), targetType); + } + + RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); + Class beanClass = predictBeanType(beanName, mbd, new Class[] {FactoryBean.class, typeToMatch}); + if (beanClass == null) { + return false; + } + + // Check bean class whether we're dealing with a FactoryBean. + if (FactoryBean.class.isAssignableFrom(beanClass)) { + if (!BeanFactoryUtils.isFactoryDereference(name)) { + // If it's a FactoryBean, we want to look at what it creates, not the factory class. + Class type = getTypeForFactoryBean(beanName, mbd); + return (type != null && typeToMatch.isAssignableFrom(type)); + } + else { + return typeToMatch.isAssignableFrom(beanClass); + } + } + else { + return !BeanFactoryUtils.isFactoryDereference(name) && + typeToMatch.isAssignableFrom(beanClass); + } + } + } + + public Class getType(String name) throws NoSuchBeanDefinitionException { + String beanName = transformedBeanName(name); + + // Check manually registered singletons. + Object beanInstance = getSingleton(beanName, false); + if (beanInstance != null) { + if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { + return getTypeForFactoryBean((FactoryBean) beanInstance); + } + else { + return beanInstance.getClass(); + } + } + + else { + // No singleton instance found -> check bean definition. + BeanFactory parentBeanFactory = getParentBeanFactory(); + if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { + // No bean definition found in this factory -> delegate to parent. + return parentBeanFactory.getType(originalBeanName(name)); + } + + RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); + Class beanClass = predictBeanType(beanName, mbd, null); + + // Check bean class whether we're dealing with a FactoryBean. + if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) { + if (!BeanFactoryUtils.isFactoryDereference(name)) { + // If it's a FactoryBean, we want to look at what it creates, not the factory class. + return getTypeForFactoryBean(beanName, mbd); + } + else { + return beanClass; + } + } + else { + return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null); + } + } + } + + public String[] getAliases(String name) { + String beanName = transformedBeanName(name); + List aliases = new ArrayList(); + boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX); + String fullBeanName = beanName; + if (factoryPrefix) { + fullBeanName = FACTORY_BEAN_PREFIX + beanName; + } + if (!fullBeanName.equals(name)) { + aliases.add(fullBeanName); + } + String[] retrievedAliases = super.getAliases(beanName); + for (int i = 0; i < retrievedAliases.length; i++) { + String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAliases[i]; + if (!alias.equals(name)) { + aliases.add(alias); + } + } + if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) { + BeanFactory parentBeanFactory = getParentBeanFactory(); + if (parentBeanFactory != null) { + aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName))); + } + } + return StringUtils.toStringArray(aliases); + } + + + //--------------------------------------------------------------------- + // Implementation of HierarchicalBeanFactory interface + //--------------------------------------------------------------------- + + public BeanFactory getParentBeanFactory() { + return this.parentBeanFactory; + } + + public boolean containsLocalBean(String name) { + String beanName = transformedBeanName(name); + return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) && + (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName))); + } + + + //--------------------------------------------------------------------- + // Implementation of ConfigurableBeanFactory interface + //--------------------------------------------------------------------- + + public void setParentBeanFactory(BeanFactory parentBeanFactory) { + if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) { + throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory); + } + this.parentBeanFactory = parentBeanFactory; + } + + public void setBeanClassLoader(ClassLoader beanClassLoader) { + this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader()); + } + + public ClassLoader getBeanClassLoader() { + return this.beanClassLoader; + } + + public void setTempClassLoader(ClassLoader tempClassLoader) { + this.tempClassLoader = tempClassLoader; + } + + public ClassLoader getTempClassLoader() { + return this.tempClassLoader; + } + + public void setCacheBeanMetadata(boolean cacheBeanMetadata) { + this.cacheBeanMetadata = cacheBeanMetadata; + } + + public boolean isCacheBeanMetadata() { + return this.cacheBeanMetadata; + } + + public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) { + Assert.notNull(registrar, "PropertyEditorRegistrar must not be null"); + this.propertyEditorRegistrars.add(registrar); + } + + /** + * Return the set of PropertyEditorRegistrars. + */ + public Set getPropertyEditorRegistrars() { + return this.propertyEditorRegistrars; + } + + public void registerCustomEditor(Class requiredType, Class propertyEditorClass) { + Assert.notNull(requiredType, "Required type must not be null"); + Assert.isAssignable(PropertyEditor.class, propertyEditorClass); + this.customEditors.put(requiredType, propertyEditorClass); + } + + public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { + Assert.notNull(requiredType, "Required type must not be null"); + Assert.notNull(propertyEditor, "PropertyEditor must not be null"); + this.customEditors.put(requiredType, propertyEditor); + } + + public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) { + registerCustomEditors(registry); + } + + /** + * Return the map of custom editors, with Classes as keys + * and PropertyEditor instances or PropertyEditor classes as values. + */ + public Map getCustomEditors() { + return this.customEditors; + } + + public void setTypeConverter(TypeConverter typeConverter) { + this.typeConverter = typeConverter; + } + + /** + * Return the custom TypeConverter to use, if any. + * @return the custom TypeConverter, or null if none specified + */ + protected TypeConverter getCustomTypeConverter() { + return this.typeConverter; + } + + public TypeConverter getTypeConverter() { + TypeConverter customConverter = getCustomTypeConverter(); + if (customConverter != null) { + return customConverter; + } + else { + // Build default TypeConverter, registering custom editors. + SimpleTypeConverter typeConverter = new SimpleTypeConverter(); + registerCustomEditors(typeConverter); + return typeConverter; + } + } + + public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) { + Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null"); + this.beanPostProcessors.add(beanPostProcessor); + if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) { + this.hasInstantiationAwareBeanPostProcessors = true; + } + if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) { + this.hasDestructionAwareBeanPostProcessors = true; + } + } + + public int getBeanPostProcessorCount() { + return this.beanPostProcessors.size(); + } + + /** + * Return the list of BeanPostProcessors that will get applied + * to beans created with this factory. + */ + public List getBeanPostProcessors() { + return this.beanPostProcessors; + } + + /** + * Return whether this factory holds a InstantiationAwareBeanPostProcessor + * that will get applied to singleton beans on shutdown. + * @see #addBeanPostProcessor + * @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor + */ + protected boolean hasInstantiationAwareBeanPostProcessors() { + return this.hasInstantiationAwareBeanPostProcessors; + } + + /** + * Return whether this factory holds a DestructionAwareBeanPostProcessor + * that will get applied to singleton beans on shutdown. + * @see #addBeanPostProcessor + * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor + */ + protected boolean hasDestructionAwareBeanPostProcessors() { + return this.hasDestructionAwareBeanPostProcessors; + } + + public void registerScope(String scopeName, Scope scope) { + Assert.notNull(scopeName, "Scope identifier must not be null"); + Assert.notNull(scope, "Scope must not be null"); + if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) { + throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'"); + } + this.scopes.put(scopeName, scope); + } + + public String[] getRegisteredScopeNames() { + return StringUtils.toStringArray(this.scopes.keySet()); + } + + public Scope getRegisteredScope(String scopeName) { + Assert.notNull(scopeName, "Scope identifier must not be null"); + return (Scope) this.scopes.get(scopeName); + } + + public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { + Assert.notNull(otherFactory, "BeanFactory must not be null"); + setBeanClassLoader(otherFactory.getBeanClassLoader()); + setCacheBeanMetadata(otherFactory.isCacheBeanMetadata()); + if (otherFactory instanceof AbstractBeanFactory) { + AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory; + this.customEditors.putAll(otherAbstractFactory.customEditors); + this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars); + this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors); + this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors || + otherAbstractFactory.hasInstantiationAwareBeanPostProcessors; + this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors || + otherAbstractFactory.hasDestructionAwareBeanPostProcessors; + this.scopes.putAll(otherAbstractFactory.scopes); + } + } + + /** + * Return a 'merged' BeanDefinition for the given bean name, + * merging a child bean definition with its parent if necessary. + *

    This getMergedBeanDefinition considers bean definition + * in ancestors as well. + * @param name the name of the bean to retrieve the merged definition for + * (may be an alias) + * @return a (potentially merged) RootBeanDefinition for the given bean + * @throws NoSuchBeanDefinitionException if there is no bean with the given name + * @throws BeanDefinitionStoreException in case of an invalid bean definition + */ + public BeanDefinition getMergedBeanDefinition(String name) throws BeansException { + String beanName = transformedBeanName(name); + + // Efficiently check whether bean definition exists in this factory. + if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) { + return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName); + } + // Resolve merged bean definition locally. + return getMergedLocalBeanDefinition(beanName); + } + + public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException { + String beanName = transformedBeanName(name); + + Object beanInstance = getSingleton(beanName, false); + if (beanInstance != null) { + return (beanInstance instanceof FactoryBean); + } + + // No singleton instance found -> check bean definition. + if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) { + // No bean definition found in this factory -> delegate to parent. + return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name); + } + + return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName)); + } + + /** + * Callback before prototype creation. + *

    The default implementation register the prototype as currently in creation. + * @param beanName the name of the prototype about to be created + * @see #isPrototypeCurrentlyInCreation + */ + protected void beforePrototypeCreation(String beanName) { + Object curVal = this.prototypesCurrentlyInCreation.get(); + if (curVal == null) { + this.prototypesCurrentlyInCreation.set(beanName); + } + else if (curVal instanceof String) { + Set beanNameSet = new HashSet(2); + beanNameSet.add(curVal); + beanNameSet.add(beanName); + this.prototypesCurrentlyInCreation.set(beanNameSet); + } + else { + Set beanNameSet = (Set) curVal; + beanNameSet.add(beanName); + } + } + + /** + * Callback after prototype creation. + *

    The default implementation marks the prototype as not in creation anymore. + * @param beanName the name of the prototype that has been created + * @see #isPrototypeCurrentlyInCreation + */ + protected void afterPrototypeCreation(String beanName) { + Object curVal = this.prototypesCurrentlyInCreation.get(); + if (curVal instanceof String) { + this.prototypesCurrentlyInCreation.set(null); + } + else if (curVal instanceof Set) { + Set beanNameSet = (Set) curVal; + beanNameSet.remove(beanName); + if (beanNameSet.isEmpty()) { + this.prototypesCurrentlyInCreation.set(null); + } + } + } + + /** + * Return whether the specified prototype bean is currently in creation + * (within the current thread). + * @param beanName the name of the bean + */ + protected final boolean isPrototypeCurrentlyInCreation(String beanName) { + Object curVal = this.prototypesCurrentlyInCreation.get(); + return (curVal != null && + (curVal.equals(beanName) || (curVal instanceof Set && ((Set) curVal).contains(beanName)))); + } + + public boolean isCurrentlyInCreation(String beanName) { + return isSingletonCurrentlyInCreation(beanName) || isPrototypeCurrentlyInCreation(beanName); + } + + public void destroyBean(String beanName, Object beanInstance) { + destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName)); + } + + /** + * Destroy the given bean instance (usually a prototype instance + * obtained from this factory) according to the given bean definition. + * @param beanName the name of the bean definition + * @param beanInstance the bean instance to destroy + * @param mbd the merged bean definition + */ + protected void destroyBean(String beanName, Object beanInstance, RootBeanDefinition mbd) { + new DisposableBeanAdapter(beanInstance, beanName, mbd, getBeanPostProcessors()).destroy(); + } + + public void destroyScopedBean(String beanName) { + RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); + if (mbd.isSingleton() || mbd.isPrototype()) { + throw new IllegalArgumentException( + "Bean name '" + beanName + "' does not correspond to an object in a Scope"); + } + String scopeName = mbd.getScope(); + Scope scope = (Scope) this.scopes.get(scopeName); + if (scope == null) { + throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); + } + Object bean = scope.remove(beanName); + if (bean != null) { + destroyBean(beanName, bean, mbd); + } + } + + + //--------------------------------------------------------------------- + // Implementation methods + //--------------------------------------------------------------------- + + /** + * Return the bean name, stripping out the factory dereference prefix if necessary, + * and resolving aliases to canonical names. + * @param name the user-specified name + * @return the transformed bean name + */ + protected String transformedBeanName(String name) { + return canonicalName(BeanFactoryUtils.transformedBeanName(name)); + } + + /** + * Determine the original bean name, resolving locally defined aliases to canonical names. + * @param name the user-specified name + * @return the original bean name + */ + protected String originalBeanName(String name) { + String beanName = transformedBeanName(name); + if (name.startsWith(FACTORY_BEAN_PREFIX)) { + beanName = FACTORY_BEAN_PREFIX + beanName; + } + return beanName; + } + + /** + * Initialize the given BeanWrapper with the custom editors registered + * with this factory. To be called for BeanWrappers that will create + * and populate bean instances. + *

    The default implementation delegates to {@link #registerCustomEditors}. + * Can be overridden in subclasses. + * @param bw the BeanWrapper to initialize + */ + protected void initBeanWrapper(BeanWrapper bw) { + registerCustomEditors(bw); + } + + /** + * Initialize the given PropertyEditorRegistry with the custom editors + * that have been registered with this BeanFactory. + *

    To be called for BeanWrappers that will create and populate bean + * instances, and for SimpleTypeConverter used for constructor argument + * and factory method type conversion. + * @param registry the PropertyEditorRegistry to initialize + */ + protected void registerCustomEditors(PropertyEditorRegistry registry) { + PropertyEditorRegistrySupport registrySupport = + (registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null); + if (registrySupport != null) { + registrySupport.useConfigValueEditors(); + } + if (!this.propertyEditorRegistrars.isEmpty()) { + for (Iterator it = this.propertyEditorRegistrars.iterator(); it.hasNext();) { + PropertyEditorRegistrar registrar = (PropertyEditorRegistrar) it.next(); + try { + registrar.registerCustomEditors(registry); + } + catch (BeanCreationException ex) { + Throwable rootCause = ex.getMostSpecificCause(); + if (rootCause instanceof BeanCurrentlyInCreationException) { + BeanCreationException bce = (BeanCreationException) rootCause; + if (isCurrentlyInCreation(bce.getBeanName())) { + if (logger.isDebugEnabled()) { + logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() + + "] failed because it tried to obtain currently created bean '" + ex.getBeanName() + + "': " + ex.getMessage()); + } + onSuppressedException(ex); + continue; + } + } + throw ex; + } + } + } + if (!this.customEditors.isEmpty()) { + for (Iterator it = this.customEditors.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + Class requiredType = (Class) entry.getKey(); + Object value = entry.getValue(); + if (value instanceof PropertyEditor) { + PropertyEditor editor = (PropertyEditor) value; + // Register the editor as shared instance, if possible, + // to make it clear that it might be used concurrently. + if (registrySupport != null) { + registrySupport.registerSharedEditor(requiredType, editor); + } + else { + registry.registerCustomEditor(requiredType, editor); + } + } + else if (value instanceof Class) { + Class editorClass = (Class) value; + registry.registerCustomEditor(requiredType, (PropertyEditor) BeanUtils.instantiateClass(editorClass)); + } + else { + throw new IllegalStateException("Illegal custom editor value type: " + value.getClass().getName()); + } + } + } + } + + + /** + * Return a merged RootBeanDefinition, traversing the parent bean definition + * if the specified bean corresponds to a child bean definition. + * @param beanName the name of the bean to retrieve the merged definition for + * @return a (potentially merged) RootBeanDefinition for the given bean + * @throws NoSuchBeanDefinitionException if there is no bean with the given name + * @throws BeanDefinitionStoreException in case of an invalid bean definition + */ + protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException { + // Quick check on the concurrent map first, with minimal locking. + RootBeanDefinition mbd = (RootBeanDefinition) this.mergedBeanDefinitions.get(beanName); + if (mbd != null) { + return mbd; + } + return getMergedBeanDefinition(beanName, getBeanDefinition(beanName)); + } + + /** + * Return a RootBeanDefinition for the given top-level bean, by merging with + * the parent if the given bean's definition is a child bean definition. + * @param beanName the name of the bean definition + * @param bd the original bean definition (Root/ChildBeanDefinition) + * @return a (potentially merged) RootBeanDefinition for the given bean + * @throws BeanDefinitionStoreException in case of an invalid bean definition + */ + protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd) + throws BeanDefinitionStoreException { + + return getMergedBeanDefinition(beanName, bd, null); + } + + /** + * Return a RootBeanDefinition for the given bean, by merging with the + * parent if the given bean's definition is a child bean definition. + * @param beanName the name of the bean definition + * @param bd the original bean definition (Root/ChildBeanDefinition) + * @param containingBd the containing bean definition in case of inner bean, + * or null in case of a top-level bean + * @return a (potentially merged) RootBeanDefinition for the given bean + * @throws BeanDefinitionStoreException in case of an invalid bean definition + */ + protected RootBeanDefinition getMergedBeanDefinition( + String beanName, BeanDefinition bd, BeanDefinition containingBd) + throws BeanDefinitionStoreException { + + synchronized (this.mergedBeanDefinitions) { + RootBeanDefinition mbd = null; + + // Check with full lock now in order to enforce the same merged instance. + if (containingBd == null) { + mbd = (RootBeanDefinition) this.mergedBeanDefinitions.get(beanName); + } + + if (mbd == null) { + if (bd.getParentName() == null) { + // Use copy of given root bean definition. + mbd = new RootBeanDefinition(bd); + } + else { + // Child bean definition: needs to be merged with parent. + BeanDefinition pbd = null; + try { + String parentBeanName = transformedBeanName(bd.getParentName()); + if (!beanName.equals(parentBeanName)) { + pbd = getMergedBeanDefinition(parentBeanName); + } + else { + if (getParentBeanFactory() instanceof ConfigurableBeanFactory) { + pbd = ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(parentBeanName); + } + else { + throw new NoSuchBeanDefinitionException(bd.getParentName(), + "Parent name '" + bd.getParentName() + "' is equal to bean name '" + beanName + + "': cannot be resolved without an AbstractBeanFactory parent"); + } + } + } + catch (NoSuchBeanDefinitionException ex) { + throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName, + "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex); + } + // Deep copy with overridden values. + mbd = new RootBeanDefinition(pbd); + mbd.overrideFrom(bd); + } + + // A bean contained in a non-singleton bean cannot be a singleton itself. + // Let's correct this on the fly here, since this might be the result of + // parent-child merging for the outer bean, in which case the original inner bean + // definition will not have inherited the merged outer bean's singleton status. + if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) { + mbd.setScope(containingBd.getScope()); + } + + // Only cache the merged bean definition if we're already about to create an + // instance of the bean, or at least have already created an instance before. + if (containingBd == null && isCacheBeanMetadata() && isBeanEligibleForMetadataCaching(beanName)) { + this.mergedBeanDefinitions.put(beanName, mbd); + } + } + + return mbd; + } + } + + /** + * Check the given merged bean definition, + * potentially throwing validation exceptions. + * @param mbd the merged bean definition to check + * @param beanName the name of the bean + * @param args the arguments for bean creation, if any + * @throws BeanDefinitionStoreException in case of validation failure + */ + protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, Object[] args) + throws BeanDefinitionStoreException { + + // check if bean definition is not abstract + if (mbd.isAbstract()) { + throw new BeanIsAbstractException(beanName); + } + + // Check validity of the usage of the args parameter. This can + // only be used for prototypes constructed via a factory method. + if (args != null && !mbd.isPrototype()) { + throw new BeanDefinitionStoreException( + "Can only specify arguments for the getBean method when referring to a prototype bean definition"); + } + } + + /** + * Remove the merged bean definition for the specified bean, + * recreating it on next access. + * @param beanName the bean name to clear the merged definition for + */ + protected void clearMergedBeanDefinition(String beanName) { + this.mergedBeanDefinitions.remove(beanName); + } + + /** + * Resolve the bean class for the specified bean definition, + * resolving a bean class name into a Class reference (if necessary) + * and storing the resolved Class in the bean definition for further use. + * @param mbd the merged bean definition to determine the class for + * @param beanName the name of the bean (for error handling purposes) + * @return the resolved bean class (or null if none) + * @throws CannotLoadBeanClassException if we failed to load the class + */ + protected Class resolveBeanClass(RootBeanDefinition mbd, String beanName) { + return resolveBeanClass(mbd, beanName, null); + } + + /** + * Resolve the bean class for the specified bean definition, + * resolving a bean class name into a Class reference (if necessary) + * and storing the resolved Class in the bean definition for further use. + * @param mbd the merged bean definition to determine the class for + * @param beanName the name of the bean (for error handling purposes) + * @param typesToMatch the types to match in case of internal type matching purposes + * (also signals that the returned Class will never be exposed to application code) + * @return the resolved bean class (or null if none) + * @throws CannotLoadBeanClassException if we failed to load the class + */ + protected Class resolveBeanClass(RootBeanDefinition mbd, String beanName, Class[] typesToMatch) + throws CannotLoadBeanClassException { + try { + if (mbd.hasBeanClass()) { + return mbd.getBeanClass(); + } + if (typesToMatch != null) { + ClassLoader tempClassLoader = getTempClassLoader(); + if (tempClassLoader != null) { + if (tempClassLoader instanceof DecoratingClassLoader) { + DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader; + for (int i = 0; i < typesToMatch.length; i++) { + dcl.excludeClass(typesToMatch[i].getName()); + } + } + String className = mbd.getBeanClassName(); + return (className != null ? ClassUtils.forName(className, tempClassLoader) : null); + } + } + return mbd.resolveBeanClass(getBeanClassLoader()); + } + catch (ClassNotFoundException ex) { + throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex); + } + catch (LinkageError err) { + throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err); + } + } + + + /** + * Predict the eventual bean type (of the processed bean instance) for the + * specified bean. Called by {@link #getType} and {@link #isTypeMatch}. + * Does not need to handle FactoryBeans specifically, since it is only + * supposed to operate on the raw bean type. + *

    This implementation is simplistic in that it is not able to + * handle factory methods and InstantiationAwareBeanPostProcessors. + * It only predicts the bean type correctly for a standard bean. + * To be overridden in subclasses, applying more sophisticated type detection. + * @param beanName the name of the bean + * @param mbd the merged bean definition to determine the type for + * @param typesToMatch the types to match in case of internal type matching purposes + * (also signals that the returned Class will never be exposed to application code) + * @return the type of the bean, or null if not predictable + */ + protected Class predictBeanType(String beanName, RootBeanDefinition mbd, Class[] typesToMatch) { + if (mbd.getFactoryMethodName() != null) { + return null; + } + return resolveBeanClass(mbd, beanName, typesToMatch); + } + + /** + * Check whether the given bean is defined as a {@link FactoryBean}. + * @param beanName the name of the bean + * @param mbd the corresponding bean definition + */ + protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) { + Class beanClass = predictBeanType(beanName, mbd, new Class[] {FactoryBean.class}); + return (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)); + } + + /** + * Determine the bean type for the given FactoryBean definition, as far as possible. + * Only called if there is no singleton instance registered for the target bean already. + *

    The default implementation creates the FactoryBean via getBean + * to call its getObjectType method. Subclasses are encouraged to optimize + * this, typically by just instantiating the FactoryBean but not populating it yet, + * trying whether its getObjectType method already returns a type. + * If no type found, a full FactoryBean creation as performed by this implementation + * should be used as fallback. + * @param beanName the name of the bean + * @param mbd the merged bean definition for the bean + * @return the type for the bean if determinable, or null else + * @see org.springframework.beans.factory.FactoryBean#getObjectType() + * @see #getBean(String) + */ + protected Class getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) { + if (!mbd.isSingleton()) { + return null; + } + try { + FactoryBean factoryBean = + (FactoryBean) doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true); + return getTypeForFactoryBean(factoryBean); + } + catch (BeanCreationException ex) { + // Can only happen when getting a FactoryBean. + if (logger.isDebugEnabled()) { + logger.debug("Ignoring bean creation exception on FactoryBean type check: " + ex); + } + onSuppressedException(ex); + return null; + } + } + + /** + * Mark the specified bean as already created (or about to be created). + *

    This allows the bean factory to optimize its caching for repeated + * creation of the specified bean. + * @param beanName the name of the bean + */ + protected void markBeanAsCreated(String beanName) { + this.alreadyCreated.add(beanName); + } + + /** + * Determine whether the specified bean is eligible for having + * its bean definition metadata cached. + * @param beanName the name of the bean + * @return true if the bean's metadata may be cached + * at this point already + */ + protected boolean isBeanEligibleForMetadataCaching(String beanName) { + return this.alreadyCreated.contains(beanName); + } + + /** + * Remove the singleton instance (if any) for the given bean name, + * but only if it hasn't been used for other purposes than type checking. + * @param beanName the name of the bean + * @return true if actually removed, false otherwise + */ + protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) { + if (!this.alreadyCreated.contains(beanName)) { + removeSingleton(beanName); + return true; + } + else { + return false; + } + } + + /** + * Get the object for the given bean instance, either the bean + * instance itself or its created object in case of a FactoryBean. + * @param beanInstance the shared bean instance + * @param name name that may include factory dereference prefix + * @param beanName the canonical bean name + * @param mbd the merged bean definition + * @return the object to expose for the bean + */ + protected Object getObjectForBeanInstance( + Object beanInstance, String name, String beanName, RootBeanDefinition mbd) { + + // Don't let calling code try to dereference the factory if the bean isn't a factory. + if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) { + throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass()); + } + + // Now we have the bean instance, which may be a normal bean or a FactoryBean. + // If it's a FactoryBean, we use it to create a bean instance, unless the + // caller actually wants a reference to the factory. + if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) { + return beanInstance; + } + + Object object = null; + if (mbd == null) { + object = getCachedObjectForFactoryBean(beanName); + } + if (object == null) { + // Return bean instance from factory. + FactoryBean factory = (FactoryBean) beanInstance; + // Caches object obtained from FactoryBean if it is a singleton. + if (mbd == null && containsBeanDefinition(beanName)) { + mbd = getMergedLocalBeanDefinition(beanName); + } + boolean synthetic = (mbd != null && mbd.isSynthetic()); + object = getObjectFromFactoryBean(factory, beanName, !synthetic); + } + return object; + } + + /** + * Determine whether the given bean name is already in use within this factory, + * i.e. whether there is a local bean or alias registered under this name or + * an inner bean created with this name. + * @param beanName the name to check + */ + public boolean isBeanNameInUse(String beanName) { + return isAlias(beanName) || containsLocalBean(beanName) || hasDependentBean(beanName); + } + + /** + * Determine whether the given bean requires destruction on shutdown. + *

    The default implementation checks the DisposableBean interface as well as + * a specified destroy method and registered DestructionAwareBeanPostProcessors. + * @param bean the bean instance to check + * @param mbd the corresponding bean definition + * @see org.springframework.beans.factory.DisposableBean + * @see AbstractBeanDefinition#getDestroyMethodName() + * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor + */ + protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) { + return (bean instanceof DisposableBean || mbd.getDestroyMethodName() != null || + hasDestructionAwareBeanPostProcessors()); + } + + /** + * Add the given bean to the list of disposable beans in this factory, + * registering its DisposableBean interface and/or the given destroy method + * to be called on factory shutdown (if applicable). Only applies to singletons. + * @param beanName the name of the bean + * @param bean the bean instance + * @param mbd the bean definition for the bean + * @see RootBeanDefinition#isSingleton + * @see RootBeanDefinition#getDependsOn + * @see #registerDisposableBean + * @see #registerDependentBean + */ + protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) { + if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) { + if (mbd.isSingleton()) { + // Register a DisposableBean implementation that performs all destruction + // work for the given bean: DestructionAwareBeanPostProcessors, + // DisposableBean interface, custom destroy method. + registerDisposableBean(beanName, + new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors())); + } + else { + // A bean with a custom scope... + Scope scope = (Scope) this.scopes.get(mbd.getScope()); + if (scope == null) { + throw new IllegalStateException("No Scope registered for scope '" + mbd.getScope() + "'"); + } + scope.registerDestructionCallback(beanName, + new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors())); + } + } + } + + + //--------------------------------------------------------------------- + // Abstract methods to be implemented by subclasses + //--------------------------------------------------------------------- + + /** + * Check if this bean factory contains a bean definition with the given name. + * Does not consider any hierarchy this factory may participate in. + * Invoked by containsBean when no cached singleton instance is found. + *

    Depending on the nature of the concrete bean factory implementation, + * this operation might be expensive (for example, because of directory lookups + * in external registries). However, for listable bean factories, this usually + * just amounts to a local hash lookup: The operation is therefore part of the + * public interface there. The same implementation can serve for both this + * template method and the public interface method in that case. + * @param beanName the name of the bean to look for + * @return if this bean factory contains a bean definition with the given name + * @see #containsBean + * @see org.springframework.beans.factory.ListableBeanFactory#containsBeanDefinition + */ + protected abstract boolean containsBeanDefinition(String beanName); + + /** + * Return the bean definition for the given bean name. + * Subclasses should normally implement caching, as this method is invoked + * by this class every time bean definition metadata is needed. + *

    Depending on the nature of the concrete bean factory implementation, + * this operation might be expensive (for example, because of directory lookups + * in external registries). However, for listable bean factories, this usually + * just amounts to a local hash lookup: The operation is therefore part of the + * public interface there. The same implementation can serve for both this + * template method and the public interface method in that case. + * @param beanName the name of the bean to find a definition for + * @return the BeanDefinition for this prototype name (never null) + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + * if the bean definition cannot be resolved + * @throws BeansException in case of errors + * @see RootBeanDefinition + * @see ChildBeanDefinition + * @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBeanDefinition + */ + protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException; + + /** + * Create a bean instance for the given bean definition. + * The bean definition will already have been merged with the parent + * definition in case of a child definition. + *

    All the other methods in this class invoke this method, although + * beans may be cached after being instantiated by this method. All bean + * instantiation within this class is performed by this method. + * @param beanName the name of the bean + * @param mbd the merged bean definition for the bean + * @param args arguments to use if creating a prototype using explicit arguments to a + * static factory method. This parameter must be null except in this case. + * @return a new instance of the bean + * @throws BeanCreationException if the bean could not be created + */ + protected abstract Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) + throws BeanCreationException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/AutowireCandidateQualifier.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/AutowireCandidateQualifier.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/AutowireCandidateQualifier.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,96 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.BeanMetadataAttributeAccessor; +import org.springframework.util.Assert; + +/** + * Qualifier for resolving autowire candidates. A bean definition that + * includes one or more such qualifiers enables fine-grained matching + * against annotations on a field or parameter to be autowired. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + * @see org.springframework.beans.factory.annotation.Qualifier + */ +public class AutowireCandidateQualifier extends BeanMetadataAttributeAccessor { + + public static String VALUE_KEY = "value"; + + private final String typeName; + + + /** + * Construct a qualifier to match against an annotation of the + * given type. + * @param type the annotation type + */ + public AutowireCandidateQualifier(Class type) { + this(type.getName()); + } + + /** + * Construct a qualifier to match against an annotation of the + * given type name. + *

    The type name may match the fully-qualified class name of + * the annotation or the short class name (without the package). + * @param typeName the name of the annotation type + */ + public AutowireCandidateQualifier(String typeName) { + Assert.notNull(typeName, "Type name must not be null"); + this.typeName = typeName; + } + + /** + * Construct a qualifier to match against an annotation of the + * given type whose value attribute also matches + * the specified value. + * @param type the annotation type + * @param value the annotation value to match + */ + public AutowireCandidateQualifier(Class type, Object value) { + this(type.getName(), value); + } + + /** + * Construct a qualifier to match against an annotation of the + * given type name whose value attribute also matches + * the specified value. + *

    The type name may match the fully-qualified class name of + * the annotation or the short class name (without the package). + * @param typeName the name of the annotation type + * @param value the annotation value to match + */ + public AutowireCandidateQualifier(String typeName, Object value) { + Assert.notNull(typeName, "Type name must not be null"); + this.typeName = typeName; + setAttribute(VALUE_KEY, value); + } + + + /** + * Retrieve the type name. This value will be the same as the + * type name provided to the constructor or the fully-qualified + * class name if a Class instance was provided to the constructor. + */ + public String getTypeName() { + return this.typeName; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/AutowireCandidateResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/AutowireCandidateResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/AutowireCandidateResolver.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.config.DependencyDescriptor; + +/** + * Strategy interface for determining whether a specific bean definition + * qualifies as an autowire candidate for a specific dependency. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + */ +public interface AutowireCandidateResolver { + + /** + * Determine whether the given bean definition qualifies as an + * autowire candidate for the given dependency. + * @param bdHolder the bean definition including bean name and aliases + * @param descriptor the descriptor for the target method parameter or field + * @return whether the bean definition qualifies as autowire candidate + */ + boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/AutowireUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/AutowireUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/AutowireUtils.java 17 Aug 2012 15:11:30 -0000 1.1 @@ -0,0 +1,134 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Iterator; +import java.util.Set; + +import org.springframework.core.JdkVersion; +import org.springframework.util.ClassUtils; + +/** + * Utility class that contains various methods useful for + * the implementation of autowire-capable bean factories. + * + * @author Juergen Hoeller + * @author Mark Fisher + * @since 1.1.2 + * @see AbstractAutowireCapableBeanFactory + */ +abstract class AutowireUtils { + + private static final String QUALIFIED_ANNOTATION_AUTOWIRE_CANDIDATE_RESOLVER_CLASS_NAME = + "org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolver"; + + + /** + * Sort the given constructors, preferring public constructors and "greedy" ones + * with a maximum of arguments. The result will contain public constructors first, + * with decreasing number of arguments, then non-public constructors, again with + * decreasing number of arguments. + * @param constructors the constructor array to sort + */ + public static void sortConstructors(Constructor[] constructors) { + Arrays.sort(constructors, new Comparator() { + public int compare(Object o1, Object o2) { + Constructor c1 = (Constructor) o1; + Constructor c2 = (Constructor) o2; + boolean p1 = Modifier.isPublic(c1.getModifiers()); + boolean p2 = Modifier.isPublic(c2.getModifiers()); + if (p1 != p2) { + return (p1 ? -1 : 1); + } + int c1pl = c1.getParameterTypes().length; + int c2pl = c2.getParameterTypes().length; + return (new Integer(c1pl)).compareTo(new Integer(c2pl)) * -1; + } + }); + } + + /** + * Determine whether the given bean property is excluded from dependency checks. + *

    This implementation excludes properties defined by CGLIB. + * @param pd the PropertyDescriptor of the bean property + * @return whether the bean property is excluded + */ + public static boolean isExcludedFromDependencyCheck(PropertyDescriptor pd) { + Method wm = pd.getWriteMethod(); + if (wm == null) { + return false; + } + if (wm.getDeclaringClass().getName().indexOf("$$") == -1) { + // Not a CGLIB method so it's OK. + return false; + } + // It was declared by CGLIB, but we might still want to autowire it + // if it was actually declared by the superclass. + Class superclass = wm.getDeclaringClass().getSuperclass(); + return !ClassUtils.hasMethod(superclass, wm.getName(), wm.getParameterTypes()); + } + + /** + * Return whether the setter method of the given bean property is defined + * in any of the given interfaces. + * @param pd the PropertyDescriptor of the bean property + * @param interfaces the Set of interfaces (Class objects) + * @return whether the setter method is defined by an interface + */ + public static boolean isSetterDefinedInInterface(PropertyDescriptor pd, Set interfaces) { + Method setter = pd.getWriteMethod(); + if (setter != null) { + Class targetClass = setter.getDeclaringClass(); + for (Iterator it = interfaces.iterator(); it.hasNext();) { + Class ifc = (Class) it.next(); + if (ifc.isAssignableFrom(targetClass) && + ClassUtils.hasMethod(ifc, setter.getName(), setter.getParameterTypes())) { + return true; + } + } + } + return false; + } + + /** + * If at least Java 1.5, this will return an annotation-aware resolver. + * Otherwise it returns a resolver that checks the bean definition only. + */ + public static AutowireCandidateResolver createAutowireCandidateResolver() { + if (JdkVersion.isAtLeastJava15()) { + try { + Class resolverClass = ClassUtils.forName( + QUALIFIED_ANNOTATION_AUTOWIRE_CANDIDATE_RESOLVER_CLASS_NAME, AutowireUtils.class.getClassLoader()); + return (AutowireCandidateResolver) resolverClass.newInstance(); + } + catch (Throwable ex) { + throw new IllegalStateException("Unable to load Java 1.5 dependent class [" + + QUALIFIED_ANNOTATION_AUTOWIRE_CANDIDATE_RESOLVER_CLASS_NAME + "]", ex); + } + } + else { + return new SimpleAutowireCandidateResolver(); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionBuilder.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,336 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.PropertyValue; +import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.util.ObjectUtils; + +/** + * Programmatic means of constructing + * {@link org.springframework.beans.factory.config.BeanDefinition BeanDefinitions} + * using the builder pattern. Intended primarily for use when implementing Spring 2.0 + * {@link org.springframework.beans.factory.xml.NamespaceHandler NamespaceHandlers}. + * + * @author Rod Johnson + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public class BeanDefinitionBuilder { + + /** + * Create a new BeanDefinitionBuilder used to construct a {@link GenericBeanDefinition}. + */ + public static BeanDefinitionBuilder genericBeanDefinition() { + BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); + builder.beanDefinition = new GenericBeanDefinition(); + return builder; + } + + /** + * Create a new BeanDefinitionBuilder used to construct a {@link GenericBeanDefinition}. + * @param beanClass the Class of the bean that the definition is being created for + */ + public static BeanDefinitionBuilder genericBeanDefinition(Class beanClass) { + BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); + builder.beanDefinition = new GenericBeanDefinition(); + builder.beanDefinition.setBeanClass(beanClass); + return builder; + } + + /** + * Create a new BeanDefinitionBuilder used to construct a {@link GenericBeanDefinition}. + * @param beanClassName the class name for the bean that the definition is being created for + */ + public static BeanDefinitionBuilder genericBeanDefinition(String beanClassName) { + BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); + builder.beanDefinition = new GenericBeanDefinition(); + builder.beanDefinition.setBeanClassName(beanClassName); + return builder; + } + + /** + * Create a new BeanDefinitionBuilder used to construct a {@link RootBeanDefinition}. + * @param beanClass the Class of the bean that the definition is being created for + */ + public static BeanDefinitionBuilder rootBeanDefinition(Class beanClass) { + return rootBeanDefinition(beanClass, null); + } + + /** + * Create a new BeanDefinitionBuilder used to construct a {@link RootBeanDefinition}. + * @param beanClass the Class of the bean that the definition is being created for + * @param factoryMethodName the name of the method to use to construct the bean instance + */ + public static BeanDefinitionBuilder rootBeanDefinition(Class beanClass, String factoryMethodName) { + BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); + builder.beanDefinition = new RootBeanDefinition(); + builder.beanDefinition.setBeanClass(beanClass); + builder.beanDefinition.setFactoryMethodName(factoryMethodName); + return builder; + } + + /** + * Create a new BeanDefinitionBuilder used to construct a {@link RootBeanDefinition}. + * @param beanClassName the class name for the bean that the definition is being created for + */ + public static BeanDefinitionBuilder rootBeanDefinition(String beanClassName) { + return rootBeanDefinition(beanClassName, null); + } + + /** + * Create a new BeanDefinitionBuilder used to construct a {@link RootBeanDefinition}. + * @param beanClassName the class name for the bean that the definition is being created for + * @param factoryMethodName the name of the method to use to construct the bean instance + */ + public static BeanDefinitionBuilder rootBeanDefinition(String beanClassName, String factoryMethodName) { + BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); + builder.beanDefinition = new RootBeanDefinition(); + builder.beanDefinition.setBeanClassName(beanClassName); + builder.beanDefinition.setFactoryMethodName(factoryMethodName); + return builder; + } + + /** + * Create a new BeanDefinitionBuilder used to construct a {@link ChildBeanDefinition}. + * @param parentName the name of the parent bean + */ + public static BeanDefinitionBuilder childBeanDefinition(String parentName) { + BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); + builder.beanDefinition = new ChildBeanDefinition(parentName); + return builder; + } + + + /** + * The BeanDefinition instance we are creating. + */ + private AbstractBeanDefinition beanDefinition; + + /** + * Our current position with respect to constructor args. + */ + private int constructorArgIndex; + + + /** + * Enforce the use of factory methods. + */ + private BeanDefinitionBuilder() { + } + + /** + * Return the current BeanDefinition object in its raw (unvalidated) form. + * @see #getBeanDefinition() + */ + public AbstractBeanDefinition getRawBeanDefinition() { + return this.beanDefinition; + } + + /** + * Validate and return the created BeanDefinition object. + */ + public AbstractBeanDefinition getBeanDefinition() { + this.beanDefinition.validate(); + return this.beanDefinition; + } + + + /** + * Set the name of the parent definition of this bean definition. + */ + public BeanDefinitionBuilder setParentName(String parentName) { + this.beanDefinition.setParentName(parentName); + return this; + } + + /** + * Set the name of the factory method to use for this definition. + */ + public BeanDefinitionBuilder setFactoryMethod(String factoryMethod) { + this.beanDefinition.setFactoryMethodName(factoryMethod); + return this; + } + + /** + * Set the name of the factory bean to use for this definition. + * @deprecated since Spring 2.5, in favor of preparing this on the + * {@link #getRawBeanDefinition() raw BeanDefinition object} + */ + public BeanDefinitionBuilder setFactoryBean(String factoryBean, String factoryMethod) { + this.beanDefinition.setFactoryBeanName(factoryBean); + this.beanDefinition.setFactoryMethodName(factoryMethod); + return this; + } + + /** + * Add an indexed constructor arg value. The current index is tracked internally + * and all additions are at the present point. + * @deprecated since Spring 2.5, in favor of {@link #addConstructorArgValue} + */ + public BeanDefinitionBuilder addConstructorArg(Object value) { + return addConstructorArgValue(value); + } + + /** + * Add an indexed constructor arg value. The current index is tracked internally + * and all additions are at the present point. + */ + public BeanDefinitionBuilder addConstructorArgValue(Object value) { + this.beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(this.constructorArgIndex++, value); + return this; + } + + /** + * Add a reference to a named bean as a constructor arg. + * @see #addConstructorArgValue(Object) + */ + public BeanDefinitionBuilder addConstructorArgReference(String beanName) { + return addConstructorArgValue(new RuntimeBeanReference(beanName)); + } + + /** + * Add the supplied property value under the given name. + */ + public BeanDefinitionBuilder addPropertyValue(String name, Object value) { + this.beanDefinition.getPropertyValues().addPropertyValue(new PropertyValue(name, value)); + return this; + } + + /** + * Add a reference to the specified bean name under the property specified. + * @param name the name of the property to add the reference to + * @param beanName the name of the bean being referenced + */ + public BeanDefinitionBuilder addPropertyReference(String name, String beanName) { + return addPropertyValue(name, new RuntimeBeanReference(beanName)); + } + + /** + * Set the init method for this definition. + */ + public BeanDefinitionBuilder setInitMethodName(String methodName) { + this.beanDefinition.setInitMethodName(methodName); + return this; + } + + /** + * Set the destroy method for this definition. + */ + public BeanDefinitionBuilder setDestroyMethodName(String methodName) { + this.beanDefinition.setDestroyMethodName(methodName); + return this; + } + + + /** + * Set the scope of this definition. + * @see org.springframework.beans.factory.config.BeanDefinition#SCOPE_SINGLETON + * @see org.springframework.beans.factory.config.BeanDefinition#SCOPE_PROTOTYPE + */ + public BeanDefinitionBuilder setScope(String scope) { + this.beanDefinition.setScope(scope); + return this; + } + + /** + * Set whether or not this definition describes a singleton bean, + * as alternative to {@link #setScope}. + * @deprecated since Spring 2.5, in favor of {@link #setScope} + */ + public BeanDefinitionBuilder setSingleton(boolean singleton) { + this.beanDefinition.setSingleton(singleton); + return this; + } + + /** + * Set whether or not this definition is abstract. + */ + public BeanDefinitionBuilder setAbstract(boolean flag) { + this.beanDefinition.setAbstract(flag); + return this; + } + + /** + * Set whether beans for this definition should be lazily initialized or not. + */ + public BeanDefinitionBuilder setLazyInit(boolean lazy) { + this.beanDefinition.setLazyInit(lazy); + return this; + } + + /** + * Set the autowire mode for this definition. + */ + public BeanDefinitionBuilder setAutowireMode(int autowireMode) { + beanDefinition.setAutowireMode(autowireMode); + return this; + } + + /** + * Set the depency check mode for this definition. + */ + public BeanDefinitionBuilder setDependencyCheck(int dependencyCheck) { + beanDefinition.setDependencyCheck(dependencyCheck); + return this; + } + + /** + * Append the specified bean name to the list of beans that this definition + * depends on. + */ + public BeanDefinitionBuilder addDependsOn(String beanName) { + if (this.beanDefinition.getDependsOn() == null) { + this.beanDefinition.setDependsOn(new String[] {beanName}); + } + else { + String[] added = (String[]) ObjectUtils.addObjectToArray(this.beanDefinition.getDependsOn(), beanName); + this.beanDefinition.setDependsOn(added); + } + return this; + } + + /** + * Set the role of this definition. + */ + public BeanDefinitionBuilder setRole(int role) { + this.beanDefinition.setRole(role); + return this; + } + + /** + * Set the source of this definition. + * @deprecated since Spring 2.5, in favor of preparing this on the + * {@link #getRawBeanDefinition() raw BeanDefinition object} + */ + public BeanDefinitionBuilder setSource(Object source) { + this.beanDefinition.setSource(source); + return this; + } + + /** + * Set the description associated with this definition. + * @deprecated since Spring 2.5, in favor of preparing this on the + * {@link #getRawBeanDefinition() raw BeanDefinition object} + */ + public BeanDefinitionBuilder setResourceDescription(String resourceDescription) { + this.beanDefinition.setResourceDescription(resourceDescription); + return this; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionDefaults.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionDefaults.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionDefaults.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.util.StringUtils; + +/** + * A simple holder for BeanDefinition property defaults. + * + * @author Mark Fisher + * @since 2.5 + */ +public class BeanDefinitionDefaults { + + private boolean lazyInit; + + private int dependencyCheck = AbstractBeanDefinition.DEPENDENCY_CHECK_NONE; + + private int autowireMode = AbstractBeanDefinition.AUTOWIRE_NO; + + private String initMethodName; + + private String destroyMethodName; + + + public void setLazyInit(boolean lazyInit) { + this.lazyInit = lazyInit; + } + + public boolean isLazyInit() { + return this.lazyInit; + } + + public void setDependencyCheck(int dependencyCheck) { + this.dependencyCheck = dependencyCheck; + } + + public int getDependencyCheck() { + return this.dependencyCheck; + } + + public void setAutowireMode(int autowireMode) { + this.autowireMode = autowireMode; + } + + public int getAutowireMode() { + return this.autowireMode; + } + + public void setInitMethodName(String initMethodName) { + this.initMethodName = (StringUtils.hasText(initMethodName)) ? initMethodName : null; + } + + public String getInitMethodName() { + return this.initMethodName; + } + + public void setDestroyMethodName(String destroyMethodName) { + this.destroyMethodName = (StringUtils.hasText(destroyMethodName)) ? destroyMethodName : null; + } + + public String getDestroyMethodName() { + return this.destroyMethodName; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionReader.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,129 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; + +/** + * Simple interface for bean definition readers. + * Specifies load methods with Resource parameters. + * + *

    Concrete bean definition readers can of course add additional + * load and register methods for bean definitions, specific to + * their bean definition format. + * + *

    Note that a bean definition reader does not have to implement + * this interface. It only serves as suggestion for bean definition + * readers that want to follow standard naming conventions. + * + * @author Juergen Hoeller + * @since 1.1 + * @see org.springframework.core.io.Resource + */ +public interface BeanDefinitionReader { + +/** + * Return the bean factory to register the bean definitions with. + *

    The factory is exposed through the BeanDefinitionRegistry interface, + * encapsulating the methods that are relevant for bean definition handling. + * @deprecated in favor of the uniformly named {@link #getRegistry()} + */ + BeanDefinitionRegistry getBeanFactory(); + + /** + * Return the bean factory to register the bean definitions with. + *

    The factory is exposed through the BeanDefinitionRegistry interface, + * encapsulating the methods that are relevant for bean definition handling. + */ + BeanDefinitionRegistry getRegistry(); + + /** + * Return the resource loader to use for resource locations. + * Can be checked for the ResourcePatternResolver interface and cast + * accordingly, for loading multiple resources for a given resource pattern. + *

    Null suggests that absolute resource loading is not available + * for this bean definition reader. + *

    This is mainly meant to be used for importing further resources + * from within a bean definition resource, for example via the "import" + * tag in XML bean definitions. It is recommended, however, to apply + * such imports relative to the defining resource; only explicit full + * resource locations will trigger absolute resource loading. + *

    There is also a loadBeanDefinitions(String) method available, + * for loading bean definitions from a resource location (or location pattern). + * This is a convenience to avoid explicit ResourceLoader handling. + * @see #loadBeanDefinitions(String) + * @see org.springframework.core.io.support.ResourcePatternResolver + */ + ResourceLoader getResourceLoader(); + + /** + * Return the class loader to use for bean classes. + *

    null suggests to not load bean classes eagerly + * but rather to just register bean definitions with class names, + * with the corresponding Classes to be resolved later (or never). + */ + ClassLoader getBeanClassLoader(); + + /** + * Return the BeanNameGenerator to use for anonymous beans + * (without explicit bean name specified). + */ + BeanNameGenerator getBeanNameGenerator(); + + + /** + * Load bean definitions from the specified resource. + * @param resource the resource descriptor + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + */ + int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException; + + /** + * Load bean definitions from the specified resources. + * @param resources the resource descriptors + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + */ + int loadBeanDefinitions(Resource[] resources) throws BeanDefinitionStoreException; + + /** + * Load bean definitions from the specified resource location. + *

    The location can also be a location pattern, provided that the + * ResourceLoader of this bean definition reader is a ResourcePatternResolver. + * @param location the resource location, to be loaded with the ResourceLoader + * (or ResourcePatternResolver) of this bean definition reader + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + * @see #getResourceLoader() + * @see #loadBeanDefinitions(org.springframework.core.io.Resource) + * @see #loadBeanDefinitions(org.springframework.core.io.Resource[]) + */ + int loadBeanDefinitions(String location) throws BeanDefinitionStoreException; + + /** + * Load bean definitions from the specified resource locations. + * @param locations the resource locations, to be loaded with the ResourceLoader + * (or ResourcePatternResolver) of this bean definition reader + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + */ + int loadBeanDefinitions(String[] locations) throws BeanDefinitionStoreException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,203 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.config.ConstructorArgumentValues; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +/** + * Utility methods that are useful for bean definition reader implementations. + * Mainly intended for internal use. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @since 1.1 + * @see PropertiesBeanDefinitionReader + * @see org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader + */ +public class BeanDefinitionReaderUtils { + + /** + * Separator for generated bean names. If a class name or parent name is not + * unique, "#1", "#2" etc will be appended, until the name becomes unique. + */ + public static final String GENERATED_BEAN_NAME_SEPARATOR = BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR; + + + /** + * Create a new GenericBeanDefinition for the given + * class name, parent, constructor arguments, and property values. + * @param className the name of the bean class, if any + * @param parentName the name of the parent bean, if any + * @param cargs the constructor arguments, if any + * @param pvs the property values, if any + * @param classLoader the ClassLoader to use for loading bean classes + * (can be null to just register bean classes by name) + * @return the bean definition + * @throws ClassNotFoundException if the bean class could not be loaded + * @deprecated in favor of createBeanDefinition(String, String, ClassLoader) + * @see #createBeanDefinition(String, String, ClassLoader) + */ + public static AbstractBeanDefinition createBeanDefinition( + String className, String parentName, ConstructorArgumentValues cargs, + MutablePropertyValues pvs, ClassLoader classLoader) throws ClassNotFoundException { + + AbstractBeanDefinition bd = createBeanDefinition(parentName, className, classLoader); + bd.setConstructorArgumentValues(cargs); + bd.setPropertyValues(pvs); + return bd; + } + + /** + * Create a new GenericBeanDefinition for the given parent name and class name, + * eagerly loading the bean class if a ClassLoader has been specified. + * @param parentName the name of the parent bean, if any + * @param className the name of the bean class, if any + * @param classLoader the ClassLoader to use for loading bean classes + * (can be null to just register bean classes by name) + * @return the bean definition + * @throws ClassNotFoundException if the bean class could not be loaded + */ + public static AbstractBeanDefinition createBeanDefinition( + String parentName, String className, ClassLoader classLoader) throws ClassNotFoundException { + + GenericBeanDefinition bd = new GenericBeanDefinition(); + bd.setParentName(parentName); + if (className != null) { + if (classLoader != null) { + bd.setBeanClass(ClassUtils.forName(className, classLoader)); + } + else { + bd.setBeanClassName(className); + } + } + return bd; + } + + /** + * Generate a bean name for the given bean definition, unique within the + * given bean factory. + * @param definition the bean definition to generate a bean name for + * @param registry the bean factory that the definition is going to be + * registered with (to check for existing bean names) + * @param isInnerBean whether the given bean definition will be registered + * as inner bean or as top-level bean (allowing for special name generation + * for inner beans versus top-level beans) + * @return the generated bean name + * @throws BeanDefinitionStoreException if no unique name can be generated + * for the given bean definition + */ + public static String generateBeanName( + BeanDefinition definition, BeanDefinitionRegistry registry, boolean isInnerBean) + throws BeanDefinitionStoreException { + + String generatedBeanName = definition.getBeanClassName(); + if (generatedBeanName == null) { + if (definition.getParentName() != null) { + generatedBeanName = definition.getParentName() + "$child"; + } + else if (definition.getFactoryBeanName() != null) { + generatedBeanName = definition.getFactoryBeanName() + "$created"; + } + } + if (!StringUtils.hasText(generatedBeanName)) { + throw new BeanDefinitionStoreException("Unnamed bean definition specifies neither " + + "'class' nor 'parent' nor 'factory-bean' - can't generate bean name"); + } + + String id = generatedBeanName; + if (isInnerBean) { + // Inner bean: generate identity hashcode suffix. + id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + ObjectUtils.getIdentityHexString(definition); + } + else { + // Top-level bean: use plain class name. + // Increase counter until the id is unique. + int counter = -1; + while (counter == -1 || registry.containsBeanDefinition(id)) { + counter++; + id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + counter; + } + } + return id; + } + + /** + * Generate a bean name for the given top-level bean definition, + * unique within the given bean factory. + * @param beanDefinition the bean definition to generate a bean name for + * @param registry the bean factory that the definition is going to be + * registered with (to check for existing bean names) + * @return the generated bean name + * @throws BeanDefinitionStoreException if no unique name can be generated + * for the given bean definition + */ + public static String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry registry) + throws BeanDefinitionStoreException { + + return generateBeanName(beanDefinition, registry, false); + } + + /** + * Register the given bean definition with the given bean factory. + * @param definitionHolder the bean definition including name and aliases + * @param registry the bean factory to register with + * @throws BeanDefinitionStoreException if registration failed + */ + public static void registerBeanDefinition( + BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) + throws BeanDefinitionStoreException { + + // Register bean definition under primary name. + String beanName = definitionHolder.getBeanName(); + registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); + + // Register aliases for bean name, if any. + String[] aliases = definitionHolder.getAliases(); + if (aliases != null) { + for (int i = 0; i < aliases.length; i++) { + registry.registerAlias(beanName, aliases[i]); + } + } + } + + /** + * Register the given bean definition with a generated name, + * unique within the given bean factory. + * @param definition the bean definition to generate a bean name for + * @param registry the bean factory to register with + * @return the generated bean name + * @throws BeanDefinitionStoreException if no unique name can be generated + * for the given bean definition or the definition cannot be registered + */ + public static String registerWithGeneratedName( + AbstractBeanDefinition definition, BeanDefinitionRegistry registry) + throws BeanDefinitionStoreException { + + String generatedName = generateBeanName(definition, registry, false); + registry.registerBeanDefinition(generatedName, definition); + return generatedName; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionRegistry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionRegistry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionRegistry.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,107 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.core.AliasRegistry; + +/** + * Interface for registries that hold bean definitions, for example RootBeanDefinition + * and ChildBeanDefinition instances. Typically implemented by BeanFactories that + * internally work with the AbstractBeanDefinition hierarchy. + * + *

    This is the only interface in Spring's bean factory packages that encapsulates + * registration of bean definitions. The standard BeanFactory interfaces + * only cover access to a fully configured factory instance. + * + *

    Spring's bean definition readers expect to work on an implementation of this + * interface. Known implementors within the Spring core are DefaultListableBeanFactory + * and GenericApplicationContext. + * + * @author Juergen Hoeller + * @since 26.11.2003 + * @see org.springframework.beans.factory.config.BeanDefinition + * @see AbstractBeanDefinition + * @see RootBeanDefinition + * @see ChildBeanDefinition + * @see DefaultListableBeanFactory + * @see org.springframework.context.support.GenericApplicationContext + * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader + * @see PropertiesBeanDefinitionReader + */ +public interface BeanDefinitionRegistry extends AliasRegistry { + + /** + * Register a new bean definition with this registry. + * Must support RootBeanDefinition and ChildBeanDefinition. + * @param beanName the name of the bean instance to register + * @param beanDefinition definition of the bean instance to register + * @throws BeanDefinitionStoreException if the BeanDefinition is invalid + * or if there is already a BeanDefinition for the specified bean name + * (and we are not allowed to override it) + * @see RootBeanDefinition + * @see ChildBeanDefinition + */ + void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) + throws BeanDefinitionStoreException; + + /** + * Remove the BeanDefinition for the given name. + * @param beanName the name of the bean instance to register + * @throws NoSuchBeanDefinitionException if there is no such bean definition + */ + void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; + + /** + * Return the BeanDefinition for the given bean name. + * @param beanName name of the bean to find a definition for + * @return the BeanDefinition for the given name (never null) + * @throws NoSuchBeanDefinitionException if there is no such bean definition + */ + BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; + + /** + * Check if this registry contains a bean definition with the given name. + * @param beanName the name of the bean to look for + * @return if this registry contains a bean definition with the given name + */ + boolean containsBeanDefinition(String beanName); + + /** + * Return the names of all beans defined in this registry. + * @return the names of all beans defined in this registry, + * or an empty array if none defined + */ + String[] getBeanDefinitionNames(); + + /** + * Return the number of beans defined in the registry. + * @return the number of beans defined in the registry + */ + int getBeanDefinitionCount(); + + /** + * Determine whether the given bean name is already in use within this registry, + * i.e. whether there is a local bean or alias registered under this name. + * @param beanName the name to check + * @return whether the given bean name is already in use + */ + boolean isBeanNameInUse(String beanName); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionResource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionResource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionResource.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,91 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.core.io.AbstractResource; +import org.springframework.util.Assert; + +/** + * Descriptive {@link org.springframework.core.io.Resource} wrapper for + * a {@link org.springframework.beans.factory.config.BeanDefinition}. + * + * @author Juergen Hoeller + * @since 2.5.2 + * @see org.springframework.core.io.DescriptiveResource + */ +class BeanDefinitionResource extends AbstractResource { + + private final BeanDefinition beanDefinition; + + + /** + * Create a new BeanDefinitionResource. + * @param beanDefinition the BeanDefinition objectto wrap + */ + public BeanDefinitionResource(BeanDefinition beanDefinition) { + Assert.notNull(beanDefinition, "BeanDefinition must not be null"); + this.beanDefinition = beanDefinition; + } + + /** + * Return the wrapped BeanDefinition object. + */ + public final BeanDefinition getBeanDefinition() { + return this.beanDefinition; + } + + + public boolean exists() { + return false; + } + + public boolean isReadable() { + return false; + } + + public InputStream getInputStream() throws IOException { + throw new FileNotFoundException( + "Resource cannot be opened because it points to " + getDescription()); + } + + public String getDescription() { + return "BeanDefinition defined in " + this.beanDefinition.getResourceDescription(); + } + + + /** + * This implementation compares the underlying BeanDefinition. + */ + public boolean equals(Object obj) { + return (obj == this || + (obj instanceof BeanDefinitionResource && + ((BeanDefinitionResource) obj).beanDefinition.equals(this.beanDefinition))); + } + + /** + * This implementation returns the hash code of the underlying BeanDefinition. + */ + public int hashCode() { + return this.beanDefinition.hashCode(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionValidationException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionValidationException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionValidationException.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.FatalBeanException; + +/** + * Exception thrown when the validation of a bean definition failed. + * + * @author Juergen Hoeller + * @since 21.11.2003 + * @see AbstractBeanDefinition#validate() + */ +public class BeanDefinitionValidationException extends FatalBeanException { + + /** + * Create a new BeanDefinitionValidationException with the specified message. + * @param msg the detail message + */ + public BeanDefinitionValidationException(String msg) { + super(msg); + } + + /** + * Create a new BeanDefinitionValidationException with the specified message + * and root cause. + * @param msg the detail message + * @param cause the root cause + */ + public BeanDefinitionValidationException(String msg, Throwable cause) { + super(msg, cause); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanDefinitionValueResolver.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,328 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.springframework.beans.BeanWrapper; +import org.springframework.beans.BeansException; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.config.RuntimeBeanNameReference; +import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.beans.factory.config.TypedStringValue; + +/** + * Helper class for use in bean factory implementations, + * resolving values contained in bean definition objects + * into the actual values applied to the target bean instance. + * + *

    Operates on an {@link AbstractBeanFactory} and a plain + * {@link org.springframework.beans.factory.config.BeanDefinition} object. + * Used by {@link AbstractAutowireCapableBeanFactory}. + * + * @author Juergen Hoeller + * @since 1.2 + * @see AbstractAutowireCapableBeanFactory + */ +class BeanDefinitionValueResolver { + + private final AbstractBeanFactory beanFactory; + + private final String beanName; + + private final BeanDefinition beanDefinition; + + private final TypeConverter typeConverter; + + + /** + * Create a BeanDefinitionValueResolver for the given BeanFactory and BeanDefinition. + * @param beanFactory the BeanFactory to resolve against + * @param beanName the name of the bean that we work on + * @param beanDefinition the BeanDefinition of the bean that we work on + * @param typeConverter the TypeConverter to use for resolving TypedStringValues + */ + public BeanDefinitionValueResolver( + AbstractBeanFactory beanFactory, String beanName, BeanDefinition beanDefinition, TypeConverter typeConverter) { + + this.beanFactory = beanFactory; + this.beanName = beanName; + this.beanDefinition = beanDefinition; + this.typeConverter = typeConverter; + } + + /** + * Given a PropertyValue, return a value, resolving any references to other + * beans in the factory if necessary. The value could be: + *

  • A BeanDefinition, which leads to the creation of a corresponding + * new bean instance. Singleton flags and names of such "inner beans" + * are always ignored: Inner beans are anonymous prototypes. + *
  • A RuntimeBeanReference, which must be resolved. + *
  • A ManagedList. This is a special collection that may contain + * RuntimeBeanReferences or Collections that will need to be resolved. + *
  • A ManagedSet. May also contain RuntimeBeanReferences or + * Collections that will need to be resolved. + *
  • A ManagedMap. In this case the value may be a RuntimeBeanReference + * or Collection that will need to be resolved. + *
  • An ordinary object or null, in which case it's left alone. + * @param argName the name of the argument that the value is defined for + * @param value the value object to resolve + * @return the resolved object + */ + public Object resolveValueIfNecessary(Object argName, Object value) { + // We must check each value to see whether it requires a runtime reference + // to another bean to be resolved. + if (value instanceof RuntimeBeanReference) { + RuntimeBeanReference ref = (RuntimeBeanReference) value; + return resolveReference(argName, ref); + } + else if (value instanceof RuntimeBeanNameReference) { + String ref = ((RuntimeBeanNameReference) value).getBeanName(); + if (!this.beanFactory.containsBean(ref)) { + throw new BeanDefinitionStoreException( + "Invalid bean name '" + ref + "' in bean reference for " + argName); + } + return ref; + } + else if (value instanceof BeanDefinitionHolder) { + // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases. + BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value; + return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition()); + } + else if (value instanceof BeanDefinition) { + // Resolve plain BeanDefinition, without contained name: use dummy name. + BeanDefinition bd = (BeanDefinition) value; + return resolveInnerBean(argName, "(inner bean)", bd); + } + else if (value instanceof ManagedList) { + // May need to resolve contained runtime references. + return resolveManagedList(argName, (List) value); + } + else if (value instanceof ManagedSet) { + // May need to resolve contained runtime references. + return resolveManagedSet(argName, (Set) value); + } + else if (value instanceof ManagedMap) { + // May need to resolve contained runtime references. + return resolveManagedMap(argName, (Map) value); + } + else if (value instanceof ManagedProperties) { + Properties original = (Properties) value; + Properties copy = new Properties(); + for (Iterator it = original.entrySet().iterator(); it.hasNext();) { + Map.Entry propEntry = (Map.Entry) it.next(); + Object propKey = propEntry.getKey(); + Object propValue = propEntry.getValue(); + if (propKey instanceof TypedStringValue) { + propKey = ((TypedStringValue) propKey).getValue(); + } + if (propValue instanceof TypedStringValue) { + propValue = ((TypedStringValue) propValue).getValue(); + } + copy.put(propKey, propValue); + } + return copy; + } + else if (value instanceof TypedStringValue) { + // Convert value to target type here. + TypedStringValue typedStringValue = (TypedStringValue) value; + try { + Class resolvedTargetType = resolveTargetType(typedStringValue); + if (resolvedTargetType != null) { + return this.typeConverter.convertIfNecessary(typedStringValue.getValue(), resolvedTargetType); + } + else { + // No target type specified - no conversion necessary... + return typedStringValue.getValue(); + } + } + catch (Throwable ex) { + // Improve the message by showing the context. + throw new BeanCreationException( + this.beanDefinition.getResourceDescription(), this.beanName, + "Error converting typed String value for " + argName, ex); + } + } + else { + // No need to resolve value... + return value; + } + } + + /** + * Resolve the target type in the given TypedStringValue. + * @param value the TypedStringValue to resolve + * @return the resolved target type (or null if none specified) + * @throws ClassNotFoundException if the specified type cannot be resolved + * @see TypedStringValue#resolveTargetType + */ + protected Class resolveTargetType(TypedStringValue value) throws ClassNotFoundException { + if (value.hasTargetType()) { + return value.getTargetType(); + } + return value.resolveTargetType(this.beanFactory.getBeanClassLoader()); + } + + /** + * Resolve an inner bean definition. + * @param argName the name of the argument that the inner bean is defined for + * @param innerBeanName the name of the inner bean + * @param innerBd the bean definition for the inner bean + * @return the resolved inner bean instance + */ + private Object resolveInnerBean(Object argName, String innerBeanName, BeanDefinition innerBd) { + RootBeanDefinition mbd = null; + try { + mbd = this.beanFactory.getMergedBeanDefinition(innerBeanName, innerBd, this.beanDefinition); + // Check given bean name whether it is unique. If not already unique, + // add counter - increasing the counter until the name is unique. + String actualInnerBeanName = innerBeanName; + if (mbd.isSingleton()) { + actualInnerBeanName = adaptInnerBeanName(innerBeanName); + } + // Guarantee initialization of beans that the inner bean depends on. + String[] dependsOn = mbd.getDependsOn(); + if (dependsOn != null) { + for (int i = 0; i < dependsOn.length; i++) { + String dependsOnBean = dependsOn[i]; + this.beanFactory.getBean(dependsOnBean); + this.beanFactory.registerDependentBean(dependsOnBean, actualInnerBeanName); + } + } + Object innerBean = this.beanFactory.createBean(actualInnerBeanName, mbd, null); + this.beanFactory.registerContainedBean(actualInnerBeanName, this.beanName); + if (innerBean instanceof FactoryBean) { + boolean synthetic = (mbd != null && mbd.isSynthetic()); + return this.beanFactory.getObjectFromFactoryBean((FactoryBean) innerBean, actualInnerBeanName, !synthetic); + } + else { + return innerBean; + } + } + catch (BeansException ex) { + throw new BeanCreationException( + this.beanDefinition.getResourceDescription(), this.beanName, + "Cannot create inner bean '" + innerBeanName + "' " + + (mbd != null && mbd.getBeanClassName() != null ? "of type [" + mbd.getBeanClassName() + "] " : "") + + "while setting " + argName, ex); + } + } + + /** + * Checks the given bean name whether it is unique. If not already unique, + * a counter is added, increasing the counter until the name is unique. + * @param innerBeanName the original name for the inner bean + * @return the adapted name for the inner bean + */ + private String adaptInnerBeanName(String innerBeanName) { + String actualInnerBeanName = innerBeanName; + int counter = 0; + while (this.beanFactory.isBeanNameInUse(actualInnerBeanName)) { + counter++; + actualInnerBeanName = innerBeanName + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR + counter; + } + return actualInnerBeanName; + } + + /** + * Resolve a reference to another bean in the factory. + */ + private Object resolveReference(Object argName, RuntimeBeanReference ref) { + try { + if (ref.isToParent()) { + if (this.beanFactory.getParentBeanFactory() == null) { + throw new BeanCreationException( + this.beanDefinition.getResourceDescription(), this.beanName, + "Can't resolve reference to bean '" + ref.getBeanName() + + "' in parent factory: no parent factory available"); + } + return this.beanFactory.getParentBeanFactory().getBean(ref.getBeanName()); + } + else { + Object bean = this.beanFactory.getBean(ref.getBeanName()); + this.beanFactory.registerDependentBean(ref.getBeanName(), this.beanName); + return bean; + } + } + catch (BeansException ex) { + throw new BeanCreationException( + this.beanDefinition.getResourceDescription(), this.beanName, + "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex); + } + } + + /** + * For each element in the ManagedList, resolve reference if necessary. + */ + private List resolveManagedList(Object argName, List ml) { + List resolved = new ArrayList(ml.size()); + for (int i = 0; i < ml.size(); i++) { + resolved.add( + resolveValueIfNecessary( + argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX, + ml.get(i))); + } + return resolved; + } + + /** + * For each element in the ManagedList, resolve reference if necessary. + */ + private Set resolveManagedSet(Object argName, Set ms) { + Set resolved = new LinkedHashSet(ms.size()); + int i = 0; + for (Iterator it = ms.iterator(); it.hasNext();) { + resolved.add( + resolveValueIfNecessary( + argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + i + BeanWrapper.PROPERTY_KEY_SUFFIX, + it.next())); + i++; + } + return resolved; + } + + /** + * For each element in the ManagedMap, resolve reference if necessary. + */ + private Map resolveManagedMap(Object argName, Map mm) { + Map resolved = new LinkedHashMap(mm.size()); + Iterator it = mm.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + Object resolvedKey = resolveValueIfNecessary(argName, entry.getKey()); + Object resolvedValue = resolveValueIfNecessary( + argName + " with key " + BeanWrapper.PROPERTY_KEY_PREFIX + entry.getKey() + BeanWrapper.PROPERTY_KEY_SUFFIX, + entry.getValue()); + resolved.put(resolvedKey, resolvedValue); + } + return resolved; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanNameGenerator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/BeanNameGenerator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/BeanNameGenerator.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.factory.config.BeanDefinition; + +/** + * Strategy interface for generating bean names for bean definitions. + * + * @author Juergen Hoeller + * @since 2.0.3 + */ +public interface BeanNameGenerator { + + /** + * Generate a bean name for the given bean definition. + * @param definition the bean definition to generate a name for + * @param registry the bean definition registry that the given definition + * is supposed to be registered with + * @return the generated bean name + */ + String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,201 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; + +import net.sf.cglib.proxy.Callback; +import net.sf.cglib.proxy.CallbackFilter; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.MethodProxy; +import net.sf.cglib.proxy.NoOp; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.factory.BeanFactory; + +/** + * Default object instantiation strategy for use in BeanFactories. + * Uses CGLIB to generate subclasses dynamically if methods need to be + * overridden by the container, to implement Method Injection. + * + *

    Using Method Injection features requires CGLIB on the classpath. + * However, the core IoC container will still run without CGLIB being available. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 1.1 + */ +public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy { + + /** + * Index in the CGLIB callback array for passthrough behavior, + * in which case the subclass won't override the original class. + */ + private static final int PASSTHROUGH = 0; + + /** + * Index in the CGLIB callback array for a method that should + * be overridden to provide method lookup. + */ + private static final int LOOKUP_OVERRIDE = 1; + + /** + * Index in the CGLIB callback array for a method that should + * be overridden using generic Methodreplacer functionality. + */ + private static final int METHOD_REPLACER = 2; + + + protected Object instantiateWithMethodInjection( + RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { + + // Must generate CGLIB subclass. + return new CglibSubclassCreator(beanDefinition, owner).instantiate(null, null); + } + + protected Object instantiateWithMethodInjection( + RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, + Constructor ctor, Object[] args) { + + return new CglibSubclassCreator(beanDefinition, owner).instantiate(ctor, args); + } + + + /** + * An inner class so we don't have a CGLIB dependency in core. + */ + private static class CglibSubclassCreator { + + private static final Log logger = LogFactory.getLog(CglibSubclassCreator.class); + + private final RootBeanDefinition beanDefinition; + + private final BeanFactory owner; + + public CglibSubclassCreator(RootBeanDefinition beanDefinition, BeanFactory owner) { + this.beanDefinition = beanDefinition; + this.owner = owner; + } + + /** + * Create a new instance of a dynamically generated subclasses implementing the + * required lookups. + * @param ctor constructor to use. If this is null, use the + * no-arg constructor (no parameterization, or Setter Injection) + * @param args arguments to use for the constructor. + * Ignored if the ctor parameter is null. + * @return new instance of the dynamically generated class + */ + public Object instantiate(Constructor ctor, Object[] args) { + Enhancer enhancer = new Enhancer(); + enhancer.setSuperclass(this.beanDefinition.getBeanClass()); + enhancer.setCallbackFilter(new CallbackFilterImpl()); + enhancer.setCallbacks(new Callback[] { + NoOp.INSTANCE, + new LookupOverrideMethodInterceptor(), + new ReplaceOverrideMethodInterceptor() + }); + + return (ctor == null) ? + enhancer.create() : + enhancer.create(ctor.getParameterTypes(), args); + } + + + /** + * Class providing hashCode and equals methods required by CGLIB to + * ensure that CGLIB doesn't generate a distinct class per bean. + * Identity is based on class and bean definition. + */ + private class CglibIdentitySupport { + + /** + * Exposed for equals method to allow access to enclosing class field + */ + protected RootBeanDefinition getBeanDefinition() { + return beanDefinition; + } + + public boolean equals(Object other) { + return (other.getClass().equals(getClass()) && + ((CglibIdentitySupport) other).getBeanDefinition().equals(beanDefinition)); + } + + public int hashCode() { + return beanDefinition.hashCode(); + } + } + + + /** + * CGLIB MethodInterceptor to override methods, replacing them with an + * implementation that returns a bean looked up in the container. + */ + private class LookupOverrideMethodInterceptor extends CglibIdentitySupport implements MethodInterceptor { + + public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable { + // Cast is safe, as CallbackFilter filters are used selectively. + LookupOverride lo = (LookupOverride) beanDefinition.getMethodOverrides().getOverride(method); + return owner.getBean(lo.getBeanName()); + } + } + + + /** + * CGLIB MethodInterceptor to override methods, replacing them with a call + * to a generic MethodReplacer. + */ + private class ReplaceOverrideMethodInterceptor extends CglibIdentitySupport implements MethodInterceptor { + + public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable { + ReplaceOverride ro = (ReplaceOverride) beanDefinition.getMethodOverrides().getOverride(method); + // TODO could cache if a singleton for minor performance optimization + MethodReplacer mr = (MethodReplacer) owner.getBean(ro.getMethodReplacerBeanName()); + return mr.reimplement(obj, method, args); + } + } + + + /** + * CGLIB object to filter method interception behavior. + */ + private class CallbackFilterImpl extends CglibIdentitySupport implements CallbackFilter { + + public int accept(Method method) { + MethodOverride methodOverride = beanDefinition.getMethodOverrides().getOverride(method); + if (logger.isTraceEnabled()) { + logger.trace("Override for '" + method.getName() + "' is [" + methodOverride + "]"); + } + if (methodOverride == null) { + return PASSTHROUGH; + } + else if (methodOverride instanceof LookupOverride) { + return LOOKUP_OVERRIDE; + } + else if (methodOverride instanceof ReplaceOverride) { + return METHOD_REPLACER; + } + throw new UnsupportedOperationException( + "Unexpected MethodOverride subclass: " + methodOverride.getClass().getName()); + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/ChildBeanDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/ChildBeanDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/ChildBeanDefinition.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,175 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConstructorArgumentValues; +import org.springframework.util.ObjectUtils; + +/** + * Bean definition for beans which inherit settings from their parent. + * Child bean definitions have a fixed dependency on a parent bean definition. + * + *

    A child bean definition will inherit constructor argument values, + * property values and method overrides from the parent, with the option + * to add new values. If init method, destroy method and/or static factory + * method are specified, they will override the corresponding parent settings. + * The remaining settings will always be taken from the child definition: + * depends on, autowire mode, dependency check, singleton, lazy init. + * + *

    NOTE: Since Spring 2.5, the preferred way to register bean + * definitions programmatically is the {@link GenericBeanDefinition} class, + * which allows to dynamically define parent dependencies through the + * {@link GenericBeanDefinition#setParentName} method. This effectively + * supersedes the ChildBeanDefinition class for most use cases. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see GenericBeanDefinition + * @see RootBeanDefinition + */ +public class ChildBeanDefinition extends AbstractBeanDefinition { + + private String parentName; + + + /** + * Create a new ChildBeanDefinition for the given parent, to be + * configured through its bean properties and configuration methods. + * @param parentName the name of the parent bean + * @see #setBeanClass + * @see #setBeanClassName + * @see #setScope + * @see #setAutowireMode + * @see #setDependencyCheck + * @see #setConstructorArgumentValues + * @see #setPropertyValues + */ + public ChildBeanDefinition(String parentName) { + super(); + this.parentName = parentName; + } + + /** + * Create a new ChildBeanDefinition for the given parent. + * @param parentName the name of the parent bean + * @param pvs the additional property values of the child + */ + public ChildBeanDefinition(String parentName, MutablePropertyValues pvs) { + super(null, pvs); + this.parentName = parentName; + } + + /** + * Create a new ChildBeanDefinition for the given parent. + * @param parentName the name of the parent bean + * @param cargs the constructor argument values to apply + * @param pvs the additional property values of the child + */ + public ChildBeanDefinition( + String parentName, ConstructorArgumentValues cargs, MutablePropertyValues pvs) { + + super(cargs, pvs); + this.parentName = parentName; + } + + /** + * Create a new ChildBeanDefinition for the given parent, + * providing constructor arguments and property values. + * @param parentName the name of the parent bean + * @param beanClass the class of the bean to instantiate + * @param cargs the constructor argument values to apply + * @param pvs the property values to apply + */ + public ChildBeanDefinition( + String parentName, Class beanClass, ConstructorArgumentValues cargs, MutablePropertyValues pvs) { + + super(cargs, pvs); + this.parentName = parentName; + setBeanClass(beanClass); + } + + /** + * Create a new ChildBeanDefinition for the given parent, + * providing constructor arguments and property values. + * Takes a bean class name to avoid eager loading of the bean class. + * @param parentName the name of the parent bean + * @param beanClassName the name of the class to instantiate + * @param cargs the constructor argument values to apply + * @param pvs the property values to apply + */ + public ChildBeanDefinition( + String parentName, String beanClassName, ConstructorArgumentValues cargs, MutablePropertyValues pvs) { + + super(cargs, pvs); + this.parentName = parentName; + setBeanClassName(beanClassName); + } + + /** + * Create a new ChildBeanDefinition as deep copy of the given + * bean definition. + * @param original the original bean definition to copy from + */ + public ChildBeanDefinition(ChildBeanDefinition original) { + super((BeanDefinition) original); + } + + + public void setParentName(String parentName) { + this.parentName = parentName; + } + + public String getParentName() { + return this.parentName; + } + + public void validate() throws BeanDefinitionValidationException { + super.validate(); + if (this.parentName == null) { + throw new BeanDefinitionValidationException("'parentName' must be set in ChildBeanDefinition"); + } + } + + + public AbstractBeanDefinition cloneBeanDefinition() { + return new ChildBeanDefinition(this); + } + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof ChildBeanDefinition)) { + return false; + } + ChildBeanDefinition that = (ChildBeanDefinition) other; + return (ObjectUtils.nullSafeEquals(this.parentName, that.parentName) && super.equals(other)); + } + + public int hashCode() { + return ObjectUtils.nullSafeHashCode(this.parentName) * 29 + super.hashCode(); + } + + public String toString() { + StringBuffer sb = new StringBuffer("Child bean with parent '"); + sb.append(this.parentName).append("': ").append(super.toString()); + return sb.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/ConstructorResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/ConstructorResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/ConstructorResolver.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,668 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.beans.BeanWrapper; +import org.springframework.beans.BeanWrapperImpl; +import org.springframework.beans.BeansException; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.TypeMismatchException; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.UnsatisfiedDependencyException; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.beans.factory.config.ConstructorArgumentValues; +import org.springframework.beans.factory.config.DependencyDescriptor; +import org.springframework.beans.factory.config.TypedStringValue; +import org.springframework.core.GenericTypeResolver; +import org.springframework.core.JdkVersion; +import org.springframework.core.MethodParameter; +import org.springframework.util.MethodInvoker; +import org.springframework.util.ObjectUtils; +import org.springframework.util.ReflectionUtils; + +/** + * Helper class for resolving constructors and factory methods. + * Performs constructor resolution through argument matching. + * + *

    Operates on an {@link AbstractBeanFactory} and an {@link InstantiationStrategy}. + * Used by {@link AbstractAutowireCapableBeanFactory}. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @author Mark Fisher + * @since 2.0 + * @see #autowireConstructor + * @see #instantiateUsingFactoryMethod + * @see AbstractAutowireCapableBeanFactory + */ +class ConstructorResolver { + + private final AbstractBeanFactory beanFactory; + + private final AutowireCapableBeanFactory autowireFactory; + + private final InstantiationStrategy instantiationStrategy; + + private final TypeConverter typeConverter; + + + /** + * Create a new ConstructorResolver for the given factory and instantiation strategy. + * @param beanFactory the BeanFactory to work with + * @param autowireFactory the BeanFactory as AutowireCapableBeanFactory + * @param instantiationStrategy the instantiate strategy for creating bean instances + * @param typeConverter the TypeConverter to use (or null for using the default) + */ + public ConstructorResolver(AbstractBeanFactory beanFactory, AutowireCapableBeanFactory autowireFactory, + InstantiationStrategy instantiationStrategy, TypeConverter typeConverter) { + + this.beanFactory = beanFactory; + this.autowireFactory = autowireFactory; + this.instantiationStrategy = instantiationStrategy; + this.typeConverter = typeConverter; + } + + + /** + * "autowire constructor" (with constructor arguments by type) behavior. + * Also applied if explicit constructor argument values are specified, + * matching all remaining arguments with beans from the bean factory. + *

    This corresponds to constructor injection: In this mode, a Spring + * bean factory is able to host components that expect constructor-based + * dependency resolution. + * @param beanName the name of the bean + * @param mbd the merged bean definition for the bean + * @param chosenCtors chosen candidate constructors (or null if none) + * @param explicitArgs argument values passed in programmatically via the getBean method, + * or null if none (-> use constructor argument values from bean definition) + * @return a BeanWrapper for the new instance + */ + protected BeanWrapper autowireConstructor( + String beanName, RootBeanDefinition mbd, Constructor[] chosenCtors, Object[] explicitArgs) { + + BeanWrapperImpl bw = new BeanWrapperImpl(); + this.beanFactory.initBeanWrapper(bw); + + Constructor constructorToUse = null; + Object[] argsToUse = null; + + if (explicitArgs != null) { + argsToUse = explicitArgs; + } + else { + constructorToUse = (Constructor) mbd.resolvedConstructorOrFactoryMethod; + if (constructorToUse != null) { + // Found a cached constructor... + argsToUse = mbd.resolvedConstructorArguments; + if (argsToUse == null) { + Class[] paramTypes = constructorToUse.getParameterTypes(); + Object[] argsToResolve = mbd.preparedConstructorArguments; + TypeConverter converter = (this.typeConverter != null ? this.typeConverter : bw); + BeanDefinitionValueResolver valueResolver = + new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter); + argsToUse = new Object[argsToResolve.length]; + for (int i = 0; i < argsToResolve.length; i++) { + Object argValue = argsToResolve[i]; + MethodParameter methodParam = new MethodParameter(constructorToUse, i); + if (JdkVersion.isAtLeastJava15()) { + GenericTypeResolver.resolveParameterType(methodParam, constructorToUse.getDeclaringClass()); + } + if (argValue instanceof AutowiredArgumentMarker) { + argValue = resolveAutowiredArgument(methodParam, beanName, null, converter); + } + else if (argValue instanceof BeanMetadataElement) { + argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue); + } + argsToUse[i] = converter.convertIfNecessary(argValue, paramTypes[i], methodParam); + } + } + } + } + + if (constructorToUse == null) { + // Need to resolve the constructor. + boolean autowiring = (chosenCtors != null || + mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR); + ConstructorArgumentValues resolvedValues = null; + + int minNrOfArgs = 0; + if (explicitArgs != null) { + minNrOfArgs = explicitArgs.length; + } + else { + ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues(); + resolvedValues = new ConstructorArgumentValues(); + minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues); + } + + // Take specified constructors, if any. + Constructor[] candidates = + (chosenCtors != null ? chosenCtors : mbd.getBeanClass().getDeclaredConstructors()); + AutowireUtils.sortConstructors(candidates); + int minTypeDiffWeight = Integer.MAX_VALUE; + + for (int i = 0; i < candidates.length; i++) { + Constructor candidate = candidates[i]; + Class[] paramTypes = candidate.getParameterTypes(); + + if (constructorToUse != null && argsToUse.length > paramTypes.length) { + // Already found greedy constructor that can be satisfied -> + // do not look any further, there are only less greedy constructors left. + break; + } + if (paramTypes.length < minNrOfArgs) { + throw new BeanCreationException(mbd.getResourceDescription(), beanName, + minNrOfArgs + " constructor arguments specified but no matching constructor found in bean '" + + beanName + "' " + + "(hint: specify index and/or type arguments for simple parameters to avoid type ambiguities)"); + } + + ArgumentsHolder args = null; + List causes = null; + + if (resolvedValues != null) { + // Try to resolve arguments for current constructor. + try { + args = createArgumentArray( + beanName, mbd, resolvedValues, bw, paramTypes, candidate, autowiring); + } + catch (UnsatisfiedDependencyException ex) { + if (this.beanFactory.logger.isTraceEnabled()) { + this.beanFactory.logger.trace( + "Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex); + } + if (i == candidates.length - 1 && constructorToUse == null) { + if (causes != null) { + for (Iterator it = causes.iterator(); it.hasNext();) { + this.beanFactory.onSuppressedException((Exception) it.next()); + } + } + throw ex; + } + else { + // Swallow and try next constructor. + if (causes == null) { + causes = new LinkedList(); + } + causes.add(ex); + continue; + } + } + } + + else { + // Explicit arguments given -> arguments length must match exactly. + if (paramTypes.length != explicitArgs.length) { + continue; + } + args = new ArgumentsHolder(explicitArgs); + } + + int typeDiffWeight = args.getTypeDifferenceWeight(paramTypes); + // Choose this constructor if it represents the closest match. + if (typeDiffWeight < minTypeDiffWeight) { + constructorToUse = candidate; + argsToUse = args.arguments; + minTypeDiffWeight = typeDiffWeight; + } + } + + if (constructorToUse == null) { + throw new BeanCreationException( + mbd.getResourceDescription(), beanName, "Could not resolve matching constructor"); + } + + if (explicitArgs == null) { + mbd.resolvedConstructorOrFactoryMethod = constructorToUse; + } + } + + try { + Object beanInstance = this.instantiationStrategy.instantiate( + mbd, beanName, this.beanFactory, constructorToUse, argsToUse); + bw.setWrappedInstance(beanInstance); + return bw; + } + catch (Throwable ex) { + throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex); + } + } + + /** + * Instantiate the bean using a named factory method. The method may be static, if the + * bean definition parameter specifies a class, rather than a "factory-bean", or + * an instance variable on a factory object itself configured using Dependency Injection. + *

    Implementation requires iterating over the static or instance methods with the + * name specified in the RootBeanDefinition (the method may be overloaded) and trying + * to match with the parameters. We don't have the types attached to constructor args, + * so trial and error is the only way to go here. The explicitArgs array may contain + * argument values passed in programmatically via the corresponding getBean method. + * @param beanName the name of the bean + * @param mbd the merged bean definition for the bean + * @param explicitArgs argument values passed in programmatically via the getBean + * method, or null if none (-> use constructor argument values from bean definition) + * @return a BeanWrapper for the new instance + */ + public BeanWrapper instantiateUsingFactoryMethod(String beanName, RootBeanDefinition mbd, Object[] explicitArgs) { + BeanWrapperImpl bw = new BeanWrapperImpl(); + this.beanFactory.initBeanWrapper(bw); + + Class factoryClass = null; + Object factoryBean = null; + boolean isStatic = true; + + String factoryBeanName = mbd.getFactoryBeanName(); + if (factoryBeanName != null) { + if (factoryBeanName.equals(beanName)) { + throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, + "factory-bean reference points back to the same bean definition"); + } + factoryBean = this.beanFactory.getBean(factoryBeanName); + if (factoryBean == null) { + throw new BeanCreationException(mbd.getResourceDescription(), beanName, + "factory-bean '" + factoryBeanName + "' returned null"); + } + factoryClass = factoryBean.getClass(); + isStatic = false; + } + else { + // It's a static factory method on the bean class. + factoryClass = mbd.getBeanClass(); + } + + Method factoryMethodToUse = null; + Object[] argsToUse = null; + + if (explicitArgs != null) { + argsToUse = explicitArgs; + } + else { + factoryMethodToUse = (Method) mbd.resolvedConstructorOrFactoryMethod; + if (factoryMethodToUse != null) { + // Found a cached factory method... + argsToUse = mbd.resolvedConstructorArguments; + if (argsToUse == null) { + Class[] paramTypes = factoryMethodToUse.getParameterTypes(); + Object[] argsToResolve = mbd.preparedConstructorArguments; + TypeConverter converter = (this.typeConverter != null ? this.typeConverter : bw); + BeanDefinitionValueResolver valueResolver = + new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter); + argsToUse = new Object[argsToResolve.length]; + for (int i = 0; i < argsToResolve.length; i++) { + Object argValue = argsToResolve[i]; + MethodParameter methodParam = new MethodParameter(factoryMethodToUse, i); + if (JdkVersion.isAtLeastJava15()) { + GenericTypeResolver.resolveParameterType(methodParam, factoryClass); + } + if (argValue instanceof AutowiredArgumentMarker) { + argValue = resolveAutowiredArgument(methodParam, beanName, null, converter); + } + else if (argValue instanceof BeanMetadataElement) { + argValue = valueResolver.resolveValueIfNecessary("factory method argument", argValue); + } + argsToUse[i] = converter.convertIfNecessary(argValue, paramTypes[i], methodParam); + } + } + } + } + + if (factoryMethodToUse == null) { + // Need to determine the factory method... + // Try all methods with this name to see if they match the given arguments. + Method[] candidates = ReflectionUtils.getAllDeclaredMethods(factoryClass); + boolean autowiring = (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR); + int minTypeDiffWeight = Integer.MAX_VALUE; + ConstructorArgumentValues resolvedValues = null; + + int minNrOfArgs = 0; + if (explicitArgs != null) { + minNrOfArgs = explicitArgs.length; + } + else { + // We don't have arguments passed in programmatically, so we need to resolve the + // arguments specified in the constructor arguments held in the bean definition. + ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues(); + resolvedValues = new ConstructorArgumentValues(); + minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues); + } + + List causes = null; + + for (int i = 0; i < candidates.length; i++) { + Method candidate = candidates[i]; + Class[] paramTypes = candidate.getParameterTypes(); + + if (Modifier.isStatic(candidate.getModifiers()) == isStatic && + candidate.getName().equals(mbd.getFactoryMethodName()) && + paramTypes.length >= minNrOfArgs) { + + ArgumentsHolder args = null; + + if (resolvedValues != null) { + // Resolved contructor arguments: type conversion and/or autowiring necessary. + try { + args = createArgumentArray( + beanName, mbd, resolvedValues, bw, paramTypes, candidate, autowiring); + } + catch (UnsatisfiedDependencyException ex) { + if (this.beanFactory.logger.isTraceEnabled()) { + this.beanFactory.logger.trace("Ignoring factory method [" + candidate + + "] of bean '" + beanName + "': " + ex); + } + if (i == candidates.length - 1 && factoryMethodToUse == null) { + if (causes != null) { + for (Iterator it = causes.iterator(); it.hasNext();) { + this.beanFactory.onSuppressedException((Exception) it.next()); + } + } + throw ex; + } + else { + // Swallow and try next overloaded factory method. + if (causes == null) { + causes = new LinkedList(); + } + causes.add(ex); + continue; + } + } + } + + else { + // Explicit arguments given -> arguments length must match exactly. + if (paramTypes.length != explicitArgs.length) { + continue; + } + args = new ArgumentsHolder(explicitArgs); + } + + int typeDiffWeight = args.getTypeDifferenceWeight(paramTypes); + // Choose this constructor if it represents the closest match. + if (typeDiffWeight < minTypeDiffWeight) { + factoryMethodToUse = candidate; + argsToUse = args.arguments; + minTypeDiffWeight = typeDiffWeight; + } + } + } + + if (factoryMethodToUse == null) { + throw new BeanCreationException(mbd.getResourceDescription(), beanName, + "No matching factory method found: " + + (mbd.getFactoryBeanName() != null ? + "factory bean '" + mbd.getFactoryBeanName() + "'; " : "") + + "factory method '" + mbd.getFactoryMethodName() + "'"); + } + if (void.class.equals(factoryMethodToUse.getReturnType())) { + throw new BeanCreationException(mbd.getResourceDescription(), beanName, + "Invalid factory method '" + mbd.getFactoryMethodName() + + "': needs to have a non-void return type!"); + } + + if (explicitArgs == null) { + mbd.resolvedConstructorOrFactoryMethod = factoryMethodToUse; + } + } + + try { + Object beanInstance = this.instantiationStrategy.instantiate( + mbd, beanName, this.beanFactory, factoryBean, factoryMethodToUse, argsToUse); + if (beanInstance == null) { + return null; + } + bw.setWrappedInstance(beanInstance); + return bw; + } + catch (Throwable ex) { + throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex); + } + } + + /** + * Resolve the constructor arguments for this bean into the resolvedValues object. + * This may involve looking up other beans. + * This method is also used for handling invocations of static factory methods. + */ + private int resolveConstructorArguments( + String beanName, RootBeanDefinition mbd, BeanWrapper bw, + ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) { + + TypeConverter converterToUse = (this.typeConverter != null ? this.typeConverter : bw); + BeanDefinitionValueResolver valueResolver = + new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converterToUse); + + int minNrOfArgs = cargs.getArgumentCount(); + + for (Iterator it = cargs.getIndexedArgumentValues().entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + int index = ((Integer) entry.getKey()).intValue(); + if (index < 0) { + throw new BeanCreationException(mbd.getResourceDescription(), beanName, + "Invalid constructor argument index: " + index); + } + if (index > minNrOfArgs) { + minNrOfArgs = index + 1; + } + ConstructorArgumentValues.ValueHolder valueHolder = + (ConstructorArgumentValues.ValueHolder) entry.getValue(); + if (valueHolder.isConverted()) { + resolvedValues.addIndexedArgumentValue(index, valueHolder); + } + else { + Object resolvedValue = + valueResolver.resolveValueIfNecessary("constructor argument", valueHolder.getValue()); + ConstructorArgumentValues.ValueHolder resolvedValueHolder = + new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType()); + resolvedValueHolder.setSource(valueHolder); + resolvedValues.addIndexedArgumentValue(index, resolvedValueHolder); + } + } + + for (Iterator it = cargs.getGenericArgumentValues().iterator(); it.hasNext();) { + ConstructorArgumentValues.ValueHolder valueHolder = + (ConstructorArgumentValues.ValueHolder) it.next(); + if (valueHolder.isConverted()) { + resolvedValues.addGenericArgumentValue(valueHolder); + } + else { + Object resolvedValue = + valueResolver.resolveValueIfNecessary("constructor argument", valueHolder.getValue()); + ConstructorArgumentValues.ValueHolder resolvedValueHolder = + new ConstructorArgumentValues.ValueHolder(resolvedValue, valueHolder.getType()); + resolvedValueHolder.setSource(valueHolder); + resolvedValues.addGenericArgumentValue(resolvedValueHolder); + } + } + + return minNrOfArgs; + } + + /** + * Create an array of arguments to invoke a constructor or factory method, + * given the resolved constructor argument values. + */ + private ArgumentsHolder createArgumentArray( + String beanName, RootBeanDefinition mbd, ConstructorArgumentValues resolvedValues, + BeanWrapper bw, Class[] paramTypes, Object methodOrCtor, boolean autowiring) + throws UnsatisfiedDependencyException { + + String methodType = (methodOrCtor instanceof Constructor ? "constructor" : "factory method"); + TypeConverter converter = (this.typeConverter != null ? this.typeConverter : bw); + + ArgumentsHolder args = new ArgumentsHolder(paramTypes.length); + Set usedValueHolders = new HashSet(paramTypes.length); + Set autowiredBeanNames = new LinkedHashSet(4); + boolean resolveNecessary = false; + + for (int paramIndex = 0; paramIndex < paramTypes.length; paramIndex++) { + Class paramType = paramTypes[paramIndex]; + // Try to find matching constructor argument value, either indexed or generic. + ConstructorArgumentValues.ValueHolder valueHolder = + resolvedValues.getArgumentValue(paramIndex, paramType, usedValueHolders); + // If we couldn't find a direct match and are not supposed to autowire, + // let's try the next generic, untyped argument value as fallback: + // it could match after type conversion (for example, String -> int). + if (valueHolder == null && !autowiring) { + valueHolder = resolvedValues.getGenericArgumentValue(null, usedValueHolders); + } + if (valueHolder != null) { + // We found a potential match - let's give it a try. + // Do not consider the same value definition multiple times! + usedValueHolders.add(valueHolder); + args.rawArguments[paramIndex] = valueHolder.getValue(); + if (valueHolder.isConverted()) { + Object convertedValue = valueHolder.getConvertedValue(); + args.arguments[paramIndex] = convertedValue; + args.preparedArguments[paramIndex] = convertedValue; + } + else { + try { + Object originalValue = valueHolder.getValue(); + Object convertedValue = converter.convertIfNecessary(originalValue, paramType, + MethodParameter.forMethodOrConstructor(methodOrCtor, paramIndex)); + args.arguments[paramIndex] = convertedValue; + ConstructorArgumentValues.ValueHolder sourceHolder = + (ConstructorArgumentValues.ValueHolder) valueHolder.getSource(); + Object sourceValue = sourceHolder.getValue(); + if (originalValue == sourceValue || sourceValue instanceof TypedStringValue) { + // Either a converted value or still the original one: store converted value. + sourceHolder.setConvertedValue(convertedValue); + args.preparedArguments[paramIndex] = convertedValue; + } + else { + resolveNecessary = true; + args.preparedArguments[paramIndex] = sourceValue; + } + } + catch (TypeMismatchException ex) { + throw new UnsatisfiedDependencyException( + mbd.getResourceDescription(), beanName, paramIndex, paramType, + "Could not convert " + methodType + " argument value of type [" + + ObjectUtils.nullSafeClassName(valueHolder.getValue()) + + "] to required type [" + paramType.getName() + "]: " + ex.getMessage()); + } + } + } + else { + // No explicit match found: we're either supposed to autowire or + // have to fail creating an argument array for the given constructor. + if (!autowiring) { + throw new UnsatisfiedDependencyException( + mbd.getResourceDescription(), beanName, paramIndex, paramType, + "Ambiguous " + methodType + " argument types - " + + "did you specify the correct bean references as " + methodType + " arguments?"); + } + try { + MethodParameter param = MethodParameter.forMethodOrConstructor(methodOrCtor, paramIndex); + Object autowiredArgument = resolveAutowiredArgument(param, beanName, autowiredBeanNames, converter); + args.rawArguments[paramIndex] = autowiredArgument; + args.arguments[paramIndex] = autowiredArgument; + args.preparedArguments[paramIndex] = new AutowiredArgumentMarker(); + resolveNecessary = true; + } + catch (BeansException ex) { + throw new UnsatisfiedDependencyException( + mbd.getResourceDescription(), beanName, paramIndex, paramType, ex); + } + } + } + + for (Iterator it = autowiredBeanNames.iterator(); it.hasNext();) { + String autowiredBeanName = (String) it.next(); + this.beanFactory.registerDependentBean(autowiredBeanName, beanName); + if (this.beanFactory.logger.isDebugEnabled()) { + this.beanFactory.logger.debug("Autowiring by type from bean name '" + beanName + + "' via " + methodType + " to bean named '" + autowiredBeanName + "'"); + } + } + + if (resolveNecessary) { + mbd.preparedConstructorArguments = args.preparedArguments; + } + else { + mbd.resolvedConstructorArguments = args.arguments; + } + mbd.constructorArgumentsResolved = true; + return args; + } + + /** + * Template method for resolving the specified argument which is supposed to be autowired. + */ + protected Object resolveAutowiredArgument( + MethodParameter param, String beanName, Set autowiredBeanNames, TypeConverter typeConverter) { + + return this.autowireFactory.resolveDependency( + new DependencyDescriptor(param, true), beanName, autowiredBeanNames, typeConverter); + } + + + /** + * Private inner class for holding argument combinations. + */ + private static class ArgumentsHolder { + + public Object rawArguments[]; + + public Object arguments[]; + + public Object preparedArguments[]; + + public ArgumentsHolder(int size) { + this.rawArguments = new Object[size]; + this.arguments = new Object[size]; + this.preparedArguments = new Object[size]; + } + + public ArgumentsHolder(Object[] args) { + this.rawArguments = args; + this.arguments = args; + this.preparedArguments = args; + } + + public int getTypeDifferenceWeight(Class[] paramTypes) { + // If valid arguments found, determine type difference weight. + // Try type difference weight on both the converted arguments and + // the raw arguments. If the raw weight is better, use it. + // Decrease raw weight by 1024 to prefer it over equal converted weight. + int typeDiffWeight = MethodInvoker.getTypeDifferenceWeight(paramTypes, this.arguments); + int rawTypeDiffWeight = MethodInvoker.getTypeDifferenceWeight(paramTypes, this.rawArguments) - 1024; + return (rawTypeDiffWeight < typeDiffWeight ? rawTypeDiffWeight : typeDiffWeight); + } + } + + + /** + * Marker for autowired arguments in a cached argument array. + */ + private static class AutowiredArgumentMarker { + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/DefaultBeanNameGenerator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/DefaultBeanNameGenerator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/DefaultBeanNameGenerator.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.factory.config.BeanDefinition; + +/** + * Default implementation of the {@link BeanNameGenerator} interface, delegating to + * {@link BeanDefinitionReaderUtils#generateBeanName(BeanDefinition, BeanDefinitionRegistry)}. + * + * @author Juergen Hoeller + * @since 2.0.3 + */ +public class DefaultBeanNameGenerator implements BeanNameGenerator { + + public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) { + return BeanDefinitionReaderUtils.generateBeanName(definition, registry); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/DefaultListableBeanFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/DefaultListableBeanFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/DefaultListableBeanFactory.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,747 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.springframework.beans.BeansException; +import org.springframework.beans.FatalBeanException; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanCurrentlyInCreationException; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.CannotLoadBeanClassException; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.ObjectFactory; +import org.springframework.beans.factory.SmartFactoryBean; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.config.DependencyDescriptor; +import org.springframework.core.CollectionFactory; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +/** + * Default implementation of the + * {@link org.springframework.beans.factory.ListableBeanFactory} and + * {@link BeanDefinitionRegistry} interfaces: a full-fledged bean factory + * based on bean definition objects. + * + *

    Typical usage is registering all bean definitions first (possibly read + * from a bean definition file), before accessing beans. Bean definition lookup + * is therefore an inexpensive operation in a local bean definition table, + * operating on pre-built bean definition metadata objects. + * + *

    Can be used as a standalone bean factory, or as a superclass for custom + * bean factories. Note that readers for specific bean definition formats are + * typically implemented separately rather than as bean factory subclasses: + * see for example {@link PropertiesBeanDefinitionReader} and + * {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}. + * + *

    For an alternative implementation of the + * {@link org.springframework.beans.factory.ListableBeanFactory} interface, + * have a look at {@link StaticListableBeanFactory}, which manages existing + * bean instances rather than creating new ones based on bean definitions. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Sam Brannen + * @since 16 April 2001 + * @see StaticListableBeanFactory + * @see PropertiesBeanDefinitionReader + * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader + */ +public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory + implements ConfigurableListableBeanFactory, BeanDefinitionRegistry { + + /** Whether to allow re-registration of a different definition with the same name */ + private boolean allowBeanDefinitionOverriding = true; + + /** Whether to allow eager class loading even for lazy-init beans */ + private boolean allowEagerClassLoading = true; + + /** Whether bean definition metadata may be cached for all beans */ + private boolean configurationFrozen = false; + + /** Map of bean definition objects, keyed by bean name */ + private final Map beanDefinitionMap = CollectionFactory.createConcurrentMapIfPossible(16); + + /** List of bean definition names, in registration order */ + private final List beanDefinitionNames = new ArrayList(); + + /** Cached array of bean definition names in case of frozen configuration */ + private String[] frozenBeanDefinitionNames; + + /** Resolver to use for checking if a bean definition is an autowire candidate */ + private AutowireCandidateResolver autowireCandidateResolver = AutowireUtils.createAutowireCandidateResolver(); + + /** Map from dependency type to corresponding autowired value */ + private final Map resolvableDependencies = new HashMap(); + + + /** + * Create a new DefaultListableBeanFactory. + */ + public DefaultListableBeanFactory() { + super(); + } + + /** + * Create a new DefaultListableBeanFactory with the given parent. + * @param parentBeanFactory the parent BeanFactory + */ + public DefaultListableBeanFactory(BeanFactory parentBeanFactory) { + super(parentBeanFactory); + } + + + /** + * Set a custom autowire candidate resolver for this BeanFactory to use + * when deciding whether a bean definition should be considered as a + * candidate for autowiring. + */ + public void setAutowireCandidateResolver(AutowireCandidateResolver autowireCandidateResolver) { + Assert.notNull(autowireCandidateResolver, "AutowireCandidateResolver must not be null"); + this.autowireCandidateResolver = autowireCandidateResolver; + } + + /** + * Return the autowire candidate resolver for this BeanFactory (never null). + */ + public AutowireCandidateResolver getAutowireCandidateResolver() { + return this.autowireCandidateResolver; + } + + /** + * Set whether it should be allowed to override bean definitions by registering + * a different definition with the same name, automatically replacing the former. + * If not, an exception will be thrown. This also applies to overriding aliases. + *

    Default is "true". + * @see #registerBeanDefinition + */ + public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) { + this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding; + } + + /** + * Set whether the factory is allowed to eagerly load bean classes + * even for bean definitions that are marked as "lazy-init". + *

    Default is "true". Turn this flag off to suppress class loading + * for lazy-init beans unless such a bean is explicitly requested. + * In particular, by-type lookups will then simply ignore bean definitions + * without resolved class name, instead of loading the bean classes on + * demand just to perform a type check. + * @see AbstractBeanDefinition#setLazyInit + */ + public void setAllowEagerClassLoading(boolean allowEagerClassLoading) { + this.allowEagerClassLoading = allowEagerClassLoading; + } + + + public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { + super.copyConfigurationFrom(otherFactory); + if (otherFactory instanceof DefaultListableBeanFactory) { + DefaultListableBeanFactory otherListableFactory = (DefaultListableBeanFactory) otherFactory; + this.allowBeanDefinitionOverriding = otherListableFactory.allowBeanDefinitionOverriding; + this.allowEagerClassLoading = otherListableFactory.allowEagerClassLoading; + } + } + + + //--------------------------------------------------------------------- + // Implementation of ListableBeanFactory interface + //--------------------------------------------------------------------- + + public boolean containsBeanDefinition(String beanName) { + return this.beanDefinitionMap.containsKey(beanName); + } + + public int getBeanDefinitionCount() { + return this.beanDefinitionMap.size(); + } + + public String[] getBeanDefinitionNames() { + synchronized (this.beanDefinitionMap) { + if (this.frozenBeanDefinitionNames != null) { + return this.frozenBeanDefinitionNames; + } + else { + return StringUtils.toStringArray(this.beanDefinitionNames); + } + } + } + + public String[] getBeanNamesForType(Class type) { + return getBeanNamesForType(type, true, true); + } + + public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { + List result = new ArrayList(); + + // Check all bean definitions. + String[] beanDefinitionNames = getBeanDefinitionNames(); + for (int i = 0; i < beanDefinitionNames.length; i++) { + String beanName = beanDefinitionNames[i]; + // Only consider bean as eligible if the bean name + // is not defined as alias for some other bean. + if (!isAlias(beanName)) { + try { + RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); + // Only check bean definition if it is complete. + if (!mbd.isAbstract() && + (allowEagerInit || ((mbd.hasBeanClass() || !mbd.isLazyInit() || this.allowEagerClassLoading)) && + !requiresEagerInitForType(mbd.getFactoryBeanName()))) { + // In case of FactoryBean, match object created by FactoryBean. + boolean isFactoryBean = isFactoryBean(beanName, mbd); + boolean matchFound = + (allowEagerInit || !isFactoryBean || containsSingleton(beanName)) && + (includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type); + if (!matchFound && isFactoryBean) { + // In case of FactoryBean, try to match FactoryBean instance itself next. + beanName = FACTORY_BEAN_PREFIX + beanName; + matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type); + } + if (matchFound) { + result.add(beanName); + } + } + } + catch (CannotLoadBeanClassException ex) { + if (allowEagerInit) { + throw ex; + } + // Probably contains a placeholder: let's ignore it for type matching purposes. + if (this.logger.isDebugEnabled()) { + this.logger.debug("Ignoring bean class loading failure for bean '" + beanName + "'", ex); + } + onSuppressedException(ex); + } + catch (BeanDefinitionStoreException ex) { + if (allowEagerInit) { + throw ex; + } + // Probably contains a placeholder: let's ignore it for type matching purposes. + if (this.logger.isDebugEnabled()) { + this.logger.debug("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex); + } + onSuppressedException(ex); + } + } + } + + // Check singletons too, to catch manually registered singletons. + String[] singletonNames = getSingletonNames(); + for (int i = 0; i < singletonNames.length; i++) { + String beanName = singletonNames[i]; + // Only check if manually registered. + if (!containsBeanDefinition(beanName)) { + // In case of FactoryBean, match object created by FactoryBean. + if (isFactoryBean(beanName)) { + if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) { + result.add(beanName); + // Match found for this bean: do not match FactoryBean itself anymore. + continue; + } + // In case of FactoryBean, try to match FactoryBean itself next. + beanName = FACTORY_BEAN_PREFIX + beanName; + } + // Match raw bean instance (might be raw FactoryBean). + if (isTypeMatch(beanName, type)) { + result.add(beanName); + } + } + } + + return StringUtils.toStringArray(result); + } + + /** + * Check whether the specified bean would need to be eagerly initialized + * in order to determine its type. + * @param factoryBeanName a factory-bean reference that the bean definition + * defines a factory method for + * @return whether eager initialization is necessary + */ + private boolean requiresEagerInitForType(String factoryBeanName) { + return (factoryBeanName != null && isFactoryBean(factoryBeanName) && !containsSingleton(factoryBeanName)); + } + + public Map getBeansOfType(Class type) throws BeansException { + return getBeansOfType(type, true, true); + } + + public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException { + + String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit); + Map result = new LinkedHashMap(beanNames.length); + for (int i = 0; i < beanNames.length; i++) { + String beanName = beanNames[i]; + try { + result.put(beanName, getBean(beanName)); + } + catch (BeanCreationException ex) { + Throwable rootCause = ex.getMostSpecificCause(); + if (rootCause instanceof BeanCurrentlyInCreationException) { + BeanCreationException bce = (BeanCreationException) rootCause; + if (isCurrentlyInCreation(bce.getBeanName())) { + if (this.logger.isDebugEnabled()) { + this.logger.debug("Ignoring match to currently created bean '" + beanName + "': " + ex.getMessage()); + } + onSuppressedException(ex); + // Ignore: indicates a circular reference when autowiring constructors. + // We want to find matches other than the currently created bean itself. + continue; + } + } + throw ex; + } + } + return result; + } + + + //--------------------------------------------------------------------- + // Implementation of ConfigurableListableBeanFactory interface + //--------------------------------------------------------------------- + + public void registerResolvableDependency(Class dependencyType, Object autowiredValue) { + Assert.notNull(dependencyType, "Type must not be null"); + if (autowiredValue != null) { + Assert.isTrue((autowiredValue instanceof ObjectFactory || dependencyType.isInstance(autowiredValue)), + "Value [" + autowiredValue + "] does not implement specified type [" + dependencyType.getName() + "]"); + this.resolvableDependencies.put(dependencyType, autowiredValue); + } + } + + public boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor) + throws NoSuchBeanDefinitionException { + + // Consider FactoryBeans as autowiring candidates. + boolean isFactoryBean = (descriptor != null && descriptor.getDependencyType() != null && + FactoryBean.class.isAssignableFrom(descriptor.getDependencyType())); + if (isFactoryBean) { + beanName = BeanFactoryUtils.transformedBeanName(beanName); + } + + if (!containsBeanDefinition(beanName)) { + if (containsSingleton(beanName)) { + return true; + } + else if (getParentBeanFactory() instanceof ConfigurableListableBeanFactory) { + // No bean definition found in this factory -> delegate to parent. + return ((ConfigurableListableBeanFactory) getParentBeanFactory()).isAutowireCandidate(beanName, descriptor); + } + } + + return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanName), descriptor); + } + + /** + * Determine whether the specified bean definition qualifies as an autowire candidate, + * to be injected into other beans which declare a dependency of matching type. + * @param beanName the name of the bean definition to check + * @param mbd the merged bean definition to check + * @param descriptor the descriptor of the dependency to resolve + * @return whether the bean should be considered as autowire candidate + */ + protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd, DependencyDescriptor descriptor) { + resolveBeanClass(mbd, beanName); + return getAutowireCandidateResolver().isAutowireCandidate( + new BeanDefinitionHolder(mbd, beanName, getAliases(beanName)), descriptor); + } + + public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { + BeanDefinition bd = (BeanDefinition) this.beanDefinitionMap.get(beanName); + if (bd == null) { + if (this.logger.isTraceEnabled()) { + this.logger.trace("No bean named '" + beanName + "' found in " + this); + } + throw new NoSuchBeanDefinitionException(beanName); + } + return bd; + } + + public void freezeConfiguration() { + this.configurationFrozen = true; + synchronized (this.beanDefinitionMap) { + this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames); + } + } + + public boolean isConfigurationFrozen() { + return this.configurationFrozen; + } + + /** + * Considers all beans as eligible for metdata caching + * if the factory's configuration has been marked as frozen. + * @see #freezeConfiguration() + */ + protected boolean isBeanEligibleForMetadataCaching(String beanName) { + return (this.configurationFrozen || super.isBeanEligibleForMetadataCaching(beanName)); + } + + public void preInstantiateSingletons() throws BeansException { + if (this.logger.isInfoEnabled()) { + this.logger.info("Pre-instantiating singletons in " + this); + } + + synchronized (this.beanDefinitionMap) { + for (Iterator it = this.beanDefinitionNames.iterator(); it.hasNext();) { + String beanName = (String) it.next(); + RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); + if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { + if (isFactoryBean(beanName)) { + FactoryBean factory = (FactoryBean) getBean(FACTORY_BEAN_PREFIX + beanName); + if (factory instanceof SmartFactoryBean && ((SmartFactoryBean) factory).isEagerInit()) { + getBean(beanName); + } + } + else { + getBean(beanName); + } + } + } + } + } + + + //--------------------------------------------------------------------- + // Implementation of BeanDefinitionRegistry interface + //--------------------------------------------------------------------- + + public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) + throws BeanDefinitionStoreException { + + Assert.hasText(beanName, "'beanName' must not be empty"); + Assert.notNull(beanDefinition, "BeanDefinition must not be null"); + + if (beanDefinition instanceof AbstractBeanDefinition) { + try { + ((AbstractBeanDefinition) beanDefinition).validate(); + } + catch (BeanDefinitionValidationException ex) { + throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, + "Validation of bean definition failed", ex); + } + } + + synchronized (this.beanDefinitionMap) { + Object oldBeanDefinition = this.beanDefinitionMap.get(beanName); + if (oldBeanDefinition != null) { + if (!this.allowBeanDefinitionOverriding) { + throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, + "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName + + "': There is already [" + oldBeanDefinition + "] bound."); + } + else { + if (this.logger.isInfoEnabled()) { + this.logger.info("Overriding bean definition for bean '" + beanName + + "': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]"); + } + } + } + else { + this.beanDefinitionNames.add(beanName); + this.frozenBeanDefinitionNames = null; + } + this.beanDefinitionMap.put(beanName, beanDefinition); + + resetBeanDefinition(beanName); + } + } + + public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { + Assert.hasText(beanName, "'beanName' must not be empty"); + + synchronized (this.beanDefinitionMap) { + BeanDefinition bd = (BeanDefinition) this.beanDefinitionMap.remove(beanName); + if (bd == null) { + if (this.logger.isTraceEnabled()) { + this.logger.trace("No bean named '" + beanName + "' found in " + this); + } + throw new NoSuchBeanDefinitionException(beanName); + } + this.beanDefinitionNames.remove(beanName); + this.frozenBeanDefinitionNames = null; + + resetBeanDefinition(beanName); + } + } + + /** + * Reset all bean definition caches for the given bean, + * including the caches of beans that are derived from it. + * @param beanName the name of the bean to reset + */ + protected void resetBeanDefinition(String beanName) { + // Remove the merged bean definition for the given bean, if already created. + clearMergedBeanDefinition(beanName); + + // Remove corresponding bean from singleton cache, if any. Shouldn't usually + // be necessary, rather just meant for overriding a context's default beans + // (e.g. the default StaticMessageSource in a StaticApplicationContext). + synchronized (getSingletonMutex()) { + destroySingleton(beanName); + } + + // Reset all bean definitions that have the given bean as parent + // (recursively). + for (Iterator it = this.beanDefinitionNames.iterator(); it.hasNext();) { + String bdName = (String) it.next(); + if (!beanName.equals(bdName)) { + BeanDefinition bd = (BeanDefinition) this.beanDefinitionMap.get(bdName); + if (beanName.equals(bd.getParentName())) { + resetBeanDefinition(bdName); + } + } + } + } + + /** + * Only allows alias overriding if bean definition overriding is allowed. + */ + protected boolean allowAliasOverriding() { + return this.allowBeanDefinitionOverriding; + } + + + //--------------------------------------------------------------------- + // Implementation of superclass abstract methods + //--------------------------------------------------------------------- + + public Object resolveDependency(DependencyDescriptor descriptor, String beanName, + Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException { + + Class type = descriptor.getDependencyType(); + if (type.isArray()) { + Class componentType = type.getComponentType(); + Map matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); + if (matchingBeans.isEmpty()) { + if (descriptor.isRequired()) { + raiseNoSuchBeanDefinitionException(componentType, "array of " + componentType.getName(), descriptor); + } + return null; + } + if (autowiredBeanNames != null) { + autowiredBeanNames.addAll(matchingBeans.keySet()); + } + TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); + return converter.convertIfNecessary(matchingBeans.values(), type); + } + else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { + Class elementType = descriptor.getCollectionType(); + if (elementType == null) { + if (descriptor.isRequired()) { + throw new FatalBeanException("No element type declared for collection [" + type.getName() + "]"); + } + return null; + } + Map matchingBeans = findAutowireCandidates(beanName, elementType, descriptor); + if (matchingBeans.isEmpty()) { + if (descriptor.isRequired()) { + raiseNoSuchBeanDefinitionException(elementType, "collection of " + elementType.getName(), descriptor); + } + return null; + } + if (autowiredBeanNames != null) { + autowiredBeanNames.addAll(matchingBeans.keySet()); + } + TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); + return converter.convertIfNecessary(matchingBeans.values(), type); + } + else if (Map.class.isAssignableFrom(type) && type.isInterface()) { + Class keyType = descriptor.getMapKeyType(); + if (keyType == null || !String.class.isAssignableFrom(keyType)) { + if (descriptor.isRequired()) { + throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() + + "] must be assignable to [java.lang.String]"); + } + return null; + } + Class valueType = descriptor.getMapValueType(); + if (valueType == null) { + if (descriptor.isRequired()) { + throw new FatalBeanException("No value type declared for map [" + type.getName() + "]"); + } + return null; + } + Map matchingBeans = findAutowireCandidates(beanName, valueType, descriptor); + if (matchingBeans.isEmpty()) { + if (descriptor.isRequired()) { + raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor); + } + return null; + } + if (autowiredBeanNames != null) { + autowiredBeanNames.addAll(matchingBeans.keySet()); + } + return matchingBeans; + } + else { + Map matchingBeans = findAutowireCandidates(beanName, type, descriptor); + if (matchingBeans.isEmpty()) { + if (descriptor.isRequired()) { + throw new NoSuchBeanDefinitionException(type, + "Unsatisfied dependency of type [" + type + "]: expected at least 1 matching bean"); + } + return null; + } + if (matchingBeans.size() > 1) { + String primaryBeanName = determinePrimaryCandidate(matchingBeans, type); + if (primaryBeanName == null) { + throw new NoSuchBeanDefinitionException(type, + "expected single matching bean but found " + matchingBeans.size() + ": " + matchingBeans.keySet()); + } + if (autowiredBeanNames != null) { + autowiredBeanNames.add(primaryBeanName); + } + return matchingBeans.get(primaryBeanName); + } + // We have exactly one match. + Map.Entry entry = (Map.Entry) matchingBeans.entrySet().iterator().next(); + if (autowiredBeanNames != null) { + autowiredBeanNames.add(entry.getKey()); + } + return entry.getValue(); + } + } + + /** + * Find bean instances that match the required type. + * Called during autowiring for the specified bean. + * @param beanName the name of the bean that is about to be wired + * @param requiredType the actual type of bean to look for + * (may be an array component type or collection element type) + * @param descriptor the descriptor of the dependency to resolve + * @return a Map of candidate names and candidate instances that match + * the required type (never null) + * @throws BeansException in case of errors + * @see #autowireByType + * @see #autowireConstructor + */ + protected Map findAutowireCandidates(String beanName, Class requiredType, DependencyDescriptor descriptor) { + String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( + this, requiredType, true, descriptor.isEager()); + Map result = new LinkedHashMap(candidateNames.length); + for (Iterator it = this.resolvableDependencies.keySet().iterator(); it.hasNext();) { + Class autowiringType = (Class) it.next(); + if (autowiringType.isAssignableFrom(requiredType)) { + Object autowiringValue = this.resolvableDependencies.get(autowiringType); + if (autowiringValue instanceof ObjectFactory && !requiredType.isInstance(autowiringValue)) { + autowiringValue = ((ObjectFactory) autowiringValue).getObject(); + } + if (requiredType.isInstance(autowiringValue)) { + result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue); + break; + } + } + } + for (int i = 0; i < candidateNames.length; i++) { + String candidateName = candidateNames[i]; + if (!candidateName.equals(beanName) && isAutowireCandidate(candidateName, descriptor)) { + result.put(candidateName, getBean(candidateName)); + } + } + return result; + } + + /** + * Determine the primary autowire candidate in the given set of beans. + * @param candidateBeans a Map of candidate names and candidate instances + * that match the required type, as returned by {@link #findAutowireCandidates} + * @param type the required type + * @return the name of the primary candidate, or null if none found + */ + protected String determinePrimaryCandidate(Map candidateBeans, Class type) { + String primaryBeanName = null; + for (Iterator it = candidateBeans.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + String candidateBeanName = (String) entry.getKey(); + if (isPrimary(candidateBeanName, entry.getValue())) { + if (primaryBeanName != null) { + throw new NoSuchBeanDefinitionException(type, + "more than one 'primary' bean found among candidates: " + candidateBeans.keySet()); + } + primaryBeanName = candidateBeanName; + } + } + return primaryBeanName; + } + + /** + * Return whether the bean definition for the given bean name has been + * marked as a primary bean. + * @param beanName the name of the bean + * @param beanInstance the corresponding bean instance + * @return whether the given bean qualifies as primary + */ + protected boolean isPrimary(String beanName, Object beanInstance) { + if (containsBeanDefinition(beanName)) { + return getMergedLocalBeanDefinition(beanName).isPrimary(); + } + if (this.resolvableDependencies.values().contains(beanInstance)) { + return true; + } + BeanFactory parentFactory = getParentBeanFactory(); + return (parentFactory instanceof DefaultListableBeanFactory && + ((DefaultListableBeanFactory) parentFactory).isPrimary(beanName, beanInstance)); + } + + /** + * Raise a NoSuchBeanDefinitionException for an unresolvable dependency. + */ + private void raiseNoSuchBeanDefinitionException( + Class type, String dependencyDescription, DependencyDescriptor descriptor) + throws NoSuchBeanDefinitionException { + + throw new NoSuchBeanDefinitionException(type, dependencyDescription, + "expected at least 1 bean which qualifies as autowire candidate for this dependency. " + + "Dependency annotations: " + ObjectUtils.nullSafeToString(descriptor.getAnnotations())); + } + + + public String toString() { + StringBuffer sb = new StringBuffer(ObjectUtils.identityToString(this)); + sb.append(": defining beans ["); + sb.append(StringUtils.arrayToCommaDelimitedString(getBeanDefinitionNames())); + sb.append("]; "); + BeanFactory parent = getParentBeanFactory(); + if (parent == null) { + sb.append("root of factory hierarchy"); + } + else { + sb.append("parent: " + ObjectUtils.identityToString(parent)); + } + return sb.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,530 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanCreationNotAllowedException; +import org.springframework.beans.factory.BeanCurrentlyInCreationException; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.ObjectFactory; +import org.springframework.beans.factory.config.SingletonBeanRegistry; +import org.springframework.core.CollectionFactory; +import org.springframework.core.SimpleAliasRegistry; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +/** + * Generic registry for shared bean instances, implementing the + * {@link org.springframework.beans.factory.config.SingletonBeanRegistry}. + * Allows for registering singleton instances that should be shared + * for all callers of the registry, to be obtained via bean name. + * + *

    Also supports registration of + * {@link org.springframework.beans.factory.DisposableBean} instances, + * (which might or might not correspond to registered singletons), + * to be destroyed on shutdown of the registry. Dependencies between + * beans can be registered to enforce an appropriate shutdown order. + * + *

    This class mainly serves as base class for + * {@link org.springframework.beans.factory.BeanFactory} implementations, + * factoring out the common management of singleton bean instances. Note that + * the {@link org.springframework.beans.factory.config.ConfigurableBeanFactory} + * interface extends the {@link SingletonBeanRegistry} interface. + * + *

    Note that this class assumes neither a bean definition concept + * nor a specific creation process for bean instances, in contrast to + * {@link AbstractBeanFactory} and {@link DefaultListableBeanFactory} + * (which inherit from it). Can alternatively also be used as a nested + * helper to delegate to. + * + * @author Juergen Hoeller + * @since 2.0 + * @see #registerSingleton + * @see #registerDisposableBean + * @see org.springframework.beans.factory.DisposableBean + * @see org.springframework.beans.factory.config.ConfigurableBeanFactory + */ +public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry { + + /** + * Internal marker for a null singleton object: + * used as marker value for concurrent Maps (which don't support null values). + */ + protected static final Object NULL_OBJECT = new Object(); + + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + /** Cache of singleton objects: bean name --> bean instance */ + private final Map singletonObjects = CollectionFactory.createConcurrentMapIfPossible(16); + + /** Cache of singleton factories: bean name --> ObjectFactory */ + private final Map singletonFactories = new HashMap(); + + /** Cache of early singleton objects: bean name --> bean instance */ + private final Map earlySingletonObjects = new HashMap(); + + /** Set of registered singletons, containing the bean names in registration order */ + private final Set registeredSingletons = new LinkedHashSet(16); + + /** Names of beans that are currently in creation */ + private final Set singletonsCurrentlyInCreation = Collections.synchronizedSet(new HashSet()); + + /** List of suppressed Exceptions, available for associating related causes */ + private Set suppressedExceptions; + + /** Flag that indicates whether we're currently within destroySingletons */ + private boolean singletonsCurrentlyInDestruction = false; + + /** Disposable bean instances: bean name --> disposable instance */ + private final Map disposableBeans = new LinkedHashMap(16); + + /** Map between containing bean names: bean name --> Set of bean names that the bean contains */ + private final Map containedBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + + /** Map between dependent bean names: bean name --> Set of dependent bean names */ + private final Map dependentBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + + /** Map between depending bean names: bean name --> Set of bean names for the bean's dependencies */ + private final Map dependenciesForBeanMap = CollectionFactory.createConcurrentMapIfPossible(16); + + + public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException { + Assert.notNull(beanName, "'beanName' must not be null"); + synchronized (this.singletonObjects) { + Object oldObject = this.singletonObjects.get(beanName); + if (oldObject != null) { + throw new IllegalStateException("Could not register object [" + singletonObject + + "] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound"); + } + addSingleton(beanName, singletonObject); + } + } + + /** + * Add the given singleton object to the singleton cache of this factory. + *

    To be called for eager registration of singletons. + * @param beanName the name of the bean + * @param singletonObject the singleton object + */ + protected void addSingleton(String beanName, Object singletonObject) { + synchronized (this.singletonObjects) { + this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT)); + this.singletonFactories.remove(beanName); + this.earlySingletonObjects.remove(beanName); + this.registeredSingletons.add(beanName); + } + } + + /** + * Add the given singleton factory for building the specified singleton + * if necessary. + *

    To be called for eager registration of singletons, e.g. to be able to + * resolve circular references. + * @param beanName the name of the bean + * @param singletonFactory the factory for the singleton object + */ + protected void addSingletonFactory(String beanName, ObjectFactory singletonFactory) { + Assert.notNull(singletonFactory, "Singleton factory must not be null"); + synchronized (this.singletonObjects) { + if (!this.singletonObjects.containsKey(beanName)) { + this.singletonFactories.put(beanName, singletonFactory); + this.earlySingletonObjects.remove(beanName); + this.registeredSingletons.add(beanName); + } + } + } + + public Object getSingleton(String beanName) { + return getSingleton(beanName, true); + } + + /** + * Return the (raw) singleton object registered under the given name. + *

    Checks already instantiated singletons and also allows for an early + * reference to a currently created singleton (resolving a circular reference). + * @param beanName the name of the bean to look for + * @param allowEarlyReference whether early references should be created or not + * @return the registered singleton object, or null if none found + */ + protected Object getSingleton(String beanName, boolean allowEarlyReference) { + Object singletonObject = this.singletonObjects.get(beanName); + if (singletonObject == null) { + synchronized (this.singletonObjects) { + singletonObject = this.earlySingletonObjects.get(beanName); + if (singletonObject == null && allowEarlyReference) { + ObjectFactory singletonFactory = (ObjectFactory) this.singletonFactories.get(beanName); + if (singletonFactory != null) { + singletonObject = singletonFactory.getObject(); + this.earlySingletonObjects.put(beanName, singletonObject); + this.singletonFactories.remove(beanName); + } + } + } + } + return (singletonObject != NULL_OBJECT ? singletonObject : null); + } + + /** + * Return the (raw) singleton object registered under the given name, + * creating and registering a new one if none registered yet. + * @param beanName the name of the bean + * @param singletonFactory the ObjectFactory to lazily create the singleton + * with, if necessary + * @return the registered singleton object + */ + public Object getSingleton(String beanName, ObjectFactory singletonFactory) { + Assert.notNull(beanName, "'beanName' must not be null"); + synchronized (this.singletonObjects) { + Object singletonObject = this.singletonObjects.get(beanName); + if (singletonObject == null) { + if (this.singletonsCurrentlyInDestruction) { + throw new BeanCreationNotAllowedException(beanName, + "Singleton bean creation not allowed while the singletons of this factory are in destruction " + + "(Do not request a bean from a BeanFactory in a destroy method implementation!)"); + } + if (logger.isDebugEnabled()) { + logger.debug("Creating shared instance of singleton bean '" + beanName + "'"); + } + beforeSingletonCreation(beanName); + boolean recordSuppressedExceptions = (this.suppressedExceptions == null); + if (recordSuppressedExceptions) { + this.suppressedExceptions = new LinkedHashSet(); + } + try { + singletonObject = singletonFactory.getObject(); + } + catch (BeanCreationException ex) { + if (recordSuppressedExceptions) { + for (Iterator it = this.suppressedExceptions.iterator(); it.hasNext();) { + ex.addRelatedCause((Exception) it.next()); + } + } + throw ex; + } + finally { + if (recordSuppressedExceptions) { + this.suppressedExceptions = null; + } + afterSingletonCreation(beanName); + } + addSingleton(beanName, singletonObject); + } + return (singletonObject != NULL_OBJECT ? singletonObject : null); + } + } + + /** + * Register an Exception that happened to get suppressed during the creation of a + * singleton bean instance, e.g. a temporary circular reference resolution problem. + * @param ex the Exception to register + */ + protected void onSuppressedException(Exception ex) { + synchronized (this.singletonObjects) { + if (this.suppressedExceptions != null) { + this.suppressedExceptions.add(ex); + } + } + } + + /** + * Remove the bean with the given name from the singleton cache of this factory, + * to be able to clean up eager registration of a singleton if creation failed. + * @param beanName the name of the bean + * @see #getSingletonMutex() + */ + protected void removeSingleton(String beanName) { + synchronized (this.singletonObjects) { + this.singletonObjects.remove(beanName); + this.singletonFactories.remove(beanName); + this.earlySingletonObjects.remove(beanName); + this.registeredSingletons.remove(beanName); + } + } + + public boolean containsSingleton(String beanName) { + return (this.singletonObjects.containsKey(beanName)); + } + + public String[] getSingletonNames() { + synchronized (this.singletonObjects) { + return StringUtils.toStringArray(this.registeredSingletons); + } + } + + public int getSingletonCount() { + synchronized (this.singletonObjects) { + return this.registeredSingletons.size(); + } + } + + + /** + * Callback before singleton creation. + *

    Default implementation register the singleton as currently in creation. + * @param beanName the name of the singleton about to be created + * @see #isSingletonCurrentlyInCreation + */ + protected void beforeSingletonCreation(String beanName) { + if (!this.singletonsCurrentlyInCreation.add(beanName)) { + throw new BeanCurrentlyInCreationException(beanName); + } + } + + /** + * Callback after singleton creation. + *

    Default implementation marks the singleton as not in creation anymore. + * @param beanName the name of the singleton that has been created + * @see #isSingletonCurrentlyInCreation + */ + protected void afterSingletonCreation(String beanName) { + if (!this.singletonsCurrentlyInCreation.remove(beanName)) { + throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation"); + } + } + + /** + * Return whether the specified singleton bean is currently in creation + * (within the entire factory). + * @param beanName the name of the bean + */ + public final boolean isSingletonCurrentlyInCreation(String beanName) { + return this.singletonsCurrentlyInCreation.contains(beanName); + } + + + /** + * Add the given bean to the list of disposable beans in this registry. + * Disposable beans usually correspond to registered singletons, + * matching the bean name but potentially being a different instance + * (for example, a DisposableBean adapter for a singleton that does not + * naturally implement Spring's DisposableBean interface). + * @param beanName the name of the bean + * @param bean the bean instance + */ + public void registerDisposableBean(String beanName, DisposableBean bean) { + synchronized (this.disposableBeans) { + this.disposableBeans.put(beanName, bean); + } + } + + /** + * Register a containment relationship between two beans, + * e.g. between an inner bean and its containing outer bean. + *

    Also registers the containing bean as dependent on the contained bean + * in terms of destruction order. + * @param containedBeanName the name of the contained (inner) bean + * @param containingBeanName the name of the containing (outer) bean + * @see #registerDependentBean + */ + public void registerContainedBean(String containedBeanName, String containingBeanName) { + synchronized (this.containedBeanMap) { + Set containedBeans = (Set) this.containedBeanMap.get(containingBeanName); + if (containedBeans == null) { + containedBeans = new LinkedHashSet(8); + this.containedBeanMap.put(containingBeanName, containedBeans); + } + containedBeans.add(containedBeanName); + } + registerDependentBean(containedBeanName, containingBeanName); + } + + /** + * Register a dependent bean for the given bean, + * to be destroyed before the given bean is destroyed. + * @param beanName the name of the bean + * @param dependentBeanName the name of the dependent bean + */ + public void registerDependentBean(String beanName, String dependentBeanName) { + synchronized (this.dependentBeanMap) { + Set dependentBeans = (Set) this.dependentBeanMap.get(beanName); + if (dependentBeans == null) { + dependentBeans = new LinkedHashSet(8); + this.dependentBeanMap.put(beanName, dependentBeans); + } + dependentBeans.add(dependentBeanName); + } + synchronized (this.dependenciesForBeanMap) { + Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(dependentBeanName); + if (dependenciesForBean == null) { + dependenciesForBean = new LinkedHashSet(8); + this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean); + } + dependenciesForBean.add(beanName); + } + } + + /** + * Determine whether a dependent bean has been registered for the given name. + * @param beanName the name of the bean to check + */ + protected boolean hasDependentBean(String beanName) { + return this.dependentBeanMap.containsKey(beanName); + } + + /** + * Return the names of all beans which depend on the specified bean, if any. + * @param beanName the name of the bean + * @return the array of dependent bean names, or an empty array if none + */ + public String[] getDependentBeans(String beanName) { + Set dependentBeans = (Set) this.dependentBeanMap.get(beanName); + if (dependentBeans == null) { + return new String[0]; + } + return (String[]) dependentBeans.toArray(new String[dependentBeans.size()]); + } + + /** + * Return the names of all beans that the specified bean depends on, if any. + * @param beanName the name of the bean + * @return the array of names of beans which the bean depends on, + * or an empty array if none + */ + public String[] getDependenciesForBean(String beanName) { + Set dependenciesForBean = (Set) this.dependenciesForBeanMap.get(beanName); + if (dependenciesForBean == null) { + return new String[0]; + } + return (String[]) dependenciesForBean.toArray(new String[dependenciesForBean.size()]); + } + + public void destroySingletons() { + if (logger.isInfoEnabled()) { + logger.info("Destroying singletons in " + this); + } + synchronized (this.singletonObjects) { + this.singletonsCurrentlyInDestruction = true; + } + + synchronized (this.disposableBeans) { + String[] disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet()); + for (int i = disposableBeanNames.length - 1; i >= 0; i--) { + destroySingleton(disposableBeanNames[i]); + } + } + + this.containedBeanMap.clear(); + this.dependentBeanMap.clear(); + this.dependenciesForBeanMap.clear(); + + synchronized (this.singletonObjects) { + this.singletonObjects.clear(); + this.singletonFactories.clear(); + this.earlySingletonObjects.clear(); + this.registeredSingletons.clear(); + this.singletonsCurrentlyInDestruction = false; + } + } + + /** + * Destroy the given bean. Delegates to destroyBean + * if a corresponding disposable bean instance is found. + * @param beanName the name of the bean + * @see #destroyBean + */ + public void destroySingleton(String beanName) { + // Remove a registered singleton of the given name, if any. + removeSingleton(beanName); + + // Destroy the corresponding DisposableBean instance. + DisposableBean disposableBean = null; + synchronized (this.disposableBeans) { + disposableBean = (DisposableBean) this.disposableBeans.remove(beanName); + } + destroyBean(beanName, disposableBean); + } + + /** + * Destroy the given bean. Must destroy beans that depend on the given + * bean before the bean itself. Should not throw any exceptions. + * @param beanName the name of the bean + * @param bean the bean instance to destroy + */ + protected void destroyBean(String beanName, DisposableBean bean) { + // Trigger destruction of dependent beans first... + Set dependencies = (Set) this.dependentBeanMap.remove(beanName); + if (dependencies != null) { + if (logger.isDebugEnabled()) { + logger.debug("Retrieved dependent beans for bean '" + beanName + "': " + dependencies); + } + for (Iterator it = dependencies.iterator(); it.hasNext();) { + String dependentBeanName = (String) it.next(); + destroySingleton(dependentBeanName); + } + } + + // Actually destroy the bean now... + if (bean != null) { + try { + bean.destroy(); + } + catch (Throwable ex) { + logger.error("Destroy method on bean with name '" + beanName + "' threw an exception", ex); + } + } + + // Trigger destruction of contained beans... + Set containedBeans = (Set) this.containedBeanMap.remove(beanName); + if (containedBeans != null) { + for (Iterator it = containedBeans.iterator(); it.hasNext();) { + String containedBeanName = (String) it.next(); + destroySingleton(containedBeanName); + } + } + + // Remove destroyed bean from other beans' dependencies. + synchronized (this.dependentBeanMap) { + for (Iterator it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + Set dependenciesToClean = (Set) entry.getValue(); + dependenciesToClean.remove(beanName); + if (dependenciesToClean.isEmpty()) { + it.remove(); + } + } + } + + // Remove destroyed bean's prepared dependency information. + this.dependenciesForBeanMap.remove(beanName); + } + + /** + * Expose the singleton mutex to subclasses. + *

    Subclasses should synchronize on the given Object if they perform + * any sort of extended singleton creation phase. In particular, subclasses + * should not have their own mutexes involved in singleton creation, + * to avoid the potential for deadlocks in lazy-init situations. + */ + protected final Object getSingletonMutex() { + return this.singletonObjects; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/DisposableBeanAdapter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/DisposableBeanAdapter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/DisposableBeanAdapter.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,254 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; +import org.springframework.util.Assert; +import org.springframework.util.ReflectionUtils; + +/** + * Adapter that implements the {@link DisposableBean} interface + * performing various destruction steps on a given bean instance: + *

      + *
    • DestructionAwareBeanPostProcessors + *
    • the bean implementing DisposableBean itself + *
    • a custom destroy method specified on the bean definition + *
    + * + * @author Juergen Hoeller + * @since 2.0 + * @see AbstractBeanFactory + * @see org.springframework.beans.factory.DisposableBean + * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor + * @see AbstractBeanDefinition#getDestroyMethodName() + */ +class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable { + + private static final Log logger = LogFactory.getLog(DisposableBeanAdapter.class); + + private final Object bean; + + private final String beanName; + + private final boolean invokeDisposableBean; + + private final String destroyMethodName; + + private final boolean enforceDestroyMethod; + + private List beanPostProcessors; + + + /** + * Create a new DisposableBeanAdapter for the given bean. + * @param bean the bean instance (never null) + * @param beanName the name of the bean + * @param beanDefinition the merged bean definition + * @param postProcessors the List of BeanPostProcessors + * (potentially DestructionAwareBeanPostProcessor), if any + */ + public DisposableBeanAdapter( + Object bean, String beanName, RootBeanDefinition beanDefinition, List postProcessors) { + + Assert.notNull(bean, "Bean must not be null"); + this.bean = bean; + this.beanName = beanName; + this.invokeDisposableBean = !beanDefinition.isExternallyManagedDestroyMethod("destroy"); + this.destroyMethodName = + (!beanDefinition.isExternallyManagedDestroyMethod(beanDefinition.getDestroyMethodName()) ? + beanDefinition.getDestroyMethodName() : null); + this.enforceDestroyMethod = beanDefinition.isEnforceDestroyMethod(); + this.beanPostProcessors = filterPostProcessors(postProcessors); + } + + /** + * Create a new DisposableBeanAdapter for the given bean. + * @param bean the bean instance (never null) + * @param beanName the name of the bean + * @param invokeDisposableBean whether to actually invoke + * DisposableBean's destroy method here + * @param destroyMethodName the name of the custom destroy method + * (null if there is none) + * @param enforceDestroyMethod whether to the specified custom + * destroy method (if any) has to be present on the bean object + * @param postProcessors the List of DestructionAwareBeanPostProcessors, if any + */ + private DisposableBeanAdapter(Object bean, String beanName, boolean invokeDisposableBean, + String destroyMethodName, boolean enforceDestroyMethod, List postProcessors) { + + this.bean = bean; + this.beanName = beanName; + this.invokeDisposableBean = invokeDisposableBean; + this.destroyMethodName = destroyMethodName; + this.enforceDestroyMethod = enforceDestroyMethod; + this.beanPostProcessors = postProcessors; + } + + /** + * Search for all DestructionAwareBeanPostProcessors in the List. + * @param postProcessors the List to search + * @return the filtered List of DestructionAwareBeanPostProcessors + */ + private List filterPostProcessors(List postProcessors) { + List filteredPostProcessors = null; + if (postProcessors != null && !postProcessors.isEmpty()) { + filteredPostProcessors = new ArrayList(postProcessors.size()); + for (Iterator it = postProcessors.iterator(); it.hasNext();) { + Object postProcessor = it.next(); + if (postProcessor instanceof DestructionAwareBeanPostProcessor) { + filteredPostProcessors.add(postProcessor); + } + } + } + return filteredPostProcessors; + } + + + public void run() { + destroy(); + } + + public void destroy() { + if (this.beanPostProcessors != null && !this.beanPostProcessors.isEmpty()) { + for (int i = this.beanPostProcessors.size() - 1; i >= 0; i--) { + ((DestructionAwareBeanPostProcessor) this.beanPostProcessors.get(i)).postProcessBeforeDestruction( + this.bean, this.beanName); + } + } + + boolean isDisposableBean = (this.bean instanceof DisposableBean); + if (isDisposableBean && this.invokeDisposableBean) { + if (logger.isDebugEnabled()) { + logger.debug("Invoking destroy() on bean with name '" + this.beanName + "'"); + } + try { + ((DisposableBean) this.bean).destroy(); + } + catch (Throwable ex) { + String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'"; + if (logger.isDebugEnabled()) { + logger.warn(msg, ex); + } + else { + logger.warn(msg + ": " + ex); + } + } + } + + if (this.destroyMethodName != null && !(isDisposableBean && "destroy".equals(this.destroyMethodName))) { + invokeCustomDestroyMethod(); + } + } + + /** + * Invoke the specified custom destroy method on the given bean. + *

    This implementation invokes a no-arg method if found, else checking + * for a method with a single boolean argument (passing in "true", + * assuming a "force" parameter), else logging an error. + */ + private void invokeCustomDestroyMethod() { + try { + Method destroyMethod = + BeanUtils.findMethodWithMinimalParameters(this.bean.getClass(), this.destroyMethodName); + if (destroyMethod == null) { + if (this.enforceDestroyMethod) { + logger.warn("Couldn't find a destroy method named '" + this.destroyMethodName + + "' on bean with name '" + this.beanName + "'"); + } + } + + else { + Class[] paramTypes = destroyMethod.getParameterTypes(); + if (paramTypes.length > 1) { + logger.error("Method '" + this.destroyMethodName + "' of bean '" + this.beanName + + "' has more than one parameter - not supported as destroy method"); + } + else if (paramTypes.length == 1 && !paramTypes[0].equals(boolean.class)) { + logger.error("Method '" + this.destroyMethodName + "' of bean '" + this.beanName + + "' has a non-boolean parameter - not supported as destroy method"); + } + + else { + Object[] args = new Object[paramTypes.length]; + if (paramTypes.length == 1) { + args[0] = Boolean.TRUE; + } + if (logger.isDebugEnabled()) { + logger.debug("Invoking destroy method '" + this.destroyMethodName + + "' on bean with name '" + this.beanName + "'"); + } + ReflectionUtils.makeAccessible(destroyMethod); + try { + destroyMethod.invoke(this.bean, args); + } + catch (InvocationTargetException ex) { + String msg = "Invocation of destroy method '" + this.destroyMethodName + + "' failed on bean with name '" + this.beanName + "'"; + if (logger.isDebugEnabled()) { + logger.warn(msg, ex.getTargetException()); + } + else { + logger.warn(msg + ": " + ex.getTargetException()); + } + } + catch (Throwable ex) { + logger.error("Couldn't invoke destroy method '" + this.destroyMethodName + + "' on bean with name '" + this.beanName + "'", ex); + } + } + } + } + catch (IllegalArgumentException ex) { + // thrown from findMethodWithMinimalParameters + logger.error("Couldn't find a unique destroy method on bean with name '" + + this.beanName + ": " + ex.getMessage()); + } + } + + + /** + * Serializes a copy of the state of this class, + * filtering out non-serializable BeanPostProcessors. + */ + protected Object writeReplace() { + List serializablePostProcessors = null; + if (this.beanPostProcessors != null) { + serializablePostProcessors = new ArrayList(); + for (Iterator it = this.beanPostProcessors.iterator(); it.hasNext();) { + Object postProcessor = it.next(); + if (postProcessor instanceof Serializable) { + serializablePostProcessors.add(postProcessor); + } + } + } + return new DisposableBeanAdapter(this.bean, this.beanName, this.invokeDisposableBean, + this.destroyMethodName, this.enforceDestroyMethod, serializablePostProcessors); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/FactoryBeanRegistrySupport.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,188 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.security.AccessControlContext; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Map; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanCurrentlyInCreationException; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.FactoryBeanNotInitializedException; +import org.springframework.core.CollectionFactory; + +/** + * Support base class for singleton registries which need to handle + * {@link org.springframework.beans.factory.FactoryBean} instances, + * integrated with {@link DefaultSingletonBeanRegistry}'s singleton management. + * + *

    Serves as base class for {@link AbstractBeanFactory}. + * + * @author Juergen Hoeller + * @since 2.5.1 + */ +public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry { + + /** Cache of singleton objects created by FactoryBeans: FactoryBean name --> object */ + private final Map factoryBeanObjectCache = CollectionFactory.createConcurrentMapIfPossible(16); + + + /** + * Determine the type for the given FactoryBean. + * @param factoryBean the FactoryBean instance to check + * @return the FactoryBean's object type, + * or null if the type cannot be determined yet + */ + protected Class getTypeForFactoryBean(FactoryBean factoryBean) { + try { + return factoryBean.getObjectType(); + } + catch (Throwable ex) { + // Thrown from the FactoryBean's getObjectType implementation. + logger.warn("FactoryBean threw exception from getObjectType, despite the contract saying " + + "that it should return null if the type of its object cannot be determined yet", ex); + return null; + } + } + + /** + * Obtain an object to expose from the given FactoryBean, if available + * in cached form. Quick check for minimal synchronization. + * @param beanName the name of the bean + * @return the object obtained from the FactoryBean, + * or null if not available + */ + protected Object getCachedObjectForFactoryBean(String beanName) { + Object object = this.factoryBeanObjectCache.get(beanName); + return (object != NULL_OBJECT ? object : null); + } + + /** + * Obtain an object to expose from the given FactoryBean. + * @param factory the FactoryBean instance + * @param beanName the name of the bean + * @param shouldPostProcess whether the bean is subject for post-processing + * @return the object obtained from the FactoryBean + * @throws BeanCreationException if FactoryBean object creation failed + * @see org.springframework.beans.factory.FactoryBean#getObject() + */ + protected Object getObjectFromFactoryBean(FactoryBean factory, String beanName, boolean shouldPostProcess) { + if (factory.isSingleton() && containsSingleton(beanName)) { + synchronized (getSingletonMutex()) { + Object object = this.factoryBeanObjectCache.get(beanName); + if (object == null) { + object = doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess); + this.factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT)); + } + return (object != NULL_OBJECT ? object : null); + } + } + else { + return doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess); + } + } + + /** + * Obtain an object to expose from the given FactoryBean. + * @param factory the FactoryBean instance + * @param beanName the name of the bean + * @param shouldPostProcess whether the bean is subject for post-processing + * @return the object obtained from the FactoryBean + * @throws BeanCreationException if FactoryBean object creation failed + * @see org.springframework.beans.factory.FactoryBean#getObject() + */ + private Object doGetObjectFromFactoryBean( + final FactoryBean factory, final String beanName, final boolean shouldPostProcess) + throws BeanCreationException { + + AccessControlContext acc = AccessController.getContext(); + return AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + Object object; + + try { + object = factory.getObject(); + } + catch (FactoryBeanNotInitializedException ex) { + throw new BeanCurrentlyInCreationException(beanName, ex.toString()); + } + catch (Throwable ex) { + throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex); + } + + // Do not accept a null value for a FactoryBean that's not fully + // initialized yet: Many FactoryBeans just return null then. + if (object == null && isSingletonCurrentlyInCreation(beanName)) { + throw new BeanCurrentlyInCreationException( + beanName, "FactoryBean which is currently in creation returned null from getObject"); + } + + if (object != null && shouldPostProcess) { + try { + object = postProcessObjectFromFactoryBean(object, beanName); + } + catch (Throwable ex) { + throw new BeanCreationException(beanName, "Post-processing of the FactoryBean's object failed", ex); + } + } + + return object; + } + }, acc); + } + + /** + * Post-process the given object that has been obtained from the FactoryBean. + * The resulting object will get exposed for bean references. + *

    The default implementation simply returns the given object as-is. + * Subclasses may override this, for example, to apply post-processors. + * @param object the object obtained from the FactoryBean. + * @param beanName the name of the bean + * @return the object to expose + * @throws org.springframework.beans.BeansException if any post-processing failed + */ + protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException { + return object; + } + + /** + * Get a FactoryBean for the given bean if possible. + * @param beanName the name of the bean + * @param beanInstance the corresponding bean instance + * @return the bean instance as FactoryBean + * @throws BeansException if the given bean cannot be exposed as a FactoryBean + */ + protected FactoryBean getFactoryBean(String beanName, Object beanInstance) throws BeansException { + if (!(beanInstance instanceof FactoryBean)) { + throw new BeanCreationException(beanName, + "Bean instance of type [" + beanInstance.getClass() + "] is not a FactoryBean"); + } + return (FactoryBean) beanInstance; + } + + /** + * Overridden to clear the FactoryBean object cache as well. + */ + protected void removeSingleton(String beanName) { + super.removeSingleton(beanName); + this.factoryBeanObjectCache.remove(beanName); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/GenericBeanDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/GenericBeanDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/GenericBeanDefinition.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.factory.config.BeanDefinition; + +/** + * GenericBeanDefinition is a one-stop shop for standard bean definition purposes. + * Like any bean definition, it allows for specifying a class plus optionally + * constructor argument values and property values. Additionally, deriving from a + * parent bean definition can be flexibly configured through the "parentName" property. + * + *

    In general, use this GenericBeanDefinition class for the purpose of + * registering user-visible bean definitions (which a post-processor might operate on, + * potentially even reconfiguring the parent name). Use RootBeanDefinition / + * ChildBeanDefinition where parent/child relationships happen to be pre-determined. + * + * @author Juergen Hoeller + * @since 2.5 + * @see #setParentName + * @see RootBeanDefinition + * @see ChildBeanDefinition + */ +public class GenericBeanDefinition extends AbstractBeanDefinition { + + private String parentName; + + + /** + * Create a new GenericBeanDefinition, to be configured through its bean + * properties and configuration methods. + * @see #setBeanClass + * @see #setBeanClassName + * @see #setScope + * @see #setAutowireMode + * @see #setDependencyCheck + * @see #setConstructorArgumentValues + * @see #setPropertyValues + */ + public GenericBeanDefinition() { + super(); + } + + /** + * Create a new GenericBeanDefinition as deep copy of the given + * bean definition. + * @param original the original bean definition to copy from + */ + public GenericBeanDefinition(BeanDefinition original) { + super(original); + } + + + public void setParentName(String parentName) { + this.parentName = parentName; + } + + public String getParentName() { + return this.parentName; + } + + + public AbstractBeanDefinition cloneBeanDefinition() { + return new GenericBeanDefinition(this); + } + + public boolean equals(Object other) { + return (this == other || (other instanceof GenericBeanDefinition && super.equals(other))); + } + + public String toString() { + return "Generic bean: " + super.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/InstantiationStrategy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/InstantiationStrategy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/InstantiationStrategy.java 17 Aug 2012 15:11:30 -0000 1.1 @@ -0,0 +1,85 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; + +/** + * Interface responsible for creating instances corresponding to a root bean definition. + * + *

    This is pulled out into a strategy as various approaches are possible, + * including using CGLIB to create subclasses on the fly to support Method Injection. + * + * @author Rod Johnson + * @since 1.1 + */ +public interface InstantiationStrategy { + + /** + * Return an instance of the bean with the given name in this factory. + * @param beanDefinition the bean definition + * @param beanName name of the bean when it's created in this context. + * The name can be null if we're autowiring a bean that + * doesn't belong to the factory. + * @param owner owning BeanFactory + * @return a bean instance for this bean definition + * @throws BeansException if the instantiation failed + */ + Object instantiate( + RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) throws BeansException; + + /** + * Return an instance of the bean with the given name in this factory, + * creating it via the given constructor. + * @param beanDefinition the bean definition + * @param beanName name of the bean when it's created in this context. + * The name can be null if we're autowiring a bean + * that doesn't belong to the factory. + * @param owner owning BeanFactory + * @param ctor the constructor to use + * @param args the constructor arguments to apply + * @return a bean instance for this bean definition + * @throws BeansException if the instantiation failed + */ + Object instantiate( + RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, + Constructor ctor, Object[] args) throws BeansException; + + /** + * Return an instance of the bean with the given name in this factory, + * creating it via the given factory method. + * @param beanDefinition bean definition + * @param beanName name of the bean when it's created in this context. + * The name can be null if we're autowiring a bean + * that doesn't belong to the factory. + * @param owner owning BeanFactory + * @param factoryBean the factory bean instance to call the factory method on, + * or null in case of a static factory method + * @param factoryMethod the factory method to use + * @param args the factory method arguments to apply + * @return a bean instance for this bean definition + * @throws BeansException if the instantiation failed + */ + Object instantiate( + RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, + Object factoryBean, Method factoryMethod, Object[] args) throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/LookupOverride.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/LookupOverride.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/LookupOverride.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.lang.reflect.Method; + +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + +/** + * Represents an override of a method that looks up an object in the same IoC context. + * + *

    Methods eligible for lookup override must not have arguments. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 1.1 + */ +public class LookupOverride extends MethodOverride { + + private final String beanName; + + + /** + * Construct a new LookupOverride. + * @param methodName the name of the method to override. + * This method must have no arguments. + * @param beanName name of the bean in the current BeanFactory + * that the overriden method should return + */ + public LookupOverride(String methodName, String beanName) { + super(methodName); + Assert.notNull(beanName, "Bean name must not be null"); + this.beanName = beanName; + } + + /** + * Return the name of the bean that should be returned by this method. + */ + public String getBeanName() { + return this.beanName; + } + + + /** + * Match method of the given name, with no parameters. + */ + public boolean matches(Method method) { + return (method.getName().equals(getMethodName()) && method.getParameterTypes().length == 0); + } + + + public String toString() { + return "LookupOverride for method '" + getMethodName() + "'; will return bean '" + this.beanName + "'"; + } + + public boolean equals(Object other) { + return (other instanceof LookupOverride && super.equals(other) && + ObjectUtils.nullSafeEquals(this.beanName, ((LookupOverride) other).beanName)); + } + + public int hashCode() { + return (29 * super.hashCode() + ObjectUtils.nullSafeHashCode(this.beanName)); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/ManagedList.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/ManagedList.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/ManagedList.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.beans.Mergeable; + +/** + * Tag collection class used to hold managed List elements, which may + * include runtime bean references (to be resolved into bean objects). + * + * @author Rod Johnson + * @author Rob Harrop + * @author Juergen Hoeller + * @since 27.05.2003 + */ +public class ManagedList extends ArrayList implements Mergeable, BeanMetadataElement { + + private Object source; + + private boolean mergeEnabled; + + + public ManagedList() { + } + + public ManagedList(int initialCapacity) { + super(initialCapacity); + } + + + /** + * Set the configuration source Object for this metadata element. + *

    The exact type of the object will depend on the configuration mechanism used. + */ + public void setSource(Object source) { + this.source = source; + } + + public Object getSource() { + return this.source; + } + + /** + * Set whether merging should be enabled for this collection, + * in case of a 'parent' collection value being present. + */ + public void setMergeEnabled(boolean mergeEnabled) { + this.mergeEnabled = mergeEnabled; + } + + public boolean isMergeEnabled() { + return this.mergeEnabled; + } + + public Object merge(Object parent) { + if (!this.mergeEnabled) { + throw new IllegalStateException("Not allowed to merge when the 'mergeEnabled' property is set to 'false'"); + } + if (parent == null) { + return this; + } + if (!(parent instanceof List)) { + throw new IllegalArgumentException("Cannot merge with object of type [" + parent.getClass() + "]"); + } + List merged = new ManagedList(); + merged.addAll((List) parent); + merged.addAll(this); + return merged; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/ManagedMap.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/ManagedMap.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/ManagedMap.java 17 Aug 2012 15:11:31 -0000 1.1 @@ -0,0 +1,88 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.beans.Mergeable; + +/** + * Tag collection class used to hold managed Map values, which may + * include runtime bean references (to be resolved into bean objects). + * + * @author Juergen Hoeller + * @author Rob Harrop + * @since 27.05.2003 + */ +public class ManagedMap extends LinkedHashMap implements Mergeable, BeanMetadataElement { + + private Object source; + + private boolean mergeEnabled; + + + public ManagedMap() { + } + + public ManagedMap(int initialCapacity) { + super(initialCapacity); + } + + + /** + * Set the configuration source Object for this metadata element. + *

    The exact type of the object will depend on the configuration mechanism used. + */ + public void setSource(Object source) { + this.source = source; + } + + public Object getSource() { + return this.source; + } + + /** + * Set whether merging should be enabled for this collection, + * in case of a 'parent' collection value being present. + */ + public void setMergeEnabled(boolean mergeEnabled) { + this.mergeEnabled = mergeEnabled; + } + + public boolean isMergeEnabled() { + return this.mergeEnabled; + } + + public Object merge(Object parent) { + if (!this.mergeEnabled) { + throw new IllegalStateException("Not allowed to merge when the 'mergeEnabled' property is set to 'false'"); + } + if (parent == null) { + return this; + } + if (!(parent instanceof Map)) { + throw new IllegalArgumentException("Cannot merge with object of type [" + parent.getClass() + "]"); + } + Map merged = new ManagedMap(); + merged.putAll((Map) parent); + merged.putAll(this); + return merged; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/ManagedProperties.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/ManagedProperties.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/ManagedProperties.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.util.Properties; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.beans.Mergeable; + +/** + * Tag class which represents a Spring-managed {@link Properties} instance + * that supports merging of parent/child definitions. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public class ManagedProperties extends Properties implements Mergeable, BeanMetadataElement { + + private Object source; + + private boolean mergeEnabled; + + + /** + * Set the configuration source Object for this metadata element. + *

    The exact type of the object will depend on the configuration mechanism used. + */ + public void setSource(Object source) { + this.source = source; + } + + public Object getSource() { + return this.source; + } + + /** + * Set whether merging should be enabled for this collection, + * in case of a 'parent' collection value being present. + */ + public void setMergeEnabled(boolean mergeEnabled) { + this.mergeEnabled = mergeEnabled; + } + + public boolean isMergeEnabled() { + return this.mergeEnabled; + } + + + public Object merge(Object parent) { + if (!this.mergeEnabled) { + throw new IllegalStateException("Not allowed to merge when the 'mergeEnabled' property is set to 'false'"); + } + if (parent == null) { + return this; + } + if (!(parent instanceof Properties)) { + throw new IllegalArgumentException("Cannot merge with object of type [" + parent.getClass() + "]"); + } + Properties merged = new ManagedProperties(); + merged.putAll((Properties) parent); + merged.putAll(this); + return merged; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/ManagedSet.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/ManagedSet.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/ManagedSet.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,90 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.Set; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.beans.Mergeable; + +/** + * Tag collection class used to hold managed Set values, which may + * include runtime bean references (to be resolved into bean objects). + * + * @author Juergen Hoeller + * @author Rob Harrop + * @since 21.01.2004 + */ +public class ManagedSet extends LinkedHashSet implements Mergeable, BeanMetadataElement { + + private Object source; + + private boolean mergeEnabled; + + + public ManagedSet() { + } + + public ManagedSet(int initialCapacity) { + super(initialCapacity); + } + + + /** + * Set the configuration source Object for this metadata element. + *

    The exact type of the object will depend on the configuration mechanism used. + */ + public void setSource(Object source) { + this.source = source; + } + + public Object getSource() { + return this.source; + } + + /** + * Set whether merging should be enabled for this collection, + * in case of a 'parent' collection value being present. + */ + public void setMergeEnabled(boolean mergeEnabled) { + this.mergeEnabled = mergeEnabled; + } + + public boolean isMergeEnabled() { + return this.mergeEnabled; + } + + public Object merge(Object parent) { + if (!this.mergeEnabled) { + throw new IllegalStateException("Not allowed to merge when the 'mergeEnabled' property is set to 'false'"); + } + if (parent == null) { + return this; + } + if (!(parent instanceof Set)) { + throw new IllegalArgumentException("Cannot merge with object of type [" + parent.getClass() + "]"); + } + Set merged = new ManagedSet(); + merged.addAll((Set) parent); + merged.addAll(this); + return merged; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/MergedBeanDefinitionPostProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/MergedBeanDefinitionPostProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/MergedBeanDefinitionPostProcessor.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.factory.config.BeanPostProcessor; + +/** + * Post-processor callback interface for merged bean definitions at runtime. + * {@link BeanPostProcessor} implementations may implement this sub-interface in + * order to post-process the merged bean definition that the Spring BeanFactory + * uses to create a specific bean instance. + * + *

    The {@link #postProcessMergedBeanDefinition} method may for example introspect + * the bean definition in order to prepare some cached metadata before post-processing + * actual instances of a bean. It is also allowed to modify the bean definition + * but only for bean definition properties which are actually intended + * for concurrent modification. Basically, this only applies to operations + * defined on the {@link RootBeanDefinition} itself but not to the properties + * of its base classes. + * + * @author Juergen Hoeller + * @since 2.5 + */ +public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor { + + /** + * Post-process the given merged bean definition for the specified bean. + * @param beanDefinition the merged bean definition for the bean + * @param beanType the actual type of the managed bean instance + * @param beanName the name of the bean + */ + void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/MethodOverride.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/MethodOverride.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/MethodOverride.java 17 Aug 2012 15:11:30 -0000 1.1 @@ -0,0 +1,121 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.lang.reflect.Method; + +import org.springframework.beans.BeanMetadataElement; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + +/** + * Object representing the override of a method on a managed + * object by the IoC container. + * + *

    Note that the override mechanism is not intended as a + * generic means of inserting crosscutting code: use AOP for that. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 1.1 + */ +public abstract class MethodOverride implements BeanMetadataElement { + + private final String methodName; + + private boolean overloaded = true; + + private Object source; + + + /** + * Construct a new override for the given method. + * @param methodName the name of the method to override + */ + protected MethodOverride(String methodName) { + Assert.notNull(methodName, "Method name must not be null"); + this.methodName = methodName; + } + + /** + * Return the name of the method to be overridden. + */ + public String getMethodName() { + return this.methodName; + } + + /** + * Set whether the overridden method has to be considered as overloaded + * (that is, whether arg type matching has to happen). + *

    Default is "true"; can be switched to "false" to optimize runtime performance. + */ + protected void setOverloaded(boolean overloaded) { + this.overloaded = overloaded; + } + + /** + * Return whether the overridden method has to be considered as overloaded + * (that is, whether arg type matching has to happen). + */ + protected boolean isOverloaded() { + return this.overloaded; + } + + /** + * Set the configuration source Object for this metadata element. + *

    The exact type of the object will depend on the configuration mechanism used. + */ + public void setSource(Object source) { + this.source = source; + } + + public Object getSource() { + return this.source; + } + + + /** + * Subclasses must override this to indicate whether they match + * the given method. This allows for argument list checking + * as well as method name checking. + * @param method the method to check + * @return whether this override matches the given method + */ + public abstract boolean matches(Method method); + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof MethodOverride)) { + return false; + } + MethodOverride that = (MethodOverride) other; + return (ObjectUtils.nullSafeEquals(this.methodName, that.methodName) && + this.overloaded == that.overloaded && + ObjectUtils.nullSafeEquals(this.source, that.source)); + } + + public int hashCode() { + int hashCode = ObjectUtils.nullSafeHashCode(this.methodName); + hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.source); + hashCode = 29 * hashCode + (this.overloaded ? 1 : 0); + return hashCode; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/MethodOverrides.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/MethodOverrides.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/MethodOverrides.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,117 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +/** + * Set of method overrides, determining which, if any, methods on a + * managed object the Spring IoC container will override at runtime. + * + *

    The currently supported {@link MethodOverride} variants are + * {@link LookupOverride} and {@link ReplaceOverride}. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 1.1 + * @see MethodOverride + */ +public class MethodOverrides { + + private final Set overrides = new HashSet(); + + + /** + * Create new MethodOverrides. + */ + public MethodOverrides() { + } + + /** + * Deep copy constructor. + */ + public MethodOverrides(MethodOverrides other) { + addOverrides(other); + } + + + /** + * Copy all given method overrides into this object. + */ + public void addOverrides(MethodOverrides other) { + if (other != null) { + this.overrides.addAll(other.getOverrides()); + } + } + + /** + * Add the given method override. + */ + public void addOverride(MethodOverride override) { + this.overrides.add(override); + } + + /** + * Return all method overrides contained by this object. + * @return Set of MethodOverride objects + * @see MethodOverride + */ + public Set getOverrides() { + return this.overrides; + } + + /** + * Return whether the set of method overrides is empty. + */ + public boolean isEmpty() { + return this.overrides.isEmpty(); + } + + /** + * Return the override for the given method, if any. + * @param method method to check for overrides for + * @return the method override, or null if none + */ + public MethodOverride getOverride(Method method) { + for (Iterator it = this.overrides.iterator(); it.hasNext();) { + MethodOverride methodOverride = (MethodOverride) it.next(); + if (methodOverride.matches(method)) { + return methodOverride; + } + } + return null; + } + + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + MethodOverrides that = (MethodOverrides) o; + + if (!this.overrides.equals(that.overrides)) return false; + + return true; + } + + public int hashCode() { + return this.overrides.hashCode(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/MethodReplacer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/MethodReplacer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/MethodReplacer.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.lang.reflect.Method; + +/** + * Interface to be implemented by classes that can reimplement any method + * on an IoC-managed object: the Method Injection form of + * Dependency Injection. + * + *

    Such methods may be (but need not be) abstract, in which case the + * container will create a concrete subclass to instantiate. + * + * @author Rod Johnson + * @since 1.1 + */ +public interface MethodReplacer { + + /** + * Reimplement the given method. + * @param obj the instance we're reimplementing the method for + * @param method the method to reimplement + * @param args arguments to the method + * @return return value for the method + */ + Object reimplement(Object obj, Method method, Object[] args) throws Throwable; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,550 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Properties; +import java.util.ResourceBundle; + +import org.springframework.beans.BeansException; +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.PropertyAccessor; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.CannotLoadBeanClassException; +import org.springframework.beans.factory.config.ConstructorArgumentValues; +import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.EncodedResource; +import org.springframework.util.DefaultPropertiesPersister; +import org.springframework.util.PropertiesPersister; +import org.springframework.util.StringUtils; + +/** + * Bean definition reader for a simple properties format. + * + *

    Provides bean definition registration methods for Map/Properties and + * ResourceBundle. Typically applied to a DefaultListableBeanFactory. + * + *

    Example: + * + *

    + * employee.(class)=MyClass       // bean is of class MyClass
    + * employee.(abstract)=true       // this bean can't be instantiated directly
    + * employee.group=Insurance       // real property
    + * employee.usesDialUp=false      // real property (potentially overridden)
    + *
    + * salesrep.(parent)=employee     // derives from "employee" bean definition
    + * salesrep.(lazy-init)=true      // lazily initialize this singleton bean
    + * salesrep.manager(ref)=tony     // reference to another bean
    + * salesrep.department=Sales      // real property
    + *
    + * techie.(parent)=employee       // derives from "employee" bean definition
    + * techie.(scope)=prototype       // bean is a prototype (not a shared instance)
    + * techie.manager(ref)=jeff       // reference to another bean
    + * techie.department=Engineering  // real property
    + * techie.usesDialUp=true         // real property (overriding parent value)
    + *
    + * ceo.$0(ref)=secretary          // inject 'secretary' bean as 0th constructor arg
    + * ceo.$1=1000000                 // inject value '1000000' at 1st constructor arg
    + * 
    + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + * @since 26.11.2003 + * @see DefaultListableBeanFactory + */ +public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader { + + /** + * Value of a T/F attribute that represents true. + * Anything else represents false. Case seNsItive. + */ + public static final String TRUE_VALUE = "true"; + + /** + * Separator between bean name and property name. + * We follow normal Java conventions. + */ + public static final String SEPARATOR = "."; + + /** + * Special key to distinguish owner.(class)=com.myapp.MyClass- + */ + public static final String CLASS_KEY = "(class)"; + + /** + * Special key to distinguish owner.class=com.myapp.MyClass. + * Deprecated in favor of .(class)= + */ + private static final String DEPRECATED_CLASS_KEY = "class"; + + /** + * Special key to distinguish owner.(parent)=parentBeanName. + */ + public static final String PARENT_KEY = "(parent)"; + + /** + * Special key to distinguish owner.(scope)=prototype. + * Default is "true". + */ + public static final String SCOPE_KEY = "(scope)"; + + /** + * Special key to distinguish owner.(singleton)=false. + * Default is "true". + */ + public static final String SINGLETON_KEY = "(singleton)"; + + /** + * Special key to distinguish owner.(abstract)=true + * Default is "false". + */ + public static final String ABSTRACT_KEY = "(abstract)"; + + /** + * Special key to distinguish owner.(lazy-init)=true + * Default is "false". + */ + public static final String LAZY_INIT_KEY = "(lazy-init)"; + + /** + * Property suffix for references to other beans in the current + * BeanFactory: e.g. owner.dog(ref)=fido. + * Whether this is a reference to a singleton or a prototype + * will depend on the definition of the target bean. + */ + public static final String REF_SUFFIX = "(ref)"; + + /** + * Prefix before values referencing other beans. + */ + public static final String REF_PREFIX = "*"; + + /** + * Prefix used to denote a constructor argument definition. + */ + public static final String CONSTRUCTOR_ARG_PREFIX = "$"; + + + private String defaultParentBean; + + private PropertiesPersister propertiesPersister = new DefaultPropertiesPersister(); + + + /** + * Create new PropertiesBeanDefinitionReader for the given bean factory. + * @param registry the BeanFactory to load bean definitions into, + * in the form of a BeanDefinitionRegistry + */ + public PropertiesBeanDefinitionReader(BeanDefinitionRegistry registry) { + super(registry); + } + + + /** + * Set the default parent bean for this bean factory. + * If a child bean definition handled by this factory provides neither + * a parent nor a class attribute, this default value gets used. + *

    Can be used e.g. for view definition files, to define a parent + * with a default view class and common attributes for all views. + * View definitions that define their own parent or carry their own + * class can still override this. + *

    Strictly speaking, the rule that a default parent setting does + * not apply to a bean definition that carries a class is there for + * backwards compatiblity reasons. It still matches the typical use case. + */ + public void setDefaultParentBean(String defaultParentBean) { + this.defaultParentBean = defaultParentBean; + } + + /** + * Return the default parent bean for this bean factory. + */ + public String getDefaultParentBean() { + return this.defaultParentBean; + } + + /** + * Set the PropertiesPersister to use for parsing properties files. + * The default is DefaultPropertiesPersister. + * @see org.springframework.util.DefaultPropertiesPersister + */ + public void setPropertiesPersister(PropertiesPersister propertiesPersister) { + this.propertiesPersister = + (propertiesPersister != null ? propertiesPersister : new DefaultPropertiesPersister()); + } + + /** + * Return the PropertiesPersister to use for parsing properties files. + */ + public PropertiesPersister getPropertiesPersister() { + return this.propertiesPersister; + } + + + /** + * Load bean definitions from the specified properties file, + * using all property keys (i.e. not filtering by prefix). + * @param resource the resource descriptor for the properties file + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + * @see #loadBeanDefinitions(org.springframework.core.io.Resource, String) + */ + public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException { + return loadBeanDefinitions(new EncodedResource(resource), null); + } + + /** + * Load bean definitions from the specified properties file. + * @param resource the resource descriptor for the properties file + * @param prefix a filter within the keys in the map: e.g. 'beans.' + * (can be empty or null) + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + */ + public int loadBeanDefinitions(Resource resource, String prefix) throws BeanDefinitionStoreException { + return loadBeanDefinitions(new EncodedResource(resource), prefix); + } + + /** + * Load bean definitions from the specified properties file. + * @param encodedResource the resource descriptor for the properties file, + * allowing to specify an encoding to use for parsing the file + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + */ + public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException { + return loadBeanDefinitions(encodedResource, null); + } + + /** + * Load bean definitions from the specified properties file. + * @param encodedResource the resource descriptor for the properties file, + * allowing to specify an encoding to use for parsing the file + * @param prefix a filter within the keys in the map: e.g. 'beans.' + * (can be empty or null) + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + */ + public int loadBeanDefinitions(EncodedResource encodedResource, String prefix) + throws BeanDefinitionStoreException { + + Properties props = new Properties(); + try { + InputStream is = encodedResource.getResource().getInputStream(); + try { + if (encodedResource.getEncoding() != null) { + getPropertiesPersister().load(props, new InputStreamReader(is, encodedResource.getEncoding())); + } + else { + getPropertiesPersister().load(props, is); + } + } + finally { + is.close(); + } + return registerBeanDefinitions(props, prefix, encodedResource.getResource().getDescription()); + } + catch (IOException ex) { + throw new BeanDefinitionStoreException("Could not parse properties from " + encodedResource.getResource(), ex); + } + } + + /** + * Register bean definitions contained in a resource bundle, + * using all property keys (i.e. not filtering by prefix). + * @param rb the ResourceBundle to load from + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + * @see #registerBeanDefinitions(java.util.ResourceBundle, String) + */ + public int registerBeanDefinitions(ResourceBundle rb) throws BeanDefinitionStoreException { + return registerBeanDefinitions(rb, null); + } + + /** + * Register bean definitions contained in a ResourceBundle. + *

    Similar syntax as for a Map. This method is useful to enable + * standard Java internationalization support. + * @param rb the ResourceBundle to load from + * @param prefix a filter within the keys in the map: e.g. 'beans.' + * (can be empty or null) + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + */ + public int registerBeanDefinitions(ResourceBundle rb, String prefix) throws BeanDefinitionStoreException { + // Simply create a map and call overloaded method. + Map map = new HashMap(); + Enumeration keys = rb.getKeys(); + while (keys.hasMoreElements()) { + String key = (String) keys.nextElement(); + map.put(key, rb.getObject(key)); + } + return registerBeanDefinitions(map, prefix); + } + + + /** + * Register bean definitions contained in a Map, + * using all property keys (i.e. not filtering by prefix). + * @param map Map: name -> property (String or Object). Property values + * will be strings if coming from a Properties file etc. Property names + * (keys) must be Strings. Class keys must be Strings. + * @return the number of bean definitions found + * @throws BeansException in case of loading or parsing errors + * @see #registerBeanDefinitions(java.util.Map, String, String) + */ + public int registerBeanDefinitions(Map map) throws BeansException { + return registerBeanDefinitions(map, null); + } + + /** + * Register bean definitions contained in a Map. + * Ignore ineligible properties. + * @param map Map name -> property (String or Object). Property values + * will be strings if coming from a Properties file etc. Property names + * (keys) must be Strings. Class keys must be Strings. + * @param prefix a filter within the keys in the map: e.g. 'beans.' + * (can be empty or null) + * @return the number of bean definitions found + * @throws BeansException in case of loading or parsing errors + */ + public int registerBeanDefinitions(Map map, String prefix) throws BeansException { + return registerBeanDefinitions(map, prefix, "Map " + map); + } + + /** + * Register bean definitions contained in a Map. + * Ignore ineligible properties. + * @param map Map name -> property (String or Object). Property values + * will be strings if coming from a Properties file etc. Property names + * (keys) must be strings. Class keys must be Strings. + * @param prefix a filter within the keys in the map: e.g. 'beans.' + * (can be empty or null) + * @param resourceDescription description of the resource that the + * Map came from (for logging purposes) + * @return the number of bean definitions found + * @throws BeansException in case of loading or parsing errors + * @see #registerBeanDefinitions(Map, String) + */ + public int registerBeanDefinitions(Map map, String prefix, String resourceDescription) + throws BeansException { + + if (prefix == null) { + prefix = ""; + } + int beanCount = 0; + + for (Iterator it = map.keySet().iterator(); it.hasNext();) { + Object key = it.next(); + if (!(key instanceof String)) { + throw new IllegalArgumentException("Illegal key [" + key + "]: only Strings allowed"); + } + String keyString = (String) key; + if (keyString.startsWith(prefix)) { + // Key is of form: prefix.property + String nameAndProperty = keyString.substring(prefix.length()); + // Find dot before property name, ignoring dots in property keys. + int sepIdx = -1; + int propKeyIdx = nameAndProperty.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX); + if (propKeyIdx != -1) { + sepIdx = nameAndProperty.lastIndexOf(SEPARATOR, propKeyIdx); + } + else { + sepIdx = nameAndProperty.lastIndexOf(SEPARATOR); + } + if (sepIdx != -1) { + String beanName = nameAndProperty.substring(0, sepIdx); + if (logger.isDebugEnabled()) { + logger.debug("Found bean name '" + beanName + "'"); + } + if (!getRegistry().containsBeanDefinition(beanName)) { + // If we haven't already registered it... + registerBeanDefinition(beanName, map, prefix + beanName, resourceDescription); + ++beanCount; + } + } + else { + // Ignore it: It wasn't a valid bean name and property, + // although it did start with the required prefix. + if (logger.isDebugEnabled()) { + logger.debug("Invalid bean name and property [" + nameAndProperty + "]"); + } + } + } + } + + return beanCount; + } + + /** + * Get all property values, given a prefix (which will be stripped) + * and add the bean they define to the factory with the given name + * @param beanName name of the bean to define + * @param map Map containing string pairs + * @param prefix prefix of each entry, which will be stripped + * @param resourceDescription description of the resource that the + * Map came from (for logging purposes) + * @throws BeansException if the bean definition could not be parsed or registered + */ + protected void registerBeanDefinition(String beanName, Map map, String prefix, String resourceDescription) + throws BeansException { + + String className = null; + String parent = null; + String scope = GenericBeanDefinition.SCOPE_SINGLETON; + boolean isAbstract = false; + boolean lazyInit = false; + + ConstructorArgumentValues cas = new ConstructorArgumentValues(); + MutablePropertyValues pvs = new MutablePropertyValues(); + + for (Iterator it = map.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + String key = StringUtils.trimWhitespace((String) entry.getKey()); + if (key.startsWith(prefix + SEPARATOR)) { + String property = key.substring(prefix.length() + SEPARATOR.length()); + if (isClassKey(property)) { + className = StringUtils.trimWhitespace((String) entry.getValue()); + } + else if (PARENT_KEY.equals(property)) { + parent = StringUtils.trimWhitespace((String) entry.getValue()); + } + else if (ABSTRACT_KEY.equals(property)) { + String val = StringUtils.trimWhitespace((String) entry.getValue()); + isAbstract = TRUE_VALUE.equals(val); + } + else if (SCOPE_KEY.equals(property)) { + // Spring 2.0 style + scope = StringUtils.trimWhitespace((String) entry.getValue()); + } + else if (SINGLETON_KEY.equals(property)) { + // Spring 1.2 style + String val = StringUtils.trimWhitespace((String) entry.getValue()); + scope = ((val == null || TRUE_VALUE.equals(val) ? + GenericBeanDefinition.SCOPE_SINGLETON : GenericBeanDefinition.SCOPE_PROTOTYPE)); + } + else if (LAZY_INIT_KEY.equals(property)) { + String val = StringUtils.trimWhitespace((String) entry.getValue()); + lazyInit = TRUE_VALUE.equals(val); + } + else if (property.startsWith(CONSTRUCTOR_ARG_PREFIX)) { + if (property.endsWith(REF_SUFFIX)) { + int index = Integer.parseInt(property.substring(1, property.length() - REF_SUFFIX.length())); + cas.addIndexedArgumentValue(index, new RuntimeBeanReference(entry.getValue().toString())); + } + else { + int index = Integer.parseInt(property.substring(1)); + cas.addIndexedArgumentValue(index, readValue(entry)); + } + } + else if (property.endsWith(REF_SUFFIX)) { + // This isn't a real property, but a reference to another prototype + // Extract property name: property is of form dog(ref) + property = property.substring(0, property.length() - REF_SUFFIX.length()); + String ref = StringUtils.trimWhitespace((String) entry.getValue()); + + // It doesn't matter if the referenced bean hasn't yet been registered: + // this will ensure that the reference is resolved at runtime. + Object val = new RuntimeBeanReference(ref); + pvs.addPropertyValue(property, val); + } + else{ + // It's a normal bean property. + pvs.addPropertyValue(property, readValue(entry)); + } + } + } + + if (logger.isDebugEnabled()) { + logger.debug("Registering bean definition for bean name '" + beanName + "' with " + pvs); + } + + // Just use default parent if we're not dealing with the parent itself, + // and if there's no class name specified. The latter has to happen for + // backwards compatibility reasons. + if (parent == null && className == null && !beanName.equals(this.defaultParentBean)) { + parent = this.defaultParentBean; + } + + try { + AbstractBeanDefinition bd = BeanDefinitionReaderUtils.createBeanDefinition( + parent, className, getBeanClassLoader()); + bd.setScope(scope); + bd.setAbstract(isAbstract); + bd.setLazyInit(lazyInit); + bd.setConstructorArgumentValues(cas); + bd.setPropertyValues(pvs); + getRegistry().registerBeanDefinition(beanName, bd); + } + catch (ClassNotFoundException ex) { + throw new CannotLoadBeanClassException(resourceDescription, beanName, className, ex); + } + catch (LinkageError err) { + throw new CannotLoadBeanClassException(resourceDescription, beanName, className, err); + } + } + + /** + * Indicates whether the supplied property matches the class property of + * the bean definition. + */ + private boolean isClassKey(String property) { + if (CLASS_KEY.equals(property)) { + return true; + } + else if (DEPRECATED_CLASS_KEY.equals(property)) { + if (logger.isWarnEnabled()) { + logger.warn("Use of 'class' property in [" + getClass().getName() + "] is deprecated in favor of '(class)'"); + } + return true; + } + return false; + } + + /** + * Reads the value of the entry. Correctly interprets bean references for + * values that are prefixed with an asterisk. + */ + private Object readValue(Map.Entry entry) { + Object val = entry.getValue(); + if (val instanceof String) { + String strVal = (String) val; + // If it starts with a reference prefix... + if (strVal.startsWith(REF_PREFIX)) { + // Expand the reference. + String targetName = strVal.substring(1); + if (targetName.startsWith(REF_PREFIX)) { + // Escaped prefix -> use plain value. + val = targetName; + } + else { + val = new RuntimeBeanReference(targetName); + } + } + } + return val; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/ReplaceOverride.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/ReplaceOverride.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/ReplaceOverride.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,123 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.lang.reflect.Method; +import java.util.LinkedList; +import java.util.List; + +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + +/** + * Extension of MethodOverride that represents an arbitrary + * override of a method by the IoC container. + * + *

    Any non-final method can be overridden, irrespective of its + * parameters and return types. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 1.1 + */ +public class ReplaceOverride extends MethodOverride { + + private final String methodReplacerBeanName; + + /** + * List of String. Identifying signatures. + */ + private List typeIdentifiers = new LinkedList(); + + + /** + * Construct a new ReplaceOverride. + * @param methodName the name of the method to override + * @param methodReplacerBeanName the bean name of the MethodReplacer + */ + public ReplaceOverride(String methodName, String methodReplacerBeanName) { + super(methodName); + Assert.notNull(methodName, "Method replacer bean name must not be null"); + this.methodReplacerBeanName = methodReplacerBeanName; + } + + /** + * Return the name of the bean implementing MethodReplacer. + */ + public String getMethodReplacerBeanName() { + return this.methodReplacerBeanName; + } + + /** + * Add a fragment of a class string, like "Exception" + * or "java.lang.Exc", to identify a parameter type. + * @param identifier a substring of the fully qualified class name + */ + public void addTypeIdentifier(String identifier) { + this.typeIdentifiers.add(identifier); + } + + + public boolean matches(Method method) { + // TODO could cache result for efficiency + if (!method.getName().equals(getMethodName())) { + // It can't match. + return false; + } + + if (!isOverloaded()) { + // No overloaded: don't worry about arg type matching. + return true; + } + + // If we get to here, we need to insist on precise argument matching. + if (this.typeIdentifiers.size() != method.getParameterTypes().length) { + return false; + } + for (int i = 0; i < this.typeIdentifiers.size(); i++) { + String identifier = (String) this.typeIdentifiers.get(i); + if (method.getParameterTypes()[i].getName().indexOf(identifier) == -1) { + // This parameter cannot match. + return false; + } + } + return true; + } + + + public String toString() { + return "Replace override for method '" + getMethodName() + "; will call bean '" + + this.methodReplacerBeanName + "'"; + } + + public boolean equals(Object other) { + if (!(other instanceof ReplaceOverride) || !super.equals(other)) { + return false; + } + ReplaceOverride that = (ReplaceOverride) other; + return (ObjectUtils.nullSafeEquals(this.methodReplacerBeanName, that.methodReplacerBeanName) && + ObjectUtils.nullSafeEquals(this.typeIdentifiers, that.typeIdentifiers)); + } + + public int hashCode() { + int hashCode = super.hashCode(); + hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.methodReplacerBeanName); + hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(this.typeIdentifiers); + return hashCode; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/RootBeanDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/RootBeanDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/RootBeanDefinition.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,257 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.lang.reflect.Member; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConstructorArgumentValues; + +/** + * A root bean definition represents the merged bean definition that backs + * a specific bean in a Spring BeanFactory at runtime. It might have been created + * from multiple original bean definitions that inherit from each other, + * typically registered as {@link GenericBeanDefinition GenericBeanDefinitions}. + * A root bean definition is essentially the 'unified' bean definition view at runtime. + * + *

    Root bean definitions may also be used for registering individual bean definitions + * in the configuration phase. However, since Spring 2.5, the preferred way to register + * bean definitions programmatically is the {@link GenericBeanDefinition} class. + * GenericBeanDefinition has the advantage that it allows to dynamically define + * parent dependencies, not 'hard-coding' the role as a root bean definition. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see GenericBeanDefinition + * @see ChildBeanDefinition + */ +public class RootBeanDefinition extends AbstractBeanDefinition { + + private final Set externallyManagedConfigMembers = Collections.synchronizedSet(new HashSet()); + + private final Set externallyManagedInitMethods = Collections.synchronizedSet(new HashSet()); + + private final Set externallyManagedDestroyMethods = Collections.synchronizedSet(new HashSet()); + + /** Package-visible field for caching the resolved constructor or factory method */ + volatile Object resolvedConstructorOrFactoryMethod; + + /** Package-visible field for caching fully resolved constructor arguments */ + volatile Object[] resolvedConstructorArguments; + + /** Package-visible field for caching partly prepared constructor arguments */ + volatile Object[] preparedConstructorArguments; + + /** Package-visible field that marks the constructor arguments as resolved */ + volatile boolean constructorArgumentsResolved = false; + + /** Package-visible field that indicates a before-instantiation post-processor having kicked in */ + volatile Boolean beforeInstantiationResolved; + + /** Package-visible field that indicates MergedBeanDefinitionPostProcessor having been applied */ + boolean postProcessed = false; + + final Object postProcessingLock = new Object(); + + + /** + * Create a new RootBeanDefinition, to be configured through its bean + * properties and configuration methods. + * @see #setBeanClass + * @see #setBeanClassName + * @see #setScope + * @see #setAutowireMode + * @see #setDependencyCheck + * @see #setConstructorArgumentValues + * @see #setPropertyValues + */ + public RootBeanDefinition() { + super(); + } + + /** + * Create a new RootBeanDefinition for a singleton. + * @param beanClass the class of the bean to instantiate + */ + public RootBeanDefinition(Class beanClass) { + super(); + setBeanClass(beanClass); + } + + /** + * Create a new RootBeanDefinition with the given singleton status. + * @param beanClass the class of the bean to instantiate + * @param singleton the singleton status of the bean + * @deprecated since Spring 2.5, in favor of {@link #setScope} + */ + public RootBeanDefinition(Class beanClass, boolean singleton) { + super(); + setBeanClass(beanClass); + setSingleton(singleton); + } + + /** + * Create a new RootBeanDefinition for a singleton, + * using the given autowire mode. + * @param beanClass the class of the bean to instantiate + * @param autowireMode by name or type, using the constants in this interface + */ + public RootBeanDefinition(Class beanClass, int autowireMode) { + super(); + setBeanClass(beanClass); + setAutowireMode(autowireMode); + } + + /** + * Create a new RootBeanDefinition for a singleton, + * using the given autowire mode. + * @param beanClass the class of the bean to instantiate + * @param autowireMode by name or type, using the constants in this interface + * @param dependencyCheck whether to perform a dependency check for objects + * (not applicable to autowiring a constructor, thus ignored there) + */ + public RootBeanDefinition(Class beanClass, int autowireMode, boolean dependencyCheck) { + super(); + setBeanClass(beanClass); + setAutowireMode(autowireMode); + if (dependencyCheck && getResolvedAutowireMode() != AUTOWIRE_CONSTRUCTOR) { + setDependencyCheck(RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS); + } + } + + /** + * Create a new RootBeanDefinition for a singleton, + * providing property values. + * @param beanClass the class of the bean to instantiate + * @param pvs the property values to apply + */ + public RootBeanDefinition(Class beanClass, MutablePropertyValues pvs) { + super(null, pvs); + setBeanClass(beanClass); + } + + /** + * Create a new RootBeanDefinition with the given singleton status, + * providing property values. + * @param beanClass the class of the bean to instantiate + * @param pvs the property values to apply + * @param singleton the singleton status of the bean + * @deprecated since Spring 2.5, in favor of {@link #setScope} + */ + public RootBeanDefinition(Class beanClass, MutablePropertyValues pvs, boolean singleton) { + super(null, pvs); + setBeanClass(beanClass); + setSingleton(singleton); + } + + /** + * Create a new RootBeanDefinition for a singleton, + * providing constructor arguments and property values. + * @param beanClass the class of the bean to instantiate + * @param cargs the constructor argument values to apply + * @param pvs the property values to apply + */ + public RootBeanDefinition(Class beanClass, ConstructorArgumentValues cargs, MutablePropertyValues pvs) { + super(cargs, pvs); + setBeanClass(beanClass); + } + + /** + * Create a new RootBeanDefinition for a singleton, + * providing constructor arguments and property values. + *

    Takes a bean class name to avoid eager loading of the bean class. + * @param beanClassName the name of the class to instantiate + * @param cargs the constructor argument values to apply + * @param pvs the property values to apply + */ + public RootBeanDefinition(String beanClassName, ConstructorArgumentValues cargs, MutablePropertyValues pvs) { + super(cargs, pvs); + setBeanClassName(beanClassName); + } + + /** + * Create a new RootBeanDefinition as deep copy of the given + * bean definition. + * @param original the original bean definition to copy from + */ + public RootBeanDefinition(RootBeanDefinition original) { + super((BeanDefinition) original); + } + + /** + * Create a new RootBeanDefinition as deep copy of the given + * bean definition. + * @param original the original bean definition to copy from + */ + RootBeanDefinition(BeanDefinition original) { + super(original); + } + + + public String getParentName() { + return null; + } + + public void setParentName(String parentName) { + if (parentName != null) { + throw new IllegalArgumentException("Root bean cannot be changed into a child bean with parent reference"); + } + } + + + public void registerExternallyManagedConfigMember(Member configMember) { + this.externallyManagedConfigMembers.add(configMember); + } + + public boolean isExternallyManagedConfigMember(Member configMember) { + return this.externallyManagedConfigMembers.contains(configMember); + } + + public void registerExternallyManagedInitMethod(String initMethod) { + this.externallyManagedInitMethods.add(initMethod); + } + + public boolean isExternallyManagedInitMethod(String initMethod) { + return this.externallyManagedInitMethods.contains(initMethod); + } + + public void registerExternallyManagedDestroyMethod(String destroyMethod) { + this.externallyManagedDestroyMethods.add(destroyMethod); + } + + public boolean isExternallyManagedDestroyMethod(String destroyMethod) { + return this.externallyManagedDestroyMethods.contains(destroyMethod); + } + + + public AbstractBeanDefinition cloneBeanDefinition() { + return new RootBeanDefinition(this); + } + + public boolean equals(Object other) { + return (this == other || (other instanceof RootBeanDefinition && super.equals(other))); + } + + public String toString() { + return "Root bean: " + super.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/SimpleAutowireCandidateResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/SimpleAutowireCandidateResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/SimpleAutowireCandidateResolver.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.config.DependencyDescriptor; + +/** + * {@link AutowireCandidateResolver} implementation to use when Java version + * is less than 1.5 and therefore no annotation support is available. This + * implementation checks the bean definition only. + * + * @author Mark Fisher + * @since 2.5 + * @see BeanDefinition#isAutowireCandidate() + */ +public class SimpleAutowireCandidateResolver implements AutowireCandidateResolver { + + /** + * Determine if the provided bean definition is an autowire candidate. + *

    To be considered a candidate the bean's autowire-candidate + * attribute must not have been set to 'false'. + */ + public boolean isAutowireCandidate( + BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) { + + return bdHolder.getBeanDefinition().isAutowireCandidate(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/SimpleBeanDefinitionRegistry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/SimpleBeanDefinitionRegistry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/SimpleBeanDefinitionRegistry.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.util.Map; + +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.core.CollectionFactory; +import org.springframework.core.SimpleAliasRegistry; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +/** + * Simple implementation of the {@link BeanDefinitionRegistry} interface. + * Provides registry capabilities only, with no factory capabilities built in. + * Can for example be used for testing bean definition readers. + * + * @author Juergen Hoeller + * @since 2.5.2 + */ +public class SimpleBeanDefinitionRegistry extends SimpleAliasRegistry implements BeanDefinitionRegistry { + + /** Map of bean definition objects, keyed by bean name */ + private final Map beanDefinitionMap = CollectionFactory.createConcurrentMapIfPossible(16); + + + public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) + throws BeanDefinitionStoreException { + + Assert.hasText(beanName, "'beanName' must not be empty"); + Assert.notNull(beanDefinition, "BeanDefinition must not be null"); + this.beanDefinitionMap.put(beanName, beanDefinition); + } + + public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { + if (this.beanDefinitionMap.remove(beanName) == null) { + throw new NoSuchBeanDefinitionException(beanName); + } + } + + public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { + BeanDefinition bd = (BeanDefinition) this.beanDefinitionMap.get(beanName); + if (bd == null) { + throw new NoSuchBeanDefinitionException(beanName); + } + return bd; + } + + public boolean containsBeanDefinition(String beanName) { + return this.beanDefinitionMap.containsKey(beanName); + } + + public String[] getBeanDefinitionNames() { + return StringUtils.toStringArray(this.beanDefinitionMap.keySet()); + } + + public int getBeanDefinitionCount() { + return this.beanDefinitionMap.size(); + } + + public boolean isBeanNameInUse(String beanName) { + return isAlias(beanName) || containsBeanDefinition(beanName); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java 17 Aug 2012 15:11:29 -0000 1.1 @@ -0,0 +1,132 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.springframework.beans.BeanInstantiationException; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; + +/** + * Simple object instantiation strategy for use in a BeanFactory. + * + *

    Does not support Method Injection, although it provides hooks for subclasses + * to override to add Method Injection support, for example by overriding methods. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 1.1 + */ +public class SimpleInstantiationStrategy implements InstantiationStrategy { + + public Object instantiate( + RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { + + // Don't override the class with CGLIB if no overrides. + if (beanDefinition.getMethodOverrides().isEmpty()) { + Constructor constructorToUse = (Constructor) beanDefinition.resolvedConstructorOrFactoryMethod; + if (constructorToUse == null) { + Class clazz = beanDefinition.getBeanClass(); + if (clazz.isInterface()) { + throw new BeanInstantiationException(clazz, "Specified class is an interface"); + } + try { + constructorToUse = clazz.getDeclaredConstructor((Class[]) null); + beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse; + } + catch (Exception ex) { + throw new BeanInstantiationException(clazz, "No default constructor found", ex); + } + } + return BeanUtils.instantiateClass(constructorToUse, null); + } + else { + // Must generate CGLIB subclass. + return instantiateWithMethodInjection(beanDefinition, beanName, owner); + } + } + + /** + * Subclasses can override this method, which is implemented to throw + * UnsupportedOperationException, if they can instantiate an object with + * the Method Injection specified in the given RootBeanDefinition. + * Instantiation should use a no-arg constructor. + */ + protected Object instantiateWithMethodInjection( + RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { + + throw new UnsupportedOperationException( + "Method Injection not supported in SimpleInstantiationStrategy"); + } + + public Object instantiate( + RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, + Constructor ctor, Object[] args) { + + if (beanDefinition.getMethodOverrides().isEmpty()) { + return BeanUtils.instantiateClass(ctor, args); + } + else { + return instantiateWithMethodInjection(beanDefinition, beanName, owner, ctor, args); + } + } + + /** + * Subclasses can override this method, which is implemented to throw + * UnsupportedOperationException, if they can instantiate an object with + * the Method Injection specified in the given RootBeanDefinition. + * Instantiation should use the given constructor and parameters. + */ + protected Object instantiateWithMethodInjection( + RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, + Constructor ctor, Object[] args) { + + throw new UnsupportedOperationException( + "Method Injection not supported in SimpleInstantiationStrategy"); + } + + public Object instantiate( + RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, + Object factoryBean, Method factoryMethod, Object[] args) { + + try { + // It's a static method if the target is null. + ReflectionUtils.makeAccessible(factoryMethod); + return factoryMethod.invoke(factoryBean, args); + } + catch (IllegalArgumentException ex) { + throw new BeanDefinitionStoreException( + "Illegal arguments to factory method [" + factoryMethod + "]; " + + "args: " + StringUtils.arrayToCommaDelimitedString(args)); + } + catch (IllegalAccessException ex) { + throw new BeanDefinitionStoreException( + "Cannot access factory method [" + factoryMethod + "]; is it public?"); + } + catch (InvocationTargetException ex) { + throw new BeanDefinitionStoreException( + "Factory method [" + factoryMethod + "] threw exception", ex.getTargetException()); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/StaticListableBeanFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/StaticListableBeanFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/StaticListableBeanFactory.java 17 Aug 2012 15:11:28 -0000 1.1 @@ -0,0 +1,249 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.support; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanFactoryUtils; +import org.springframework.beans.factory.BeanIsNotAFactoryException; +import org.springframework.beans.factory.BeanNotOfRequiredTypeException; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.SmartFactoryBean; +import org.springframework.util.StringUtils; + +/** + * Static {@link org.springframework.beans.factory.BeanFactory} implementation + * which allows to register existing singleton instances programmatically. + * Does not have support for prototype beans or aliases. + * + *

    Serves as example for a simple implementation of the + * {@link org.springframework.beans.factory.ListableBeanFactory} interface, + * managing existing bean instances rather than creating new ones based on bean + * definitions, and not implementing any extended SPI interfaces (such as + * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}). + * + *

    For a full-fledged factory based on bean definitions, have a look + * at {@link DefaultListableBeanFactory}. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 06.01.2003 + * @see DefaultListableBeanFactory + */ +public class StaticListableBeanFactory implements ListableBeanFactory { + + /** Map from bean name to bean instance */ + private final Map beans = new HashMap(); + + + /** + * Add a new singleton bean. + * Will overwrite any existing instance for the given name. + * @param name the name of the bean + * @param bean the bean instance + */ + public void addBean(String name, Object bean) { + this.beans.put(name, bean); + } + + + //--------------------------------------------------------------------- + // Implementation of BeanFactory interface + //--------------------------------------------------------------------- + + public Object getBean(String name) throws BeansException { + String beanName = BeanFactoryUtils.transformedBeanName(name); + Object bean = this.beans.get(beanName); + + if (bean == null) { + throw new NoSuchBeanDefinitionException(beanName, + "Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]"); + } + + // Don't let calling code try to dereference the + // bean factory if the bean isn't a factory + if (BeanFactoryUtils.isFactoryDereference(name) && !(bean instanceof FactoryBean)) { + throw new BeanIsNotAFactoryException(beanName, bean.getClass()); + } + + if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { + try { + return ((FactoryBean) bean).getObject(); + } + catch (Exception ex) { + throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex); + } + } + return bean; + } + + public Object getBean(String name, Class requiredType) throws BeansException { + Object bean = getBean(name); + if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) { + throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); + } + return bean; + } + + public Object getBean(String name, Object[] args) throws BeansException { + if (args != null) { + throw new UnsupportedOperationException( + "StaticListableBeanFactory does not support explicit bean creation arguments)"); + } + return getBean(name); + } + + public boolean containsBean(String name) { + return this.beans.containsKey(name); + } + + public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { + Object bean = getBean(name); + // In case of FactoryBean, return singleton status of created object. + return (bean instanceof FactoryBean && ((FactoryBean) bean).isSingleton()); + } + + public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { + Object bean = getBean(name); + // In case of FactoryBean, return prototype status of created object. + return ((bean instanceof SmartFactoryBean && ((SmartFactoryBean) bean).isPrototype()) || + (bean instanceof FactoryBean && !((FactoryBean) bean).isSingleton())); + } + + public boolean isTypeMatch(String name, Class targetType) throws NoSuchBeanDefinitionException { + Class type = getType(name); + return (targetType == null || (type != null && targetType.isAssignableFrom(type))); + } + + public Class getType(String name) throws NoSuchBeanDefinitionException { + String beanName = BeanFactoryUtils.transformedBeanName(name); + + Object bean = this.beans.get(beanName); + if (bean == null) { + throw new NoSuchBeanDefinitionException(beanName, + "Defined beans are [" + StringUtils.collectionToCommaDelimitedString(this.beans.keySet()) + "]"); + } + + if (bean instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { + // If it's a FactoryBean, we want to look at what it creates, not the factory class. + return ((FactoryBean) bean).getObjectType(); + } + return bean.getClass(); + } + + public String[] getAliases(String name) { + return new String[0]; + } + + + //--------------------------------------------------------------------- + // Implementation of ListableBeanFactory interface + //--------------------------------------------------------------------- + + public boolean containsBeanDefinition(String name) { + return this.beans.containsKey(name); + } + + public int getBeanDefinitionCount() { + return this.beans.size(); + } + + public String[] getBeanDefinitionNames() { + return StringUtils.toStringArray(this.beans.keySet()); + } + + public String[] getBeanNamesForType(Class type) { + return getBeanNamesForType(type, true, true); + } + + public String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean includeFactoryBeans) { + boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type)); + List matches = new ArrayList(); + Set keys = this.beans.keySet(); + Iterator it = keys.iterator(); + while (it.hasNext()) { + String name = (String) it.next(); + Object beanInstance = this.beans.get(name); + if (beanInstance instanceof FactoryBean && !isFactoryType) { + if (includeFactoryBeans) { + Class objectType = ((FactoryBean) beanInstance).getObjectType(); + if (objectType != null && type.isAssignableFrom(objectType)) { + matches.add(name); + } + } + } + else { + if (type.isInstance(beanInstance)) { + matches.add(name); + } + } + } + return StringUtils.toStringArray(matches); + } + + public Map getBeansOfType(Class type) throws BeansException { + return getBeansOfType(type, true, true); + } + + public Map getBeansOfType(Class type, boolean includeNonSingletons, boolean includeFactoryBeans) + throws BeansException { + + boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type)); + Map matches = new HashMap(); + + Iterator it = this.beans.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + String beanName = (String) entry.getKey(); + Object beanInstance = entry.getValue(); + + // Is bean a FactoryBean? + if (beanInstance instanceof FactoryBean && !isFactoryType) { + if (includeFactoryBeans) { + // Match object created by FactoryBean. + FactoryBean factory = (FactoryBean) beanInstance; + Class objectType = factory.getObjectType(); + if ((includeNonSingletons || factory.isSingleton()) && + objectType != null && type.isAssignableFrom(objectType)) { + matches.put(beanName, getBean(beanName)); + } + } + } + else { + if (type.isInstance(beanInstance)) { + // If type to match is FactoryBean, return FactoryBean itself. + // Else, return bean instance. + if (isFactoryType) { + beanName = FACTORY_BEAN_PREFIX + beanName; + } + matches.put(beanName, beanInstance); + } + } + } + return matches; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/support/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/support/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/support/package.html 17 Aug 2012 15:11:30 -0000 1.1 @@ -0,0 +1,9 @@ + + + +Classes supporting the org.springframework.beans.factory package. +Contains abstract base classes for BeanFactory implementations. + + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,180 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.wiring; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanCurrentlyInCreationException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; + +/** + * Convenient base class for configurers that can perform Dependency Injection + * on objects (however they may be created). Typically subclassed by AspectJ aspects. + * + *

    Subclasses may also need a custom metadata resolution strategy, in the + * {@link BeanWiringInfoResolver} interface. The default implementation looks + * for a bean with the same name as the fully-qualified class name. (This is + * the default name of the bean in a Spring XML file if the 'id' + * attribute is not used.) + + * @author Rob Harrop + * @author Rod Johnson + * @author Juergen Hoeller + * @author Adrian Colyer + * @since 2.0 + * @see #setBeanWiringInfoResolver + * @see ClassNameBeanWiringInfoResolver + */ +public class BeanConfigurerSupport implements BeanFactoryAware, InitializingBean, DisposableBean { + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + private volatile BeanWiringInfoResolver beanWiringInfoResolver; + + private volatile ConfigurableListableBeanFactory beanFactory; + + + /** + * Set the {@link BeanWiringInfoResolver} to use. + *

    The default behavior is to look for a bean with the same name as the class. + * As an alternative, consider using annotation-driven bean wiring. + * @see ClassNameBeanWiringInfoResolver + * @see org.springframework.beans.factory.annotation.AnnotationBeanWiringInfoResolver + */ + public void setBeanWiringInfoResolver(BeanWiringInfoResolver beanWiringInfoResolver) { + Assert.notNull(beanWiringInfoResolver, "BeanWiringInfoResolver must not be null"); + this.beanWiringInfoResolver = beanWiringInfoResolver; + } + + /** + * Set the {@link BeanFactory} in which this aspect must configure beans. + */ + public void setBeanFactory(BeanFactory beanFactory) { + if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { + throw new IllegalArgumentException( + "Bean configurer aspect needs to run in a ConfigurableListableBeanFactory: " + beanFactory); + } + this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; + if (this.beanWiringInfoResolver == null) { + this.beanWiringInfoResolver = createDefaultBeanWiringInfoResolver(); + } + } + + /** + * Create the default BeanWiringInfoResolver to be used if none was + * specified explicitly. + *

    The default implementation builds a {@link ClassNameBeanWiringInfoResolver}. + * @return the default BeanWiringInfoResolver (never null) + */ + protected BeanWiringInfoResolver createDefaultBeanWiringInfoResolver() { + return new ClassNameBeanWiringInfoResolver(); + } + + /** + * Check that a {@link BeanFactory} has been set. + */ + public void afterPropertiesSet() { + Assert.notNull(this.beanFactory, "BeanFactory must be set"); + } + + /** + * Release references to the {@link BeanFactory} and + * {@link BeanWiringInfoResolver} when the container is destroyed. + */ + public void destroy() { + this.beanFactory = null; + this.beanWiringInfoResolver = null; + } + + + /** + * Configure the bean instance. + *

    Subclasses can override this to provide custom configuration logic. + * Typically called by an aspect, for all bean instances matched by a + * pointcut. + * @param beanInstance the bean instance to configure (must not be null) + */ + public void configureBean(Object beanInstance) { + if (this.beanFactory == null) { + if (logger.isDebugEnabled()) { + logger.debug("BeanFactory has not been set on " + ClassUtils.getShortName(getClass()) + ": " + + "Make sure this configurer runs in a Spring container. Unable to configure bean of type [" + + ClassUtils.getDescriptiveType(beanInstance) + "]. Proceeding without injection."); + } + return; + } + + BeanWiringInfo bwi = this.beanWiringInfoResolver.resolveWiringInfo(beanInstance); + if (bwi == null) { + // Skip the bean if no wiring info given. + return; + } + + try { + if (bwi.indicatesAutowiring() || + (bwi.isDefaultBeanName() && !this.beanFactory.containsBean(bwi.getBeanName()))) { + // Perform autowiring (also applying standard factory / post-processor callbacks). + this.beanFactory.autowireBeanProperties(beanInstance, bwi.getAutowireMode(), bwi.getDependencyCheck()); + Object result = this.beanFactory.initializeBean(beanInstance, bwi.getBeanName()); + checkExposedObject(result, beanInstance); + } + else { + // Perform explicit wiring based on the specified bean definition. + Object result = this.beanFactory.configureBean(beanInstance, bwi.getBeanName()); + checkExposedObject(result, beanInstance); + } + } + catch (BeanCreationException ex) { + Throwable rootCause = ex.getMostSpecificCause(); + if (rootCause instanceof BeanCurrentlyInCreationException) { + BeanCreationException bce = (BeanCreationException) rootCause; + if (this.beanFactory.isCurrentlyInCreation(bce.getBeanName())) { + String msg = ClassUtils.getShortName(getClass()) + " failed to create target bean '" + + bce.getBeanName() + "' while configuring object of type [" + + beanInstance.getClass().getName() + "] (probably due to a circular reference). " + + "Proceeding without injection."; + if (logger.isDebugEnabled()) { + logger.debug(msg, ex); + } + else if (logger.isInfoEnabled()) { + logger.info(msg); + } + return; + } + } + throw ex; + } + } + + private void checkExposedObject(Object exposedObject, Object originalBeanInstance) { + if (exposedObject != originalBeanInstance) { + throw new IllegalStateException("Post-processor tried to replace bean instance of type [" + + originalBeanInstance.getClass().getName() + "] with (proxy) object of type [" + + exposedObject.getClass().getName() + "] - not supported for aspect-configured classes!"); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/wiring/BeanWiringInfo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/wiring/BeanWiringInfo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/wiring/BeanWiringInfo.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,149 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.wiring; + +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.util.Assert; + +/** + * Holder for bean wiring metadata information about a particular class. Used in + * conjunction with the {@link org.springframework.beans.factory.annotation.Configurable} + * annotation and the AspectJ AnnotationBeanConfigurerAspect. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + * @see BeanWiringInfoResolver + * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory + * @see org.springframework.beans.factory.annotation.Configurable + */ +public class BeanWiringInfo { + + /** + * Constant that indicates autowiring bean properties by name. + * @see #BeanWiringInfo(int, boolean) + * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#AUTOWIRE_BY_NAME + */ + public static final int AUTOWIRE_BY_NAME = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; + + /** + * Constant that indicates autowiring bean properties by type. + * @see #BeanWiringInfo(int, boolean) + * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#AUTOWIRE_BY_TYPE + */ + public static final int AUTOWIRE_BY_TYPE = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE; + + + private String beanName = null; + + private boolean isDefaultBeanName = false; + + private int autowireMode = AutowireCapableBeanFactory.AUTOWIRE_NO; + + private boolean dependencyCheck = false; + + + /** + * Create a default BeanWiringInfo that suggests plain initialization of + * factory and post-processor callbacks that the bean class may expect. + */ + public BeanWiringInfo() { + } + + /** + * Create a new BeanWiringInfo that points to the given bean name. + * @param beanName the name of the bean definition to take the property values from + * @throws IllegalArgumentException if the supplied beanName is null, + * is empty, or consists wholly of whitespace + */ + public BeanWiringInfo(String beanName) { + this(beanName, false); + } + + /** + * Create a new BeanWiringInfo that points to the given bean name. + * @param beanName the name of the bean definition to take the property values from + * @param isDefaultBeanName whether the given bean name is a suggested + * default bean name, not necessarily matching an actual bean definition + * @throws IllegalArgumentException if the supplied beanName is null, + * is empty, or consists wholly of whitespace + */ + public BeanWiringInfo(String beanName, boolean isDefaultBeanName) { + Assert.hasText(beanName, "'beanName' must not be empty"); + this.beanName = beanName; + this.isDefaultBeanName = isDefaultBeanName; + } + + /** + * Create a new BeanWiringInfo that indicates autowiring. + * @param autowireMode one of the constants {@link #AUTOWIRE_BY_NAME} / + * {@link #AUTOWIRE_BY_TYPE} + * @param dependencyCheck whether to perform a dependency check for object + * references in the bean instance (after autowiring) + * @throws IllegalArgumentException if the supplied autowireMode + * is not one of the allowed values + * @see #AUTOWIRE_BY_NAME + * @see #AUTOWIRE_BY_TYPE + */ + public BeanWiringInfo(int autowireMode, boolean dependencyCheck) { + if (autowireMode != AUTOWIRE_BY_NAME && autowireMode != AUTOWIRE_BY_TYPE) { + throw new IllegalArgumentException("Only constants AUTOWIRE_BY_NAME and AUTOWIRE_BY_TYPE supported"); + } + this.autowireMode = autowireMode; + this.dependencyCheck = dependencyCheck; + } + + + /** + * Return whether this BeanWiringInfo indicates autowiring. + */ + public boolean indicatesAutowiring() { + return (this.beanName == null); + } + + /** + * Return the specific bean name that this BeanWiringInfo points to, if any. + */ + public String getBeanName() { + return this.beanName; + } + + /** + * Return whether the specific bean name is a suggested default bean name, + * not necessarily matching an actual bean definition in the factory. + */ + public boolean isDefaultBeanName() { + return this.isDefaultBeanName; + } + + /** + * Return one of the constants {@link #AUTOWIRE_BY_NAME} / + * {@link #AUTOWIRE_BY_TYPE}, if autowiring is indicated. + */ + public int getAutowireMode() { + return this.autowireMode; + } + + /** + * Return whether to perform a dependency check for object references + * in the bean instance (after autowiring). + */ + public boolean getDependencyCheck() { + return this.dependencyCheck; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/wiring/BeanWiringInfoResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/wiring/BeanWiringInfoResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/wiring/BeanWiringInfoResolver.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.wiring; + +/** + * Strategy interface to be implemented by objects than can resolve bean name + * information, given a newly instantiated bean object. Invocations to the + * {@link #resolveWiringInfo} method on this interface will be driven by + * the AspectJ pointcut in the relevant concrete aspect. + * + *

    Metadata resolution strategy can be pluggable. A good default is + * {@link ClassNameBeanWiringInfoResolver}, which uses the fully-qualified + * class name as bean name. + * + * @author Rod Johnson + * @since 2.0 + * @see BeanWiringInfo + * @see ClassNameBeanWiringInfoResolver + * @see org.springframework.beans.factory.annotation.AnnotationBeanWiringInfoResolver + */ +public interface BeanWiringInfoResolver { + + /** + * Resolve the BeanWiringInfo for the given bean instance. + * @param beanInstance the bean instance to resolve info for + * @return the BeanWiringInfo, or null if not found + */ + BeanWiringInfo resolveWiringInfo(Object beanInstance); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolver.java 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.wiring; + +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; + +/** + * Simple default implementation of the {@link BeanWiringInfoResolver} interface, + * looking for a bean with the same name as the fully-qualified class name. + * This matches the default name of the bean in a Spring XML file if the + * bean tag's "id" attribute is not used. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 2.0 + */ +public class ClassNameBeanWiringInfoResolver implements BeanWiringInfoResolver { + + public BeanWiringInfo resolveWiringInfo(Object beanInstance) { + Assert.notNull(beanInstance, "Bean instance must not be null"); + return new BeanWiringInfo(ClassUtils.getUserClass(beanInstance).getName(), true); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/wiring/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/wiring/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/wiring/package.html 17 Aug 2012 15:11:41 -0000 1.1 @@ -0,0 +1,8 @@ + + + +Mechanism to determine bean wiring metadata from a bean instance. +Foundation for aspect-driven bean configuration. + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/AbstractBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/AbstractBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/AbstractBeanDefinitionParser.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,191 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.util.StringUtils; + +/** + * Abstract {@link BeanDefinitionParser} implementation providing + * a number of convenience methods and a + * {@link AbstractBeanDefinitionParser#parseInternal template method} + * that subclasses must override to provide the actual parsing logic. + * + *

    Use this {@link BeanDefinitionParser} implementation when you want + * to parse some arbitrarily complex XML into one or more + * {@link BeanDefinition BeanDefinitions}. If you just want to parse some + * XML into a single BeanDefinition, you may wish to consider + * the simpler convenience extensions of this class, namely + * {@link AbstractSingleBeanDefinitionParser} and + * {@link AbstractSimpleBeanDefinitionParser}. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @author Rick Evans + * @since 2.0 + */ +public abstract class AbstractBeanDefinitionParser implements BeanDefinitionParser { + + /** Constant for the id attribute */ + public static final String ID_ATTRIBUTE = "id"; + + + public final BeanDefinition parse(Element element, ParserContext parserContext) { + AbstractBeanDefinition definition = parseInternal(element, parserContext); + if (!parserContext.isNested()) { + try { + String id = resolveId(element, definition, parserContext); + if (!StringUtils.hasText(id)) { + parserContext.getReaderContext().error( + "Id is required for element '" + element.getLocalName() + "' when used as a top-level tag", element); + } + BeanDefinitionHolder holder = new BeanDefinitionHolder(definition, id); + registerBeanDefinition(holder, parserContext.getRegistry()); + if (shouldFireEvents()) { + BeanComponentDefinition componentDefinition = new BeanComponentDefinition(holder); + postProcessComponentDefinition(componentDefinition); + parserContext.registerComponent(componentDefinition); + } + } + catch (BeanDefinitionStoreException ex) { + parserContext.getReaderContext().error(ex.getMessage(), element); + return null; + } + } + return definition; + } + + /** + * Resolve the ID for the supplied {@link BeanDefinition}. + *

    When using {@link #shouldGenerateId generation}, a name is generated automatically. + * Otherwise, the ID is extracted from the "id" attribute, potentially with a + * {@link #shouldGenerateIdAsFallback() fallback} to a generated id. + * @param element the element that the bean definition has been built from + * @param definition the bean definition to be registered + * @param parserContext the object encapsulating the current state of the parsing process; + * provides access to a {@link org.springframework.beans.factory.support.BeanDefinitionRegistry} + * @return the resolved id + * @throws BeanDefinitionStoreException if no unique name could be generated + * for the given bean definition + */ + protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) + throws BeanDefinitionStoreException { + + if (shouldGenerateId()) { + return parserContext.getReaderContext().generateBeanName(definition); + } + else { + String id = element.getAttribute(ID_ATTRIBUTE); + if (!StringUtils.hasText(id) && shouldGenerateIdAsFallback()) { + id = parserContext.getReaderContext().generateBeanName(definition); + } + return id; + } + } + + /** + * Register the supplied {@link BeanDefinitionHolder bean} with the supplied + * {@link BeanDefinitionRegistry registry}. + *

    Subclasses can override this method to control whether or not the supplied + * {@link BeanDefinitionHolder bean} is actually even registered, or to + * register even more beans. + *

    The default implementation registers the supplied {@link BeanDefinitionHolder bean} + * with the supplied {@link BeanDefinitionRegistry registry} only if the isNested + * parameter is false, because one typically does not want inner beans + * to be registered as top level beans. + * @param definition the bean definition to be registered + * @param registry the registry that the bean is to be registered with + * @see BeanDefinitionReaderUtils#registerBeanDefinition(BeanDefinitionHolder, BeanDefinitionRegistry) + */ + protected void registerBeanDefinition(BeanDefinitionHolder definition, BeanDefinitionRegistry registry) { + BeanDefinitionReaderUtils.registerBeanDefinition(definition, registry); + } + + + /** + * Central template method to actually parse the supplied {@link Element} + * into one or more {@link BeanDefinition BeanDefinitions}. + * @param element the element that is to be parsed into one or more {@link BeanDefinition BeanDefinitions} + * @param parserContext the object encapsulating the current state of the parsing process; + * provides access to a {@link org.springframework.beans.factory.support.BeanDefinitionRegistry} + * @return the primary {@link BeanDefinition} resulting from the parsing of the supplied {@link Element} + * @see #parse(org.w3c.dom.Element, ParserContext) + * @see #postProcessComponentDefinition(org.springframework.beans.factory.parsing.BeanComponentDefinition) + */ + protected abstract AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext); + + /** + * Should an ID be generated instead of read from the passed in {@link Element}? + *

    Disabled by default; subclasses can override this to enable ID generation. + * Note that this flag is about always generating an ID; the parser + * won't even check for an "id" attribute in this case. + * @return whether the parser should always generate an id + */ + protected boolean shouldGenerateId() { + return false; + } + + /** + * Should an ID be generated instead if the passed in {@link Element} does not + * specify an "id" attribute explicitly? + *

    Disabled by default; subclasses can override this to enable ID generation + * as fallback: The parser will first check for an "id" attribute in this case, + * only falling back to a generated ID if no value was specified. + * @return whether the parser should generate an id if no id was specified + */ + protected boolean shouldGenerateIdAsFallback() { + return false; + } + + /** + * Controls whether this parser is supposed to fire a + * {@link org.springframework.beans.factory.parsing.BeanComponentDefinition} + * event after parsing the bean definition. + *

    This implementation returns true by default; that is, + * an event will be fired when a bean definition has been completely parsed. + * Override this to return false in order to suppress the event. + * @return true in order to fire a component registration event + * after parsing the bean definition; false to suppress the event + * @see #postProcessComponentDefinition + * @see org.springframework.beans.factory.parsing.ReaderContext#fireComponentRegistered + */ + protected boolean shouldFireEvents() { + return true; + } + + /** + * Hook method called after the primary parsing of a + * {@link BeanComponentDefinition} but before the + * {@link BeanComponentDefinition} has been registered with a + * {@link org.springframework.beans.factory.support.BeanDefinitionRegistry}. + *

    Derived classes can override this method to supply any custom logic that + * is to be executed after all the parsing is finished. + *

    The default implementation is a no-op. + * @param componentDefinition the {@link BeanComponentDefinition} that is to be processed + */ + protected void postProcessComponentDefinition(BeanComponentDefinition componentDefinition) { + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/AbstractSimpleBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/AbstractSimpleBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/AbstractSimpleBeanDefinitionParser.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,193 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; + +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.core.Conventions; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +/** + * Convenient base class for when there exists a one-to-one mapping + * between attribute names on the element that is to be parsed and + * the property names on the {@link Class} being configured. + * + *

    Extend this parser class when you want to create a single + * bean definition from a relatively simple custom XML element. The + * resulting BeanDefinition will be automatically + * registered with the relevant + * {@link org.springframework.beans.factory.support.BeanDefinitionRegistry}. + * + *

    An example will hopefully make the use of this particular parser + * class immediately clear. Consider the following class definition: + * + *

    public class SimpleCache implements Cache {
    + * 
    + *     public void setName(String name) {...}
    + *     public void setTimeout(int timeout) {...}
    + *     public void setEvictionPolicy(EvictionPolicy policy) {...}
    + * 
    + *     // remaining class definition elided for clarity...
    + * }
    + * + *

    Then let us assume the following XML tag has been defined to + * permit the easy configuration of instances of the above class; + * + *

    <caching:cache name="..." timeout="..." eviction-policy="..."/>
    + * + *

    All that is required of the Java developer tasked with writing + * the parser to parse the above XML tag into an actual + * SimpleCache bean definition is the following: + * + *

    public class SimpleCacheBeanDefinitionParser extends AbstractSimpleBeanDefinitionParser {
    + *
    + *     protected Class getBeanClass(Element element) {
    + *         return SimpleCache.class;
    + *     }
    + * }
    + * + *

    Please note that the AbstractSimpleBeanDefinitionParser + * is limited to populating the created bean definition with property values. + * if you want to parse constructor arguments and nested elements from the + * supplied XML element, then you will have to implement the + * {@link #postProcess(org.springframework.beans.factory.support.BeanDefinitionBuilder, org.w3c.dom.Element)} + * method and do such parsing yourself, or (more likely) subclass the + * {@link AbstractSingleBeanDefinitionParser} or {@link AbstractBeanDefinitionParser} + * classes directly. + * + *

    The process of actually registering the + * SimpleCacheBeanDefinitionParser with the Spring XML parsing + * infrastructure is described in the Spring Framework reference documentation + * (in one of the appendices). + * + *

    For an example of this parser in action (so to speak), do look at + * the source code for the + * {@link org.springframework.beans.factory.xml.UtilNamespaceHandler.PropertiesBeanDefinitionParser}; + * the observant (and even not so observant) reader will immediately notice that + * there is next to no code in the implementation. The + * PropertiesBeanDefinitionParser populates a + * {@link org.springframework.beans.factory.config.PropertiesFactoryBean} + * from an XML element that looks like this: + * + *

    <util:properties location="jdbc.properties"/>
    + * + *

    The observant reader will notice that the sole attribute on the + * <util:properties/> element matches the + * {@link org.springframework.beans.factory.config.PropertiesFactoryBean#setLocation(org.springframework.core.io.Resource)} + * method name on the PropertiesFactoryBean (the general + * usage thus illustrated holds true for any number of attributes). + * All that the PropertiesBeanDefinitionParser needs + * actually do is supply an implementation of the + * {@link #getBeanClass(org.w3c.dom.Element)} method to return the + * PropertiesFactoryBean type. + * + * @author Rob Harrop + * @author Rick Evans + * @author Juergen Hoeller + * @since 2.0 + * @see Conventions#attributeNameToPropertyName(String) + */ +public abstract class AbstractSimpleBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { + + /** + * Parse the supplied {@link Element} and populate the supplied + * {@link BeanDefinitionBuilder} as required. + *

    This implementation maps any attributes present on the + * supplied element to {@link org.springframework.beans.PropertyValue} + * instances, and + * {@link BeanDefinitionBuilder#addPropertyValue(String, Object) adds them} + * to the + * {@link org.springframework.beans.factory.config.BeanDefinition builder}. + *

    The {@link #extractPropertyName(String)} method is used to + * reconcile the name of an attribute with the name of a JavaBean + * property. + * @param element the XML element being parsed + * @param builder used to define the BeanDefinition + * @see #extractPropertyName(String) + */ + protected final void doParse(Element element, BeanDefinitionBuilder builder) { + NamedNodeMap attributes = element.getAttributes(); + for (int x = 0; x < attributes.getLength(); x++) { + Attr attribute = (Attr) attributes.item(x); + if (isEligibleAttribute(attribute)) { + String propertyName = extractPropertyName(attribute.getLocalName()); + Assert.state(StringUtils.hasText(propertyName), + "Illegal property name returned from 'extractPropertyName(String)': cannot be null or empty."); + builder.addPropertyValue(propertyName, attribute.getValue()); + } + } + postProcess(builder, element); + } + + /** + * Determine whether the given attribute is eligible for being + * turned into a corresponding bean property value. + *

    The default implementation considers any attribute as eligible, + * except for the "id" attribute and namespace declaration attributes. + * @param attribute the XML attribute to check + * @see #isEligibleAttribute(String) + */ + protected boolean isEligibleAttribute(Attr attribute) { + String fullName = attribute.getName(); + return (!fullName.equals("xmlns") && !fullName.startsWith("xmlns:") && + isEligibleAttribute(attribute.getLocalName())); + } + + /** + * Determine whether the given attribute is eligible for being + * turned into a corresponding bean property value. + *

    The default implementation considers any attribute as eligible, + * except for the "id" attribute. + * @param attributeName the attribute name taken straight from the + * XML element being parsed (never null) + */ + protected boolean isEligibleAttribute(String attributeName) { + return !ID_ATTRIBUTE.equals(attributeName); + } + + /** + * Extract a JavaBean property name from the supplied attribute name. + *

    The default implementation uses the + * {@link Conventions#attributeNameToPropertyName(String)} + * method to perform the extraction. + *

    The name returned must obey the standard JavaBean property name + * conventions. For example for a class with a setter method + * 'setBingoHallFavourite(String)', the name returned had + * better be 'bingoHallFavourite' (with that exact casing). + * @param attributeName the attribute name taken straight from the + * XML element being parsed (never null) + * @return the extracted JavaBean property name (must never be null) + */ + protected String extractPropertyName(String attributeName) { + return Conventions.attributeNameToPropertyName(attributeName); + } + + /** + * Hook method that derived classes can implement to inspect/change a + * bean definition after parsing is complete. + *

    The default implementation does nothing. + * @param beanDefinition the parsed (and probably totally defined) bean definition being built + * @param element the XML element that was the source of the bean definition's metadata + */ + protected void postProcess(BeanDefinitionBuilder beanDefinition, Element element) { + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/AbstractSingleBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/AbstractSingleBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/AbstractSingleBeanDefinitionParser.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,152 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; + +/** + * Base class for those {@link BeanDefinitionParser} implementations that + * need to parse and define just a single BeanDefinition. + * + *

    Extend this parser class when you want to create a single bean definition + * from an arbitrarily complex XML element. You may wish to consider extending + * the {@link AbstractSimpleBeanDefinitionParser} when you want to create a + * single bean definition from a relatively simple custom XML element. + * + *

    The resulting BeanDefinition will be automatically registered + * with the {@link org.springframework.beans.factory.support.BeanDefinitionRegistry}. + * Your job simply is to {@link #doParse parse} the custom XML {@link Element} + * into a single BeanDefinition. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @author Rick Evans + * @since 2.0 + * @see #getBeanClass + * @see #getBeanClassName + * @see #doParse + */ +public abstract class AbstractSingleBeanDefinitionParser extends AbstractBeanDefinitionParser { + + /** + * Creates a {@link BeanDefinitionBuilder} instance for the + * {@link #getBeanClass bean Class} and passes it to the + * {@link #doParse} strategy method. + * @param element the element that is to be parsed into a single BeanDefinition + * @param parserContext the object encapsulating the current state of the parsing process + * @return the BeanDefinition resulting from the parsing of the supplied {@link Element} + * @throws IllegalStateException if the bean {@link Class} returned from + * {@link #getBeanClass(org.w3c.dom.Element)} is null + * @see #doParse + */ + protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(); + String parentName = getParentName(element); + if (parentName != null) { + builder.getRawBeanDefinition().setParentName(parentName); + } + Class beanClass = getBeanClass(element); + if (beanClass != null) { + builder.getRawBeanDefinition().setBeanClass(beanClass); + } + else { + String beanClassName = getBeanClassName(element); + if (beanClassName != null) { + builder.getRawBeanDefinition().setBeanClassName(beanClassName); + } + } + builder.getRawBeanDefinition().setSource(parserContext.extractSource(element)); + if (parserContext.isNested()) { + // Inner bean definition must receive same scope as containing bean. + builder.setScope(parserContext.getContainingBeanDefinition().getScope()); + } + if (parserContext.isDefaultLazyInit()) { + // Default-lazy-init applies to custom bean definitions as well. + builder.setLazyInit(true); + } + doParse(element, parserContext, builder); + return builder.getBeanDefinition(); + } + + /** + * Determine the name for the parent of the currently parsed bean, + * in case of the current bean being defined as a child bean. + *

    The default implementation returns null, + * indicating a root bean definition. + * @param element the Element that is being parsed + * @return the name of the parent bean for the currently parsed bean, + * or null if none + */ + protected String getParentName(Element element) { + return null; + } + + /** + * Determine the bean class corresponding to the supplied {@link Element}. + *

    Note that, for application classes, it is generally preferable to + * override {@link #getBeanClassName} instead, in order to avoid a direct + * dependence on the bean implementation class. The BeanDefinitionParser + * and its NamespaceHandler can be used within an IDE plugin then, even + * if the application classes are not available on the plugin's classpath. + * @param element the Element that is being parsed + * @return the {@link Class} of the bean that is being defined via parsing + * the supplied Element, or null if none + * @see #getBeanClassName + */ + protected Class getBeanClass(Element element) { + return null; + } + + /** + * Determine the bean class name corresponding to the supplied {@link Element}. + * @param element the Element that is being parsed + * @return the class name of the bean that is being defined via parsing + * the supplied Element, or null if none + * @see #getBeanClass + */ + protected String getBeanClassName(Element element) { + return null; + } + + /** + * Parse the supplied {@link Element} and populate the supplied + * {@link BeanDefinitionBuilder} as required. + *

    The default implementation delegates to the doParse + * version without ParserContext argument. + * @param element the XML element being parsed + * @param parserContext the object encapsulating the current state of the parsing process + * @param builder used to define the BeanDefinition + * @see #doParse(Element, BeanDefinitionBuilder) + */ + protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { + doParse(element, builder); + } + + /** + * Parse the supplied {@link Element} and populate the supplied + * {@link BeanDefinitionBuilder} as required. + *

    The default implementation does nothing. + * @param element the XML element being parsed + * @param builder used to define the BeanDefinition + */ + protected void doParse(Element element, BeanDefinitionBuilder builder) { + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/BeanDefinitionDecorator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/BeanDefinitionDecorator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/BeanDefinitionDecorator.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.w3c.dom.Node; + +import org.springframework.beans.factory.config.BeanDefinitionHolder; + +/** + * Interface used by the {@link org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader} + * to handle custom, nested (directly under a <bean>) tags. + * + *

    Decoration may also occur based on custom attributes applied to the + * <bean> tag. Implementations are free to turn the metadata in the + * custom tag into as many + * {@link org.springframework.beans.factory.config.BeanDefinition BeanDefinitions} as + * required and to transform the + * {@link org.springframework.beans.factory.config.BeanDefinition} of the enclosing + * <bean> tag, potentially even returning a completely different + * {@link org.springframework.beans.factory.config.BeanDefinition} to replace the + * original. + * + *

    {@link BeanDefinitionDecorator BeanDefinitionDecorators} should be aware that + * they may be part of a chain. In particular, a {@link BeanDefinitionDecorator} should + * be aware that a previous {@link BeanDefinitionDecorator} may have replaced the + * original {@link org.springframework.beans.factory.config.BeanDefinition} with a + * {@link org.springframework.aop.framework.ProxyFactoryBean} definition allowing for + * custom {@link org.aopalliance.intercept.MethodInterceptor interceptors} to be added. + * + *

    {@link BeanDefinitionDecorator BeanDefinitionDecorators} that wish to add an + * interceptor to the enclosing bean should extend + * {@link org.springframework.aop.config.AbstractInterceptorDrivenBeanDefinitionDecorator} + * which handles the chaining ensuring that only one proxy is created and that it + * contains all interceptors from the chain. + * + *

    The parser locates a {@link BeanDefinitionDecorator} from the + * {@link NamespaceHandler} for the namespace in which the custom tag resides. + * + * @author Rob Harrop + * @since 2.0 + * @see NamespaceHandler + * @see BeanDefinitionParser + */ +public interface BeanDefinitionDecorator { + + /** + * Parse the specified {@link Node} (either an element or an attribute) and decorate + * the supplied {@link org.springframework.beans.factory.config.BeanDefinition}, + * returning the decorated definition. + *

    Implementations may choose to return a completely new definition, which will + * replace the original definition in the resulting + * {@link org.springframework.beans.factory.BeanFactory}. + *

    The supplied {@link ParserContext} can be used to register any additional + * beans needed to support the main definition. + */ + BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/BeanDefinitionDocumentReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/BeanDefinitionDocumentReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/BeanDefinitionDocumentReader.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.w3c.dom.Document; + +import org.springframework.beans.factory.BeanDefinitionStoreException; + +/** + * SPI for parsing an XML document that contains Spring bean definitions. + * Used by XmlBeanDefinitionReader for actually parsing a DOM document. + * + *

    Instantiated per document to parse: Implementations can hold + * state in instance variables during the execution of the + * registerBeanDefinitions method, for example global + * settings that are defined for all bean definitions in the document. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @since 18.12.2003 + * @see XmlBeanDefinitionReader#setDocumentReaderClass + */ +public interface BeanDefinitionDocumentReader { + + /** + * Read bean definitions from the given DOM document, + * and register them with the given bean factory. + * @param doc the DOM document + * @param readerContext the current context of the reader. Includes the resource being parsed + * @throws BeanDefinitionStoreException in case of parsing errors + */ + void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) + throws BeanDefinitionStoreException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/BeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/BeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/BeanDefinitionParser.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.BeanDefinition; + +/** + * Interface used by the + * {@link org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader} to + * handle custom, top-level (directly under <beans>) tags. + * + *

    Implementations are free to turn the metadata in the custom tag into as many + * {@link BeanDefinition BeanDefinitions} as required. + * + *

    The parser locates a {@link BeanDefinitionParser} from the associated + * {@link NamespaceHandler} for the namespace in which the custom tag resides. + * + * @author Rob Harrop + * @since 2.0 + * @see NamespaceHandler + * @see org.springframework.beans.factory.xml.BeanDefinitionDecorator + * @see AbstractBeanDefinitionParser + */ +public interface BeanDefinitionParser { + + /** + * Parse the specified {@link Element} and register the resulting + * {@link BeanDefinition BeanDefinition(s)} with the + * {@link org.springframework.beans.factory.xml.ParserContext#getRegistry()} BeanDefinitionRegistry} + * embedded in the supplied {@link ParserContext}. + *

    Implementations must return the primary {@link BeanDefinition} that results + * from the parse if they will ever be used in a nested fashion (for example as + * an inner tag in a <property/> tag). Implementations may return + * null if they will not be used in a nested fashion. + * @param element the element that is to be parsed into one or more {@link BeanDefinition BeanDefinitions} + * @param parserContext the object encapsulating the current state of the parsing process; + * provides access to a {@link org.springframework.beans.factory.support.BeanDefinitionRegistry} + * @return the primary {@link BeanDefinition} + */ + BeanDefinition parse(Element element, ParserContext parserContext); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,1369 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import org.springframework.beans.BeanMetadataAttribute; +import org.springframework.beans.BeanMetadataAttributeAccessor; +import org.springframework.beans.PropertyValue; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.config.ConstructorArgumentValues; +import org.springframework.beans.factory.config.RuntimeBeanNameReference; +import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.beans.factory.config.TypedStringValue; +import org.springframework.beans.factory.parsing.BeanEntry; +import org.springframework.beans.factory.parsing.ConstructorArgumentEntry; +import org.springframework.beans.factory.parsing.ParseState; +import org.springframework.beans.factory.parsing.PropertyEntry; +import org.springframework.beans.factory.parsing.QualifierEntry; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.AutowireCandidateQualifier; +import org.springframework.beans.factory.support.BeanDefinitionDefaults; +import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; +import org.springframework.beans.factory.support.LookupOverride; +import org.springframework.beans.factory.support.ManagedList; +import org.springframework.beans.factory.support.ManagedMap; +import org.springframework.beans.factory.support.ManagedProperties; +import org.springframework.beans.factory.support.ManagedSet; +import org.springframework.beans.factory.support.MethodOverrides; +import org.springframework.beans.factory.support.ReplaceOverride; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.CollectionUtils; +import org.springframework.util.ObjectUtils; +import org.springframework.util.PatternMatchUtils; +import org.springframework.util.StringUtils; +import org.springframework.util.xml.DomUtils; + +/** + * Stateful delegate class used to parse XML bean definitions. + * Intended for use by both the main parser and any extension + * {@link BeanDefinitionParser BeanDefinitionParsers} or + * {@link BeanDefinitionDecorator BeanDefinitionDecorators}. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @author Rod Johnson + * @author Mark Fisher + * @since 2.0 + * @see ParserContext + * @see DefaultBeanDefinitionDocumentReader + */ +public class BeanDefinitionParserDelegate { + + public static final String BEANS_NAMESPACE_URI = "http://www.springframework.org/schema/beans"; + + public static final String BEAN_NAME_DELIMITERS = ",; "; + + /** + * Value of a T/F attribute that represents true. + * Anything else represents false. Case seNsItive. + */ + public static final String TRUE_VALUE = "true"; + + public static final String DEFAULT_VALUE = "default"; + + public static final String DESCRIPTION_ELEMENT = "description"; + + public static final String AUTOWIRE_BY_NAME_VALUE = "byName"; + + public static final String AUTOWIRE_BY_TYPE_VALUE = "byType"; + + public static final String AUTOWIRE_CONSTRUCTOR_VALUE = "constructor"; + + public static final String AUTOWIRE_AUTODETECT_VALUE = "autodetect"; + + public static final String DEPENDENCY_CHECK_ALL_ATTRIBUTE_VALUE = "all"; + + public static final String DEPENDENCY_CHECK_SIMPLE_ATTRIBUTE_VALUE = "simple"; + + public static final String DEPENDENCY_CHECK_OBJECTS_ATTRIBUTE_VALUE = "objects"; + + public static final String NAME_ATTRIBUTE = "name"; + + public static final String BEAN_ELEMENT = "bean"; + + public static final String META_ELEMENT = "meta"; + + public static final String ID_ATTRIBUTE = "id"; + + public static final String PARENT_ATTRIBUTE = "parent"; + + public static final String CLASS_ATTRIBUTE = "class"; + + public static final String ABSTRACT_ATTRIBUTE = "abstract"; + + public static final String SCOPE_ATTRIBUTE = "scope"; + + public static final String SINGLETON_ATTRIBUTE = "singleton"; + + public static final String LAZY_INIT_ATTRIBUTE = "lazy-init"; + + public static final String AUTOWIRE_ATTRIBUTE = "autowire"; + + public static final String AUTOWIRE_CANDIDATE_ATTRIBUTE = "autowire-candidate"; + + public static final String PRIMARY_ATTRIBUTE = "primary"; + + public static final String DEPENDENCY_CHECK_ATTRIBUTE = "dependency-check"; + + public static final String DEPENDS_ON_ATTRIBUTE = "depends-on"; + + public static final String INIT_METHOD_ATTRIBUTE = "init-method"; + + public static final String DESTROY_METHOD_ATTRIBUTE = "destroy-method"; + + public static final String FACTORY_METHOD_ATTRIBUTE = "factory-method"; + + public static final String FACTORY_BEAN_ATTRIBUTE = "factory-bean"; + + public static final String CONSTRUCTOR_ARG_ELEMENT = "constructor-arg"; + + public static final String INDEX_ATTRIBUTE = "index"; + + public static final String TYPE_ATTRIBUTE = "type"; + + public static final String VALUE_TYPE_ATTRIBUTE = "value-type"; + + public static final String KEY_TYPE_ATTRIBUTE = "key-type"; + + public static final String PROPERTY_ELEMENT = "property"; + + public static final String REF_ATTRIBUTE = "ref"; + + public static final String VALUE_ATTRIBUTE = "value"; + + public static final String LOOKUP_METHOD_ELEMENT = "lookup-method"; + + public static final String REPLACED_METHOD_ELEMENT = "replaced-method"; + + public static final String REPLACER_ATTRIBUTE = "replacer"; + + public static final String ARG_TYPE_ELEMENT = "arg-type"; + + public static final String ARG_TYPE_MATCH_ATTRIBUTE = "match"; + + public static final String REF_ELEMENT = "ref"; + + public static final String IDREF_ELEMENT = "idref"; + + public static final String BEAN_REF_ATTRIBUTE = "bean"; + + public static final String LOCAL_REF_ATTRIBUTE = "local"; + + public static final String PARENT_REF_ATTRIBUTE = "parent"; + + public static final String VALUE_ELEMENT = "value"; + + public static final String NULL_ELEMENT = "null"; + + public static final String LIST_ELEMENT = "list"; + + public static final String SET_ELEMENT = "set"; + + public static final String MAP_ELEMENT = "map"; + + public static final String ENTRY_ELEMENT = "entry"; + + public static final String KEY_ELEMENT = "key"; + + public static final String KEY_ATTRIBUTE = "key"; + + public static final String KEY_REF_ATTRIBUTE = "key-ref"; + + public static final String VALUE_REF_ATTRIBUTE = "value-ref"; + + public static final String PROPS_ELEMENT = "props"; + + public static final String PROP_ELEMENT = "prop"; + + public static final String MERGE_ATTRIBUTE = "merge"; + + public static final String QUALIFIER_ELEMENT = "qualifier"; + + public static final String QUALIFIER_ATTRIBUTE_ELEMENT = "attribute"; + + public static final String DEFAULT_LAZY_INIT_ATTRIBUTE = "default-lazy-init"; + + public static final String DEFAULT_MERGE_ATTRIBUTE = "default-merge"; + + public static final String DEFAULT_AUTOWIRE_ATTRIBUTE = "default-autowire"; + + public static final String DEFAULT_DEPENDENCY_CHECK_ATTRIBUTE = "default-dependency-check"; + + public static final String DEFAULT_AUTOWIRE_CANDIDATES_ATTRIBUTE = "default-autowire-candidates"; + + public static final String DEFAULT_INIT_METHOD_ATTRIBUTE = "default-init-method"; + + public static final String DEFAULT_DESTROY_METHOD_ATTRIBUTE = "default-destroy-method"; + + + protected final Log logger = LogFactory.getLog(getClass()); + + private final XmlReaderContext readerContext; + + private DocumentDefaultsDefinition defaults; + + private ParseState parseState = new ParseState(); + + /** + * Stores all used bean names so we can enforce uniqueness on a per file basis. + */ + private final Set usedNames = new HashSet(); + + + /** + * Create a new BeanDefinitionParserDelegate associated with the + * supplied {@link XmlReaderContext}. + */ + public BeanDefinitionParserDelegate(XmlReaderContext readerContext) { + Assert.notNull(readerContext, "XmlReaderContext must not be null"); + this.readerContext = readerContext; + } + + /** + * Get the {@link XmlReaderContext} associated with this helper instance. + */ + public final XmlReaderContext getReaderContext() { + return this.readerContext; + } + + + /** + * Invoke the {@link org.springframework.beans.factory.parsing.SourceExtractor} to pull the + * source metadata from the supplied {@link Element}. + */ + protected Object extractSource(Element ele) { + return this.readerContext.extractSource(ele); + } + + /** + * Report an error with the given message for the given source element. + */ + protected void error(String message, Node source) { + this.readerContext.error(message, source, this.parseState.snapshot()); + } + + /** + * Report an error with the given message for the given source element. + */ + protected void error(String message, Element source) { + this.readerContext.error(message, source, this.parseState.snapshot()); + } + + /** + * Report an error with the given message for the given source element. + */ + protected void error(String message, Element source, Throwable cause) { + this.readerContext.error(message, source, this.parseState.snapshot(), cause); + } + + + /** + * Initialize the default lazy-init, autowire, dependency check settings, + * init-method, destroy-method and merge settings. + * @see #getDefaults() + */ + public void initDefaults(Element root) { + DocumentDefaultsDefinition defaults = new DocumentDefaultsDefinition(); + defaults.setLazyInit(root.getAttribute(DEFAULT_LAZY_INIT_ATTRIBUTE)); + defaults.setMerge(root.getAttribute(DEFAULT_MERGE_ATTRIBUTE)); + defaults.setAutowire(root.getAttribute(DEFAULT_AUTOWIRE_ATTRIBUTE)); + defaults.setDependencyCheck(root.getAttribute(DEFAULT_DEPENDENCY_CHECK_ATTRIBUTE)); + if (root.hasAttribute(DEFAULT_AUTOWIRE_CANDIDATES_ATTRIBUTE)) { + defaults.setAutowireCandidates(root.getAttribute(DEFAULT_AUTOWIRE_CANDIDATES_ATTRIBUTE)); + } + if (root.hasAttribute(DEFAULT_INIT_METHOD_ATTRIBUTE)) { + defaults.setInitMethod(root.getAttribute(DEFAULT_INIT_METHOD_ATTRIBUTE)); + } + if (root.hasAttribute(DEFAULT_DESTROY_METHOD_ATTRIBUTE)) { + defaults.setDestroyMethod(root.getAttribute(DEFAULT_DESTROY_METHOD_ATTRIBUTE)); + } + defaults.setSource(this.readerContext.extractSource(root)); + + this.defaults = defaults; + this.readerContext.fireDefaultsRegistered(defaults); + } + + /** + * Return the defaults definition object, or null if the + * defaults have been initialized yet. + */ + public DocumentDefaultsDefinition getDefaults() { + return this.defaults; + } + + /** + * Return the default settings for bean definitions as indicated within + * the attributes of the top-level <beans/> element. + */ + public BeanDefinitionDefaults getBeanDefinitionDefaults() { + BeanDefinitionDefaults bdd = new BeanDefinitionDefaults(); + if (this.defaults != null) { + bdd.setLazyInit("TRUE".equalsIgnoreCase(this.defaults.getLazyInit())); + bdd.setDependencyCheck(this.getDependencyCheck(DEFAULT_VALUE)); + bdd.setAutowireMode(this.getAutowireMode(DEFAULT_VALUE)); + bdd.setInitMethodName(this.defaults.getInitMethod()); + bdd.setDestroyMethodName(this.defaults.getDestroyMethod()); + } + return bdd; + } + + /** + * Return any patterns provided in the 'default-autowire-candidates' + * attribute of the top-level <beans/> element. + */ + public String[] getAutowireCandidatePatterns() { + String candidatePattern = this.defaults.getAutowireCandidates(); + return candidatePattern == null ? null : StringUtils.commaDelimitedListToStringArray(candidatePattern); + } + + + /** + * Parses the supplied <bean> element. May return null + * if there were errors during parse. Errors are reported to the + * {@link org.springframework.beans.factory.parsing.ProblemReporter}. + */ + public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) { + return parseBeanDefinitionElement(ele, null); + } + + /** + * Parses the supplied <bean> element. May return null + * if there were errors during parse. Errors are reported to the + * {@link org.springframework.beans.factory.parsing.ProblemReporter}. + */ + public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) { + String id = ele.getAttribute(ID_ATTRIBUTE); + String nameAttr = ele.getAttribute(NAME_ATTRIBUTE); + + List aliases = new ArrayList(); + if (StringUtils.hasLength(nameAttr)) { + String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, BEAN_NAME_DELIMITERS); + aliases.addAll(Arrays.asList(nameArr)); + } + + String beanName = id; + if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) { + beanName = (String) aliases.remove(0); + if (logger.isDebugEnabled()) { + logger.debug("No XML 'id' specified - using '" + beanName + + "' as bean name and " + aliases + " as aliases"); + } + } + + if (containingBean == null) { + checkNameUniqueness(beanName, aliases, ele); + } + + AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean); + if (beanDefinition != null) { + if (!StringUtils.hasText(beanName)) { + try { + if (containingBean != null) { + beanName = BeanDefinitionReaderUtils.generateBeanName( + beanDefinition, this.readerContext.getRegistry(), true); + } + else { + beanName = this.readerContext.generateBeanName(beanDefinition); + // Register an alias for the plain bean class name, if still possible, + // if the generator returned the class name plus a suffix. + // This is expected for Spring 1.2/2.0 backwards compatibility. + String beanClassName = beanDefinition.getBeanClassName(); + if (beanClassName != null && + beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && + !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) { + aliases.add(beanClassName); + } + } + if (logger.isDebugEnabled()) { + logger.debug("Neither XML 'id' nor 'name' specified - " + + "using generated bean name [" + beanName + "]"); + } + } + catch (Exception ex) { + error(ex.getMessage(), ele); + return null; + } + } + String[] aliasesArray = StringUtils.toStringArray(aliases); + return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray); + } + + return null; + } + + /** + * Validate that the specified bean name and aliases have not been used already. + */ + protected void checkNameUniqueness(String beanName, List aliases, Element beanElement) { + String foundName = null; + + if (StringUtils.hasText(beanName) && this.usedNames.contains(beanName)) { + foundName = beanName; + } + if (foundName == null) { + foundName = (String) CollectionUtils.findFirstMatch(this.usedNames, aliases); + } + if (foundName != null) { + error("Bean name '" + foundName + "' is already used in this file", beanElement); + } + + this.usedNames.add(beanName); + this.usedNames.addAll(aliases); + } + + /** + * Parse the bean definition itself, without regard to name or aliases. May return + * null if problems occured during the parse of the bean definition. + */ + public AbstractBeanDefinition parseBeanDefinitionElement( + Element ele, String beanName, BeanDefinition containingBean) { + + this.parseState.push(new BeanEntry(beanName)); + + String className = null; + if (ele.hasAttribute(CLASS_ATTRIBUTE)) { + className = ele.getAttribute(CLASS_ATTRIBUTE).trim(); + } + + try { + String parent = null; + if (ele.hasAttribute(PARENT_ATTRIBUTE)) { + parent = ele.getAttribute(PARENT_ATTRIBUTE); + } + AbstractBeanDefinition bd = createBeanDefinition(className, parent); + + parseBeanDefinitionAttributes(ele, beanName, containingBean, bd); + bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT)); + + parseMetaElements(ele, bd); + parseLookupOverrideSubElements(ele, bd.getMethodOverrides()); + parseReplacedMethodSubElements(ele, bd.getMethodOverrides()); + + parseConstructorArgElements(ele, bd); + parsePropertyElements(ele, bd); + parseQualifierElements(ele, bd); + + bd.setResource(this.readerContext.getResource()); + bd.setSource(extractSource(ele)); + + return bd; + } + catch (ClassNotFoundException ex) { + error("Bean class [" + className + "] not found", ele, ex); + } + catch (NoClassDefFoundError err) { + error("Class that bean class [" + className + "] depends on not found", ele, err); + } + catch (Throwable ex) { + error("Unexpected failure during bean definition parsing", ele, ex); + } + finally { + this.parseState.pop(); + } + + return null; + } + + /** + * Apply the attributes of the given bean element to the given bean * definition. + * @param ele bean declaration element + * @param beanName bean name + * @param containingBean containing bean definition + * @return a bean definition initialized according to the bean element attributes + */ + public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName, + BeanDefinition containingBean, AbstractBeanDefinition bd) { + + if (ele.hasAttribute(SCOPE_ATTRIBUTE)) { + // Spring 2.x "scope" attribute + bd.setScope(ele.getAttribute(SCOPE_ATTRIBUTE)); + if (ele.hasAttribute(SINGLETON_ATTRIBUTE)) { + error("Specify either 'scope' or 'singleton', not both", ele); + } + } + else if (ele.hasAttribute(SINGLETON_ATTRIBUTE)) { + // Spring 1.x "singleton" attribute + bd.setScope(TRUE_VALUE.equals(ele.getAttribute(SINGLETON_ATTRIBUTE)) ? BeanDefinition.SCOPE_SINGLETON + : BeanDefinition.SCOPE_PROTOTYPE); + } + else if (containingBean != null) { + // Take default from containing bean in case of an inner bean definition. + bd.setScope(containingBean.getScope()); + } + + if (ele.hasAttribute(ABSTRACT_ATTRIBUTE)) { + bd.setAbstract(TRUE_VALUE.equals(ele.getAttribute(ABSTRACT_ATTRIBUTE))); + } + + String lazyInit = ele.getAttribute(LAZY_INIT_ATTRIBUTE); + if (DEFAULT_VALUE.equals(lazyInit) && bd.isSingleton()) { + // Just apply default to singletons, as lazy-init has no meaning for prototypes. + lazyInit = this.defaults.getLazyInit(); + } + bd.setLazyInit(TRUE_VALUE.equals(lazyInit)); + + String autowire = ele.getAttribute(AUTOWIRE_ATTRIBUTE); + bd.setAutowireMode(getAutowireMode(autowire)); + + String dependencyCheck = ele.getAttribute(DEPENDENCY_CHECK_ATTRIBUTE); + bd.setDependencyCheck(getDependencyCheck(dependencyCheck)); + + if (ele.hasAttribute(DEPENDS_ON_ATTRIBUTE)) { + String dependsOn = ele.getAttribute(DEPENDS_ON_ATTRIBUTE); + bd.setDependsOn(StringUtils.tokenizeToStringArray(dependsOn, BEAN_NAME_DELIMITERS)); + } + + String autowireCandidate = ele.getAttribute(AUTOWIRE_CANDIDATE_ATTRIBUTE); + if ("".equals(autowireCandidate) || DEFAULT_VALUE.equals(autowireCandidate)) { + String candidatePattern = this.defaults.getAutowireCandidates(); + if (candidatePattern != null) { + String[] patterns = StringUtils.commaDelimitedListToStringArray(candidatePattern); + bd.setAutowireCandidate(PatternMatchUtils.simpleMatch(patterns, beanName)); + } + } + else { + bd.setAutowireCandidate(TRUE_VALUE.equals(autowireCandidate)); + } + + if (ele.hasAttribute(PRIMARY_ATTRIBUTE)) { + bd.setPrimary(TRUE_VALUE.equals(ele.getAttribute(PRIMARY_ATTRIBUTE))); + } + + if (ele.hasAttribute(INIT_METHOD_ATTRIBUTE)) { + String initMethodName = ele.getAttribute(INIT_METHOD_ATTRIBUTE); + if (!"".equals(initMethodName)) { + bd.setInitMethodName(initMethodName); + } + } + else { + if (this.defaults.getInitMethod() != null) { + bd.setInitMethodName(this.defaults.getInitMethod()); + bd.setEnforceInitMethod(false); + } + } + + if (ele.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) { + String destroyMethodName = ele.getAttribute(DESTROY_METHOD_ATTRIBUTE); + if (!"".equals(destroyMethodName)) { + bd.setDestroyMethodName(destroyMethodName); + } + } + else { + if (this.defaults.getDestroyMethod() != null) { + bd.setDestroyMethodName(this.defaults.getDestroyMethod()); + bd.setEnforceDestroyMethod(false); + } + } + + if (ele.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) { + bd.setFactoryMethodName(ele.getAttribute(FACTORY_METHOD_ATTRIBUTE)); + } + if (ele.hasAttribute(FACTORY_BEAN_ATTRIBUTE)) { + bd.setFactoryBeanName(ele.getAttribute(FACTORY_BEAN_ATTRIBUTE)); + } + + return bd; + } + + /** + * Create a bean definition for the given class name and parent name. + * @param className the name of the bean class + * @param parentName the name of the bean's parent bean + * @return the newly created bean definition + * @throws ClassNotFoundException if bean class resolution was attempted but failed + */ + protected AbstractBeanDefinition createBeanDefinition(String className, String parentName) + throws ClassNotFoundException { + + return BeanDefinitionReaderUtils.createBeanDefinition( + parentName, className, this.readerContext.getBeanClassLoader()); + } + + public void parseMetaElements(Element ele, BeanMetadataAttributeAccessor attributeAccessor) { + NodeList nl = ele.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node instanceof Element && DomUtils.nodeNameEquals(node, META_ELEMENT)) { + Element metaElement = (Element) node; + String key = metaElement.getAttribute(KEY_ATTRIBUTE); + String value = metaElement.getAttribute(VALUE_ATTRIBUTE); + BeanMetadataAttribute attribute = new BeanMetadataAttribute(key, value); + attribute.setSource(extractSource(metaElement)); + attributeAccessor.addMetadataAttribute(attribute); + } + } + } + + public int getAutowireMode(String attValue) { + String att = attValue; + if (DEFAULT_VALUE.equals(att)) { + att = this.defaults.getAutowire(); + } + int autowire = AbstractBeanDefinition.AUTOWIRE_NO; + if (AUTOWIRE_BY_NAME_VALUE.equals(att)) { + autowire = AbstractBeanDefinition.AUTOWIRE_BY_NAME; + } + else if (AUTOWIRE_BY_TYPE_VALUE.equals(att)) { + autowire = AbstractBeanDefinition.AUTOWIRE_BY_TYPE; + } + else if (AUTOWIRE_CONSTRUCTOR_VALUE.equals(att)) { + autowire = AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR; + } + else if (AUTOWIRE_AUTODETECT_VALUE.equals(att)) { + autowire = AbstractBeanDefinition.AUTOWIRE_AUTODETECT; + } + // Else leave default value. + return autowire; + } + + public int getDependencyCheck(String attValue) { + String att = attValue; + if (DEFAULT_VALUE.equals(att)) { + att = this.defaults.getDependencyCheck(); + } + int dependencyCheckCode = AbstractBeanDefinition.DEPENDENCY_CHECK_NONE; + if (DEPENDENCY_CHECK_ALL_ATTRIBUTE_VALUE.equals(att)) { + dependencyCheckCode = AbstractBeanDefinition.DEPENDENCY_CHECK_ALL; + } + else if (DEPENDENCY_CHECK_SIMPLE_ATTRIBUTE_VALUE.equals(att)) { + dependencyCheckCode = AbstractBeanDefinition.DEPENDENCY_CHECK_SIMPLE; + } + else if (DEPENDENCY_CHECK_OBJECTS_ATTRIBUTE_VALUE.equals(att)) { + dependencyCheckCode = AbstractBeanDefinition.DEPENDENCY_CHECK_OBJECTS; + } + // Else leave default value. + return dependencyCheckCode; + } + + /** + * Parse constructor-arg sub-elements of the given bean element. + */ + public void parseConstructorArgElements(Element beanEle, BeanDefinition bd) { + NodeList nl = beanEle.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node instanceof Element && DomUtils.nodeNameEquals(node, CONSTRUCTOR_ARG_ELEMENT)) { + parseConstructorArgElement((Element) node, bd); + } + } + } + + /** + * Parse property sub-elements of the given bean element. + */ + public void parsePropertyElements(Element beanEle, BeanDefinition bd) { + NodeList nl = beanEle.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node instanceof Element && DomUtils.nodeNameEquals(node, PROPERTY_ELEMENT)) { + parsePropertyElement((Element) node, bd); + } + } + } + + /** + * Parse qualifier sub-elements of the given bean element. + */ + public void parseQualifierElements(Element beanEle, AbstractBeanDefinition bd) { + NodeList nl = beanEle.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node instanceof Element && DomUtils.nodeNameEquals(node, QUALIFIER_ELEMENT)) { + parseQualifierElement((Element) node, bd); + } + } + } + + /** + * Parse lookup-override sub-elements of the given bean element. + */ + public void parseLookupOverrideSubElements(Element beanEle, MethodOverrides overrides) { + NodeList nl = beanEle.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node instanceof Element && DomUtils.nodeNameEquals(node, LOOKUP_METHOD_ELEMENT)) { + Element ele = (Element) node; + String methodName = ele.getAttribute(NAME_ATTRIBUTE); + String beanRef = ele.getAttribute(BEAN_ELEMENT); + LookupOverride override = new LookupOverride(methodName, beanRef); + override.setSource(extractSource(ele)); + overrides.addOverride(override); + } + } + } + + /** + * Parse replaced-method sub-elements of the given bean element. + */ + public void parseReplacedMethodSubElements(Element beanEle, MethodOverrides overrides) { + NodeList nl = beanEle.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node instanceof Element && DomUtils.nodeNameEquals(node, REPLACED_METHOD_ELEMENT)) { + Element replacedMethodEle = (Element) node; + String name = replacedMethodEle.getAttribute(NAME_ATTRIBUTE); + String callback = replacedMethodEle.getAttribute(REPLACER_ATTRIBUTE); + ReplaceOverride replaceOverride = new ReplaceOverride(name, callback); + // Look for arg-type match elements. + List argTypeEles = DomUtils.getChildElementsByTagName(replacedMethodEle, ARG_TYPE_ELEMENT); + for (Iterator it = argTypeEles.iterator(); it.hasNext();) { + Element argTypeEle = (Element) it.next(); + replaceOverride.addTypeIdentifier(argTypeEle.getAttribute(ARG_TYPE_MATCH_ATTRIBUTE)); + } + replaceOverride.setSource(extractSource(replacedMethodEle)); + overrides.addOverride(replaceOverride); + } + } + } + + /** + * Parse a constructor-arg element. + */ + public void parseConstructorArgElement(Element ele, BeanDefinition bd) { + String indexAttr = ele.getAttribute(INDEX_ATTRIBUTE); + String typeAttr = ele.getAttribute(TYPE_ATTRIBUTE); + if (StringUtils.hasLength(indexAttr)) { + try { + int index = Integer.parseInt(indexAttr); + if (index < 0) { + error("'index' cannot be lower than 0", ele); + } + else { + try { + this.parseState.push(new ConstructorArgumentEntry(index)); + Object value = parsePropertyValue(ele, bd, null); + ConstructorArgumentValues.ValueHolder valueHolder = new ConstructorArgumentValues.ValueHolder(value); + if (StringUtils.hasLength(typeAttr)) { + valueHolder.setType(typeAttr); + } + valueHolder.setSource(extractSource(ele)); + bd.getConstructorArgumentValues().addIndexedArgumentValue(index, valueHolder); + } + finally { + this.parseState.pop(); + } + } + } + catch (NumberFormatException ex) { + error("Attribute 'index' of tag 'constructor-arg' must be an integer", ele); + } + } + else { + try { + this.parseState.push(new ConstructorArgumentEntry()); + Object value = parsePropertyValue(ele, bd, null); + ConstructorArgumentValues.ValueHolder valueHolder = new ConstructorArgumentValues.ValueHolder(value); + if (StringUtils.hasLength(typeAttr)) { + valueHolder.setType(typeAttr); + } + valueHolder.setSource(extractSource(ele)); + bd.getConstructorArgumentValues().addGenericArgumentValue(valueHolder); + } + finally { + this.parseState.pop(); + } + } + } + + /** + * Parse a property element. + */ + public void parsePropertyElement(Element ele, BeanDefinition bd) { + String propertyName = ele.getAttribute(NAME_ATTRIBUTE); + if (!StringUtils.hasLength(propertyName)) { + error("Tag 'property' must have a 'name' attribute", ele); + return; + } + this.parseState.push(new PropertyEntry(propertyName)); + try { + if (bd.getPropertyValues().contains(propertyName)) { + error("Multiple 'property' definitions for property '" + propertyName + "'", ele); + return; + } + Object val = parsePropertyValue(ele, bd, propertyName); + PropertyValue pv = new PropertyValue(propertyName, val); + parseMetaElements(ele, pv); + pv.setSource(extractSource(ele)); + bd.getPropertyValues().addPropertyValue(pv); + } + finally { + this.parseState.pop(); + } + } + + /** + * Parse a qualifier element. + */ + public void parseQualifierElement(Element ele, AbstractBeanDefinition bd) { + String typeName = ele.getAttribute(TYPE_ATTRIBUTE); + if (!StringUtils.hasLength(typeName)) { + error("Tag 'qualifier' must have a 'type' attribute", ele); + return; + } + this.parseState.push(new QualifierEntry(typeName)); + try { + AutowireCandidateQualifier qualifier = new AutowireCandidateQualifier(typeName); + qualifier.setSource(extractSource(ele)); + String value = ele.getAttribute(VALUE_ATTRIBUTE); + if (StringUtils.hasLength(value)) { + qualifier.setAttribute(AutowireCandidateQualifier.VALUE_KEY, value); + } + NodeList nl = ele.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node instanceof Element && DomUtils.nodeNameEquals(node, QUALIFIER_ATTRIBUTE_ELEMENT)) { + Element attributeEle = (Element) node; + String attributeName = attributeEle.getAttribute(KEY_ATTRIBUTE); + String attributeValue = attributeEle.getAttribute(VALUE_ATTRIBUTE); + if (StringUtils.hasLength(attributeName) && StringUtils.hasLength(attributeValue)) { + BeanMetadataAttribute attribute = new BeanMetadataAttribute(attributeName, attributeValue); + attribute.setSource(extractSource(attributeEle)); + qualifier.addMetadataAttribute(attribute); + } + else { + error("Qualifier 'attribute' tag must have a 'name' and 'value'", attributeEle); + return; + } + } + } + bd.addQualifier(qualifier); + } + finally { + this.parseState.pop(); + } + } + + /** + * Get the value of a property element. May be a list etc. + * Also used for constructor arguments, "propertyName" being null in this case. + */ + public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName) { + String elementName = (propertyName != null) ? + " element for property '" + propertyName + "'" : + " element"; + + // Should only have one child element: ref, value, list, etc. + NodeList nl = ele.getChildNodes(); + Element subElement = null; + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node instanceof Element && !DomUtils.nodeNameEquals(node, DESCRIPTION_ELEMENT) && + !DomUtils.nodeNameEquals(node, META_ELEMENT)) { + // Child element is what we're looking for. + if (subElement != null) { + error(elementName + " must not contain more than one sub-element", ele); + } + else { + subElement = (Element) node; + } + } + } + + boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE); + boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE); + if ((hasRefAttribute && hasValueAttribute) || + ((hasRefAttribute || hasValueAttribute) && subElement != null)) { + error(elementName + + " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele); + } + + if (hasRefAttribute) { + String refName = ele.getAttribute(REF_ATTRIBUTE); + if (!StringUtils.hasText(refName)) { + error(elementName + " contains empty 'ref' attribute", ele); + } + RuntimeBeanReference ref = new RuntimeBeanReference(refName); + ref.setSource(extractSource(ele)); + return ref; + } + else if (hasValueAttribute) { + TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE)); + valueHolder.setSource(extractSource(ele)); + return valueHolder; + } + else if (subElement != null) { + return parsePropertySubElement(subElement, bd); + } + else { + // Neither child element nor "ref" or "value" attribute found. + error(elementName + " must specify a ref or value", ele); + return null; + } + } + + public Object parsePropertySubElement(Element ele, BeanDefinition bd) { + return parsePropertySubElement(ele, bd, null); + } + + /** + * Parse a value, ref or collection sub-element of a property or + * constructor-arg element. + * @param ele subelement of property element; we don't know which yet + * @param defaultTypeClassName the default type (class name) for any + * <value> tag that might be created + */ + public Object parsePropertySubElement(Element ele, BeanDefinition bd, String defaultTypeClassName) { + if (!isDefaultNamespace(ele.getNamespaceURI())) { + return parseNestedCustomElement(ele, bd); + } + else if (DomUtils.nodeNameEquals(ele, BEAN_ELEMENT)) { + BeanDefinitionHolder nestedBd = parseBeanDefinitionElement(ele, bd); + if (nestedBd != null) { + nestedBd = decorateBeanDefinitionIfRequired(ele, nestedBd, bd); + } + return nestedBd; + } + else if (DomUtils.nodeNameEquals(ele, REF_ELEMENT)) { + // A generic reference to any name of any bean. + String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE); + boolean toParent = false; + if (!StringUtils.hasLength(refName)) { + // A reference to the id of another bean in the same XML file. + refName = ele.getAttribute(LOCAL_REF_ATTRIBUTE); + if (!StringUtils.hasLength(refName)) { + // A reference to the id of another bean in a parent context. + refName = ele.getAttribute(PARENT_REF_ATTRIBUTE); + toParent = true; + if (!StringUtils.hasLength(refName)) { + error("'bean', 'local' or 'parent' is required for element", ele); + return null; + } + } + } + if (!StringUtils.hasText(refName)) { + error(" element contains empty target attribute", ele); + return null; + } + RuntimeBeanReference ref = new RuntimeBeanReference(refName, toParent); + ref.setSource(extractSource(ele)); + return ref; + } + else if (DomUtils.nodeNameEquals(ele, IDREF_ELEMENT)) { + return parseIdRefElement(ele); + } + else if (DomUtils.nodeNameEquals(ele, VALUE_ELEMENT)) { + return parseValueElement(ele, defaultTypeClassName); + } + else if (DomUtils.nodeNameEquals(ele, NULL_ELEMENT)) { + // It's a distinguished null value. Let's wrap it in a TypedStringValue + // object in order to preserve the source location. + TypedStringValue nullHolder = new TypedStringValue(null); + nullHolder.setSource(extractSource(ele)); + return nullHolder; + } + else if (DomUtils.nodeNameEquals(ele, LIST_ELEMENT)) { + return parseListElement(ele, bd); + } + else if (DomUtils.nodeNameEquals(ele, SET_ELEMENT)) { + return parseSetElement(ele, bd); + } + else if (DomUtils.nodeNameEquals(ele, MAP_ELEMENT)) { + return parseMapElement(ele, bd); + } + else if (DomUtils.nodeNameEquals(ele, PROPS_ELEMENT)) { + return parsePropsElement(ele); + } + else { + error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele); + return null; + } + } + + /** + * Return a typed String value Object for the given 'idref' element. + */ + public Object parseIdRefElement(Element ele) { + // A generic reference to any name of any bean. + String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE); + if (!StringUtils.hasLength(refName)) { + // A reference to the id of another bean in the same XML file. + refName = ele.getAttribute(LOCAL_REF_ATTRIBUTE); + if (!StringUtils.hasLength(refName)) { + error("Either 'bean' or 'local' is required for element", ele); + return null; + } + } + if (!StringUtils.hasText(refName)) { + error(" element contains empty target attribute", ele); + return null; + } + RuntimeBeanNameReference ref = new RuntimeBeanNameReference(refName); + ref.setSource(extractSource(ele)); + return ref; + } + + /** + * Return a typed String value Object for the given value element. + */ + public Object parseValueElement(Element ele, String defaultTypeClassName) { + // It's a literal value. + String value = DomUtils.getTextValue(ele); + String typeClassName = ele.getAttribute(TYPE_ATTRIBUTE); + if (!StringUtils.hasText(typeClassName)) { + typeClassName = defaultTypeClassName; + } + try { + return buildTypedStringValue(value, typeClassName, ele); + } + catch (ClassNotFoundException ex) { + error("Type class [" + typeClassName + "] not found for element", ele, ex); + return value; + } + } + + /** + * Build a typed String value Object for the given raw value. + * @see org.springframework.beans.factory.config.TypedStringValue + */ + protected Object buildTypedStringValue(String value, String targetTypeName, Element ele) + throws ClassNotFoundException { + + ClassLoader classLoader = this.readerContext.getBeanClassLoader(); + TypedStringValue typedValue = null; + if (!StringUtils.hasText(targetTypeName)) { + typedValue = new TypedStringValue(value); + } + else if (classLoader != null) { + Class targetType = ClassUtils.forName(targetTypeName, classLoader); + typedValue = new TypedStringValue(value, targetType); + } + else { + typedValue = new TypedStringValue(value, targetTypeName); + } + typedValue.setSource(extractSource(ele)); + return typedValue; + } + + /** + * Parse a list element. + */ + public List parseListElement(Element collectionEle, BeanDefinition bd) { + String defaultTypeClassName = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE); + NodeList nl = collectionEle.getChildNodes(); + ManagedList list = new ManagedList(nl.getLength()); + list.setSource(extractSource(collectionEle)); + list.setMergeEnabled(parseMergeAttribute(collectionEle)); + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node instanceof Element && !DomUtils.nodeNameEquals(node, DESCRIPTION_ELEMENT)) { + list.add(parsePropertySubElement((Element) node, bd, defaultTypeClassName)); + } + } + return list; + } + + /** + * Parse a set element. + */ + public Set parseSetElement(Element collectionEle, BeanDefinition bd) { + String defaultTypeClassName = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE); + NodeList nl = collectionEle.getChildNodes(); + ManagedSet set = new ManagedSet(nl.getLength()); + set.setSource(extractSource(collectionEle)); + set.setMergeEnabled(parseMergeAttribute(collectionEle)); + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node instanceof Element && !DomUtils.nodeNameEquals(node, DESCRIPTION_ELEMENT)) { + set.add(parsePropertySubElement((Element) node, bd, defaultTypeClassName)); + } + } + return set; + } + + /** + * Parse a map element. + */ + public Map parseMapElement(Element mapEle, BeanDefinition bd) { + String defaultKeyTypeClassName = mapEle.getAttribute(KEY_TYPE_ATTRIBUTE); + String defaultValueTypeClassName = mapEle.getAttribute(VALUE_TYPE_ATTRIBUTE); + + List entryEles = DomUtils.getChildElementsByTagName(mapEle, ENTRY_ELEMENT); + ManagedMap map = new ManagedMap(entryEles.size()); + map.setMergeEnabled(parseMergeAttribute(mapEle)); + map.setSource(extractSource(mapEle)); + + for (Iterator it = entryEles.iterator(); it.hasNext();) { + Element entryEle = (Element) it.next(); + // Should only have one value child element: ref, value, list, etc. + // Optionally, there might be a key child element. + NodeList entrySubNodes = entryEle.getChildNodes(); + + Element keyEle = null; + Element valueEle = null; + for (int j = 0; j < entrySubNodes.getLength(); j++) { + Node node = entrySubNodes.item(j); + if (node instanceof Element) { + Element candidateEle = (Element) node; + if (DomUtils.nodeNameEquals(candidateEle, KEY_ELEMENT)) { + if (keyEle != null) { + error(" element is only allowed to contain one sub-element", entryEle); + } + else { + keyEle = candidateEle; + } + } + else { + // Child element is what we're looking for. + if (valueEle != null) { + error(" element must not contain more than one value sub-element", entryEle); + } + else { + valueEle = candidateEle; + } + } + } + } + + // Extract key from attribute or sub-element. + Object key = null; + boolean hasKeyAttribute = entryEle.hasAttribute(KEY_ATTRIBUTE); + boolean hasKeyRefAttribute = entryEle.hasAttribute(KEY_REF_ATTRIBUTE); + if ((hasKeyAttribute && hasKeyRefAttribute) || + ((hasKeyAttribute || hasKeyRefAttribute)) && keyEle != null) { + error(" element is only allowed to contain either " + + "a 'key' attribute OR a 'key-ref' attribute OR a sub-element", entryEle); + } + if (hasKeyAttribute) { + key = buildTypedStringValueForMap( + entryEle.getAttribute(KEY_ATTRIBUTE), defaultKeyTypeClassName, entryEle); + } + else if (hasKeyRefAttribute) { + String refName = entryEle.getAttribute(KEY_REF_ATTRIBUTE); + if (!StringUtils.hasText(refName)) { + error(" element contains empty 'key-ref' attribute", entryEle); + } + RuntimeBeanReference ref = new RuntimeBeanReference(refName); + ref.setSource(extractSource(entryEle)); + key = ref; + } + else if (keyEle != null) { + key = parseKeyElement(keyEle, bd, defaultKeyTypeClassName); + } + else { + error(" element must specify a key", entryEle); + } + + // Extract value from attribute or sub-element. + Object value = null; + boolean hasValueAttribute = entryEle.hasAttribute(VALUE_ATTRIBUTE); + boolean hasValueRefAttribute = entryEle.hasAttribute(VALUE_REF_ATTRIBUTE); + if ((hasValueAttribute && hasValueRefAttribute) || + ((hasValueAttribute || hasValueRefAttribute)) && valueEle != null) { + error(" element is only allowed to contain either " + + "'value' attribute OR 'value-ref' attribute OR sub-element", entryEle); + } + if (hasValueAttribute) { + value = buildTypedStringValueForMap( + entryEle.getAttribute(VALUE_ATTRIBUTE), defaultValueTypeClassName, entryEle); + } + else if (hasValueRefAttribute) { + String refName = entryEle.getAttribute(VALUE_REF_ATTRIBUTE); + if (!StringUtils.hasText(refName)) { + error(" element contains empty 'value-ref' attribute", entryEle); + } + RuntimeBeanReference ref = new RuntimeBeanReference(refName); + ref.setSource(extractSource(entryEle)); + value = ref; + } + else if (valueEle != null) { + value = parsePropertySubElement(valueEle, bd, defaultValueTypeClassName); + } + else { + error(" element must specify a value", entryEle); + } + + // Add final key and value to the Map. + map.put(key, value); + } + + return map; + } + + /** + * Build a typed String value Object for the given raw value. + * @see org.springframework.beans.factory.config.TypedStringValue + */ + protected final Object buildTypedStringValueForMap(String value, String defaultTypeClassName, Element entryEle) { + try { + return buildTypedStringValue(value, defaultTypeClassName, entryEle); + } + catch (ClassNotFoundException ex) { + error("Type class [" + defaultTypeClassName + "] not found for Map key/value type", entryEle, ex); + return value; + } + } + + /** + * Parse a key sub-element of a map element. + */ + public Object parseKeyElement(Element keyEle, BeanDefinition bd, String defaultKeyTypeClassName) { + NodeList nl = keyEle.getChildNodes(); + Element subElement = null; + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node instanceof Element) { + // Child element is what we're looking for. + if (subElement != null) { + error(" element must not contain more than one value sub-element", keyEle); + } + else { + subElement = (Element) node; + } + } + } + return parsePropertySubElement(subElement, bd, defaultKeyTypeClassName); + } + + /** + * Parse a props element. + */ + public Properties parsePropsElement(Element propsEle) { + ManagedProperties props = new ManagedProperties(); + props.setSource(extractSource(propsEle)); + props.setMergeEnabled(parseMergeAttribute(propsEle)); + + List propEles = DomUtils.getChildElementsByTagName(propsEle, PROP_ELEMENT); + for (Iterator it = propEles.iterator(); it.hasNext();) { + Element propEle = (Element) it.next(); + String key = propEle.getAttribute(KEY_ATTRIBUTE); + // Trim the text value to avoid unwanted whitespace + // caused by typical XML formatting. + String value = DomUtils.getTextValue(propEle).trim(); + + TypedStringValue keyHolder = new TypedStringValue(key); + keyHolder.setSource(extractSource(propEle)); + TypedStringValue valueHolder = new TypedStringValue(value); + valueHolder.setSource(extractSource(propEle)); + props.put(keyHolder, valueHolder); + } + + return props; + } + + /** + * Parse the merge attribute of a collection element, if any. + */ + public boolean parseMergeAttribute(Element collectionElement) { + String value = collectionElement.getAttribute(MERGE_ATTRIBUTE); + if (DEFAULT_VALUE.equals(value)) { + value = this.defaults.getMerge(); + } + return TRUE_VALUE.equals(value); + } + + public BeanDefinition parseCustomElement(Element ele) { + return parseCustomElement(ele, null); + } + + public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) { + String namespaceUri = ele.getNamespaceURI(); + NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri); + if (handler == null) { + error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele); + return null; + } + return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd)); + } + + public BeanDefinitionHolder decorateBeanDefinitionIfRequired(Element ele, BeanDefinitionHolder definitionHolder) { + return decorateBeanDefinitionIfRequired(ele, definitionHolder, null); + } + + public BeanDefinitionHolder decorateBeanDefinitionIfRequired( + Element ele, BeanDefinitionHolder definitionHolder, BeanDefinition containingBd) { + + BeanDefinitionHolder finalDefinition = definitionHolder; + + // Decorate based on custom attributes first. + NamedNodeMap attributes = ele.getAttributes(); + for (int i = 0; i < attributes.getLength(); i++) { + Node node = attributes.item(i); + finalDefinition = decorateIfRequired(node, finalDefinition, containingBd); + } + + // Decorate based on custom nested elements. + NodeList children = ele.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + Node node = children.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + finalDefinition = decorateIfRequired(node, finalDefinition, containingBd); + } + } + return finalDefinition; + } + + private BeanDefinitionHolder decorateIfRequired( + Node node, BeanDefinitionHolder originalDef, BeanDefinition containingBd) { + + String namespaceUri = node.getNamespaceURI(); + if (!isDefaultNamespace(namespaceUri)) { + NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri); + if (handler != null) { + return handler.decorate(node, originalDef, new ParserContext(this.readerContext, this, containingBd)); + } + else if (namespaceUri.startsWith("http://www.springframework.org/")) { + error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", node); + } + else { + // A custom namespace, not to be handled by Spring - maybe "xml:...". + if (logger.isDebugEnabled()) { + logger.debug("No Spring NamespaceHandler found for XML schema namespace [" + namespaceUri + "]"); + } + } + } + return originalDef; + } + + public boolean isDefaultNamespace(String namespaceUri) { + return (!StringUtils.hasLength(namespaceUri) || BEANS_NAMESPACE_URI.equals(namespaceUri)); + } + + private BeanDefinitionHolder parseNestedCustomElement(Element ele, BeanDefinition containingBd) { + BeanDefinition innerDefinition = parseCustomElement(ele, containingBd); + if (innerDefinition == null) { + error("Incorrect usage of element '" + ele.getNodeName() + "' in a nested manner. " + + "This tag cannot be used nested inside .", ele); + return null; + } + String id = ele.getNodeName() + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + + ObjectUtils.getIdentityHexString(innerDefinition); + if (logger.isDebugEnabled()) { + logger.debug("Using generated bean name [" + id + + "] for nested custom element '" + ele.getNodeName() + "'"); + } + return new BeanDefinitionHolder(innerDefinition, id); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/BeansDtdResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/BeansDtdResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/BeansDtdResolver.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,90 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import java.io.IOException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +/** + * EntityResolver implementation for the Spring beans DTD, + * to load the DTD from the Spring class path (or JAR file). + * + *

    Fetches "spring-beans-2.0.dtd" from the class path resource + * "/org/springframework/beans/factory/xml/spring-beans-2.0.dtd", + * no matter whether specified as some local URL that includes "spring-beans" + * in the DTD name or as "http://www.springframework.org/dtd/spring-beans-2.0.dtd". + * + * @author Juergen Hoeller + * @author Colin Sampaleanu + * @since 04.06.2003 + * @see ResourceEntityResolver + */ +public class BeansDtdResolver implements EntityResolver { + + private static final String DTD_EXTENSION = ".dtd"; + + private static final String[] DTD_NAMES = {"spring-beans-2.0", "spring-beans"}; + + private static final Log logger = LogFactory.getLog(BeansDtdResolver.class); + + + public InputSource resolveEntity(String publicId, String systemId) throws IOException { + if (logger.isTraceEnabled()) { + logger.trace("Trying to resolve XML entity with public ID [" + publicId + + "] and system ID [" + systemId + "]"); + } + if (systemId != null && systemId.endsWith(DTD_EXTENSION)) { + int lastPathSeparator = systemId.lastIndexOf("/"); + for (int i = 0; i < DTD_NAMES.length; ++i) { + int dtdNameStart = systemId.indexOf(DTD_NAMES[i]); + if (dtdNameStart > lastPathSeparator) { + String dtdFile = systemId.substring(dtdNameStart); + if (logger.isTraceEnabled()) { + logger.trace("Trying to locate [" + dtdFile + "] in Spring jar"); + } + try { + Resource resource = new ClassPathResource(dtdFile, getClass()); + InputSource source = new InputSource(resource.getInputStream()); + source.setPublicId(publicId); + source.setSystemId(systemId); + if (logger.isDebugEnabled()) { + logger.debug("Found beans DTD [" + systemId + "] in classpath: " + dtdFile); + } + return source; + } + catch (IOException ex) { + if (logger.isDebugEnabled()) { + logger.debug("Could not resolve beans DTD [" + systemId + "]: not found in class path", ex); + } + } + + } + } + } + + // Use the default behavior -> download from website or wherever. + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/DefaultBeanDefinitionDocumentReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/DefaultBeanDefinitionDocumentReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/DefaultBeanDefinitionDocumentReader.java 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,282 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import java.io.IOException; +import java.util.LinkedHashSet; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.ResourcePatternUtils; +import org.springframework.util.StringUtils; +import org.springframework.util.SystemPropertyUtils; +import org.springframework.util.xml.DomUtils; + +/** + * Default implementation of the {@link BeanDefinitionDocumentReader} interface. + * Reads bean definitions according to the "spring-beans" DTD and XSD format + * (Spring's default XML bean definition format). + * + *

    The structure, elements and attribute names of the required XML document + * are hard-coded in this class. (Of course a transform could be run if necessary + * to produce this format). <beans> doesn't need to be the root + * element of the XML document: This class will parse all bean definition elements + * in the XML file, not regarding the actual root element. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Rob Harrop + * @author Erik Wiersma + * @since 18.12.2003 + */ +public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader { + + public static final String BEAN_ELEMENT = BeanDefinitionParserDelegate.BEAN_ELEMENT; + + public static final String ALIAS_ELEMENT = "alias"; + + public static final String NAME_ATTRIBUTE = "name"; + + public static final String ALIAS_ATTRIBUTE = "alias"; + + public static final String IMPORT_ELEMENT = "import"; + + public static final String RESOURCE_ATTRIBUTE = "resource"; + + + protected final Log logger = LogFactory.getLog(getClass()); + + private XmlReaderContext readerContext; + + + /** + * Parses bean definitions according to the "spring-beans" DTD. + *

    Opens a DOM Document; then initializes the default settings + * specified at <beans> level; then parses + * the contained bean definitions. + */ + public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) { + this.readerContext = readerContext; + + logger.debug("Loading bean definitions"); + Element root = doc.getDocumentElement(); + + BeanDefinitionParserDelegate delegate = createHelper(readerContext, root); + + preProcessXml(root); + parseBeanDefinitions(root, delegate); + postProcessXml(root); + } + + protected BeanDefinitionParserDelegate createHelper(XmlReaderContext readerContext, Element root) { + BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext); + delegate.initDefaults(root); + return delegate; + } + + /** + * Return the descriptor for the XML resource that this parser works on. + */ + protected final XmlReaderContext getReaderContext() { + return this.readerContext; + } + + /** + * Invoke the {@link org.springframework.beans.factory.parsing.SourceExtractor} to pull the + * source metadata from the supplied {@link Element}. + */ + protected Object extractSource(Element ele) { + return this.readerContext.extractSource(ele); + } + + + /** + * Parse the elements at the root level in the document: + * "import", "alias", "bean". + * @param root the DOM root element of the document + */ + protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) { + if (delegate.isDefaultNamespace(root.getNamespaceURI())) { + NodeList nl = root.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node node = nl.item(i); + if (node instanceof Element) { + Element ele = (Element) node; + String namespaceUri = ele.getNamespaceURI(); + if (delegate.isDefaultNamespace(namespaceUri)) { + parseDefaultElement(ele, delegate); + } + else { + delegate.parseCustomElement(ele); + } + } + } + } + else { + delegate.parseCustomElement(root); + } + } + + private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) { + if (DomUtils.nodeNameEquals(ele, IMPORT_ELEMENT)) { + importBeanDefinitionResource(ele); + } + else if (DomUtils.nodeNameEquals(ele, ALIAS_ELEMENT)) { + processAliasRegistration(ele); + } + else if (DomUtils.nodeNameEquals(ele, BEAN_ELEMENT)) { + processBeanDefinition(ele, delegate); + } + } + + /** + * Parse an "import" element and load the bean definitions + * from the given resource into the bean factory. + */ + protected void importBeanDefinitionResource(Element ele) { + String location = ele.getAttribute(RESOURCE_ATTRIBUTE); + if (!StringUtils.hasText(location)) { + getReaderContext().error("Resource location must not be empty", ele); + return; + } + + // Resolve system properties: e.g. "${user.dir}" + location = SystemPropertyUtils.resolvePlaceholders(location); + + if (ResourcePatternUtils.isUrl(location)) { + try { + Set actualResources = new LinkedHashSet(4); + int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources); + if (logger.isDebugEnabled()) { + logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]"); + } + Resource[] actResArray = (Resource[]) actualResources.toArray(new Resource[actualResources.size()]); + getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele)); + } + catch (BeanDefinitionStoreException ex) { + getReaderContext().error( + "Failed to import bean definitions from URL location [" + location + "]", ele, ex); + } + } + else { + // No URL -> considering resource location as relative to the current file. + try { + Resource relativeResource = getReaderContext().getResource().createRelative(location); + int importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource); + if (logger.isDebugEnabled()) { + logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]"); + } + getReaderContext().fireImportProcessed(location, new Resource[] {relativeResource}, extractSource(ele)); + } + catch (IOException ex) { + getReaderContext().error( + "Invalid relative resource location [" + location + "] to import bean definitions from", ele, ex); + } + catch (BeanDefinitionStoreException ex) { + getReaderContext().error( + "Failed to import bean definitions from relative location [" + location + "]", ele, ex); + } + } + } + + /** + * Process the given alias element, registering the alias with the registry. + */ + protected void processAliasRegistration(Element ele) { + String name = ele.getAttribute(NAME_ATTRIBUTE); + String alias = ele.getAttribute(ALIAS_ATTRIBUTE); + boolean valid = true; + if (!StringUtils.hasText(name)) { + getReaderContext().error("Name must not be empty", ele); + valid = false; + } + if (!StringUtils.hasText(alias)) { + getReaderContext().error("Alias must not be empty", ele); + valid = false; + } + if (valid) { + try { + getReaderContext().getRegistry().registerAlias(name, alias); + } + catch (Exception ex) { + getReaderContext().error("Failed to register alias '" + alias + + "' for bean with name '" + name + "'", ele, ex); + } + getReaderContext().fireAliasRegistered(name, alias, extractSource(ele)); + } + } + + /** + * Process the given bean element, parsing the bean definition + * and registering it with the registry. + */ + protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) { + BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); + if (bdHolder != null) { + bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder); + try { + // Register the final decorated instance. + BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); + } + catch (BeanDefinitionStoreException ex) { + getReaderContext().error("Failed to register bean definition with name '" + + bdHolder.getBeanName() + "'", ele, ex); + } + // Send registration event. + getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder)); + } + } + + + /** + * Allow the XML to be extensible by processing any custom element types first, + * before we start to process the bean definitions. This method is a natural + * extension point for any other custom pre-processing of the XML. + *

    The default implementation is empty. Subclasses can override this method to + * convert custom elements into standard Spring bean definitions, for example. + * Implementors have access to the parser's bean definition reader and the + * underlying XML resource, through the corresponding accessors. + * @see #getReaderContext() + */ + protected void preProcessXml(Element root) { + } + + /** + * Allow the XML to be extensible by processing any custom element types last, + * after we finished processing the bean definitions. This method is a natural + * extension point for any other custom post-processing of the XML. + *

    The default implementation is empty. Subclasses can override this method to + * convert custom elements into standard Spring bean definitions, for example. + * Implementors have access to the parser's bean definition reader and the + * underlying XML resource, through the corresponding accessors. + * @see #getReaderContext() + */ + protected void postProcessXml(Element root) { + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/DefaultDocumentLoader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/DefaultDocumentLoader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/DefaultDocumentLoader.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,140 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.xml.sax.EntityResolver; +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; + +import org.springframework.util.xml.XmlValidationModeDetector; + +/** + * Spring's default {@link DocumentLoader} implementation. + * + *

    Simply loads {@link Document documents} using the standard JAXP-configured + * XML parser. If you want to change the {@link DocumentBuilder} that is used to + * load documents, then one strategy is to define a corresponding Java system property + * when starting your JVM. For example, to use the Oracle {@link DocumentBuilder}, + * you might start your application like as follows: + * + *

    java -Djavax.xml.parsers.DocumentBuilderFactory=oracle.xml.jaxp.JXDocumentBuilderFactory MyMainClass
    + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public class DefaultDocumentLoader implements DocumentLoader { + + /** + * JAXP attribute used to configure the schema language for validation. + */ + private static final String SCHEMA_LANGUAGE_ATTRIBUTE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; + + /** + * JAXP attribute value indicating the XSD schema language. + */ + private static final String XSD_SCHEMA_LANGUAGE = "http://www.w3.org/2001/XMLSchema"; + + + private static final Log logger = LogFactory.getLog(DefaultDocumentLoader.class); + + + /** + * Load the {@link Document} at the supplied {@link InputSource} using the standard JAXP-configured + * XML parser. + */ + public Document loadDocument(InputSource inputSource, EntityResolver entityResolver, + ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception { + + DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware); + if (logger.isDebugEnabled()) { + logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]"); + } + DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler); + return builder.parse(inputSource); + } + + /** + * Create the {@link DocumentBuilderFactory} instance. + * @param validationMode the type of validation: {@link XmlValidationModeDetector#VALIDATION_DTD DTD} + * or {@link XmlValidationModeDetector#VALIDATION_XSD XSD}) + * @param namespaceAware whether the returned factory is to provide support for XML namespaces + * @return the JAXP DocumentBuilderFactory + * @throws ParserConfigurationException if we failed to build a proper DocumentBuilderFactory + */ + protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware) + throws ParserConfigurationException { + + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(namespaceAware); + + if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) { + factory.setValidating(true); + + if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) { + // Enforce namespace aware for XSD... + factory.setNamespaceAware(true); + try { + factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE); + } + catch (IllegalArgumentException ex) { + ParserConfigurationException pcex = new ParserConfigurationException( + "Unable to validate using XSD: Your JAXP provider [" + factory + + "] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " + + "Upgrade to Apache Xerces (or Java 1.5) for full XSD support."); + pcex.initCause(ex); + throw pcex; + } + } + } + + return factory; + } + + /** + * Create a JAXP DocumentBuilder that this bean definition reader + * will use for parsing XML documents. Can be overridden in subclasses, + * adding further initialization of the builder. + * @param factory the JAXP DocumentBuilderFactory that the DocumentBuilder + * should be created with + * @param entityResolver the SAX EntityResolver to use + * @param errorHandler the SAX ErrorHandler to use + * @return the JAXP DocumentBuilder + * @throws ParserConfigurationException if thrown by JAXP methods + */ + protected DocumentBuilder createDocumentBuilder( + DocumentBuilderFactory factory, EntityResolver entityResolver, ErrorHandler errorHandler) + throws ParserConfigurationException { + + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + if (entityResolver != null) { + docBuilder.setEntityResolver(entityResolver); + } + if (errorHandler != null) { + docBuilder.setErrorHandler(errorHandler); + } + return docBuilder; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/DefaultNamespaceHandlerResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/DefaultNamespaceHandlerResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/DefaultNamespaceHandlerResolver.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,167 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.FatalBeanException; +import org.springframework.core.io.support.PropertiesLoaderUtils; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; + +/** + * Default implementation of the {@link NamespaceHandlerResolver} interface. + * Resolves namespace URIs to implementation classes based on the mappings + * contained in mapping file. + * + *

    By default, this implementation looks for the mapping file at + * META-INF/spring.handlers, but this can be changed using the + * {@link #DefaultNamespaceHandlerResolver(ClassLoader, String)} constructor. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + * @see NamespaceHandler + * @see DefaultBeanDefinitionDocumentReader + */ +public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver { + + /** + * The location to look for the mapping files. Can be present in multiple JAR files. + */ + public static final String DEFAULT_HANDLER_MAPPINGS_LOCATION = "META-INF/spring.handlers"; + + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + /** ClassLoader to use for NamespaceHandler classes */ + private final ClassLoader classLoader; + + /** Resource location to search for */ + private final String handlerMappingsLocation; + + /** Stores the mappings from namespace URI to NamespaceHandler class name / instance */ + private Map handlerMappings; + + + /** + * Create a new DefaultNamespaceHandlerResolver using the + * default mapping file location. + *

    This constructor will result in the thread context ClassLoader being used + * to load resources. + * @see #DEFAULT_HANDLER_MAPPINGS_LOCATION + */ + public DefaultNamespaceHandlerResolver() { + this(null, DEFAULT_HANDLER_MAPPINGS_LOCATION); + } + + /** + * Create a new DefaultNamespaceHandlerResolver using the + * default mapping file location. + * @param classLoader the {@link ClassLoader} instance used to load mapping resources + * (may be null, in which case the thread context ClassLoader will be used) + * @see #DEFAULT_HANDLER_MAPPINGS_LOCATION + */ + public DefaultNamespaceHandlerResolver(ClassLoader classLoader) { + this(classLoader, DEFAULT_HANDLER_MAPPINGS_LOCATION); + } + + /** + * Create a new DefaultNamespaceHandlerResolver using the + * supplied mapping file location. + * @param classLoader the {@link ClassLoader} instance used to load mapping resources + * may be null, in which case the thread context ClassLoader will be used) + * @param handlerMappingsLocation the mapping file location + */ + public DefaultNamespaceHandlerResolver(ClassLoader classLoader, String handlerMappingsLocation) { + Assert.notNull(handlerMappingsLocation, "Handler mappings location must not be null"); + this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); + this.handlerMappingsLocation = handlerMappingsLocation; + } + + + /** + * Locate the {@link NamespaceHandler} for the supplied namespace URI + * from the configured mappings. + * @param namespaceUri the relevant namespace URI + * @return the located {@link NamespaceHandler}, or null if none found + */ + public NamespaceHandler resolve(String namespaceUri) { + Map handlerMappings = getHandlerMappings(); + Object handlerOrClassName = handlerMappings.get(namespaceUri); + if (handlerOrClassName == null) { + return null; + } + else if (handlerOrClassName instanceof NamespaceHandler) { + return (NamespaceHandler) handlerOrClassName; + } + else { + String className = (String) handlerOrClassName; + try { + Class handlerClass = ClassUtils.forName(className, this.classLoader); + if (!NamespaceHandler.class.isAssignableFrom(handlerClass)) { + throw new FatalBeanException("Class [" + className + "] for namespace [" + namespaceUri + + "] does not implement the [" + NamespaceHandler.class.getName() + "] interface"); + } + NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass); + namespaceHandler.init(); + handlerMappings.put(namespaceUri, namespaceHandler); + return namespaceHandler; + } + catch (ClassNotFoundException ex) { + throw new FatalBeanException("NamespaceHandler class [" + className + "] for namespace [" + + namespaceUri + "] not found", ex); + } + catch (LinkageError err) { + throw new FatalBeanException("Invalid NamespaceHandler class [" + className + "] for namespace [" + + namespaceUri + "]: problem with handler class file or dependent class", err); + } + } + } + + /** + * Load the specified NamespaceHandler mappings lazily. + */ + private Map getHandlerMappings() { + if (this.handlerMappings == null) { + try { + Properties mappings = + PropertiesLoaderUtils.loadAllProperties(this.handlerMappingsLocation, this.classLoader); + if (logger.isDebugEnabled()) { + logger.debug("Loaded mappings [" + mappings + "]"); + } + this.handlerMappings = new HashMap(mappings); + } + catch (IOException ex) { + IllegalStateException ise = new IllegalStateException( + "Unable to load NamespaceHandler mappings from location [" + this.handlerMappingsLocation + "]"); + ise.initCause(ex); + throw ise; + } + } + return this.handlerMappings; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/DelegatingEntityResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/DelegatingEntityResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/DelegatingEntityResolver.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,91 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import java.io.IOException; + +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import org.springframework.util.Assert; + +/** + * {@link EntityResolver} implementation that delegates to a {@link BeansDtdResolver} + * and a {@link PluggableSchemaResolver} for DTDs and XML schemas, respectively. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @author Rick Evans + * @since 2.0 + * @see BeansDtdResolver + * @see PluggableSchemaResolver + */ +public class DelegatingEntityResolver implements EntityResolver { + + /** Suffix for DTD files */ + public static final String DTD_SUFFIX = ".dtd"; + + /** Suffix for schema definition files */ + public static final String XSD_SUFFIX = ".xsd"; + + + private final EntityResolver dtdResolver; + + private final EntityResolver schemaResolver; + + + /** + * Create a new DelegatingEntityResolver that delegates to + * a default {@link BeansDtdResolver} and a default {@link PluggableSchemaResolver}. + *

    Configures the {@link PluggableSchemaResolver} with the supplied + * {@link ClassLoader}. + * @param classLoader the ClassLoader to use for loading + * (can be null) to use the default ClassLoader) + */ + public DelegatingEntityResolver(ClassLoader classLoader) { + this.dtdResolver = new BeansDtdResolver(); + this.schemaResolver = new PluggableSchemaResolver(classLoader); + } + + /** + * Create a new DelegatingEntityResolver that delegates to + * the given {@link EntityResolver EntityResolvers}. + * @param dtdResolver the EntityResolver to resolve DTDs with + * @param schemaResolver the EntityResolver to resolve XML schemas with + */ + public DelegatingEntityResolver(EntityResolver dtdResolver, EntityResolver schemaResolver) { + Assert.notNull(dtdResolver, "'dtdResolver' is required"); + Assert.notNull(schemaResolver, "'schemaResolver' is required"); + this.dtdResolver = dtdResolver; + this.schemaResolver = schemaResolver; + } + + + public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { + if (systemId != null) { + if (systemId.endsWith(DTD_SUFFIX)) { + return this.dtdResolver.resolveEntity(publicId, systemId); + } + else if (systemId.endsWith(XSD_SUFFIX)) { + return this.schemaResolver.resolveEntity(publicId, systemId); + } + } + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/DocumentDefaultsDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/DocumentDefaultsDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/DocumentDefaultsDefinition.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,160 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.springframework.beans.factory.parsing.DefaultsDefinition; + +/** + * Simple JavaBean that holds the defaults specified at the %lt;beans> + * level in a standard Spring XML bean definition document: + * default-lazy-init, default-autowire, etc + * + * @author Juergen Hoeller + * @since 2.0.2 + */ +public class DocumentDefaultsDefinition implements DefaultsDefinition { + + private String lazyInit; + + private String merge; + + private String autowire; + + private String dependencyCheck; + + private String autowireCandidates; + + private String initMethod; + + private String destroyMethod; + + private Object source; + + + /** + * Set the default lazy-init flag for the document that's currently parsed. + */ + public void setLazyInit(String lazyInit) { + this.lazyInit = lazyInit; + } + + /** + * Return the default lazy-init flag for the document that's currently parsed. + */ + public String getLazyInit() { + return this.lazyInit; + } + + /** + * Set the default merge setting for the document that's currently parsed. + */ + public void setMerge(String merge) { + this.merge = merge; + } + + /** + * Return the default merge setting for the document that's currently parsed. + */ + public String getMerge() { + return this.merge; + } + + /** + * Set the default autowire setting for the document that's currently parsed. + */ + public void setAutowire(String autowire) { + this.autowire = autowire; + } + + /** + * Return the default autowire setting for the document that's currently parsed. + */ + public String getAutowire() { + return this.autowire; + } + + /** + * Set the default dependency-check setting for the document that's currently parsed. + */ + public void setDependencyCheck(String dependencyCheck) { + this.dependencyCheck = dependencyCheck; + } + + /** + * Return the default dependency-check setting for the document that's currently parsed. + */ + public String getDependencyCheck() { + return this.dependencyCheck; + } + + /** + * Set the default autowire-candidate pattern for the document that's currently parsed. + * Also accepts a comma-separated list of patterns. + */ + public void setAutowireCandidates(String autowireCandidates) { + this.autowireCandidates = autowireCandidates; + } + + /** + * Return the default autowire-candidate pattern for the document that's currently parsed. + * May also return a comma-separated list of patterns. + */ + public String getAutowireCandidates() { + return this.autowireCandidates; + } + + /** + * Set the default init-method setting for the document that's currently parsed. + */ + public void setInitMethod(String initMethod) { + this.initMethod = initMethod; + } + + /** + * Return the default init-method setting for the document that's currently parsed. + */ + public String getInitMethod() { + return this.initMethod; + } + + /** + * Set the default destroy-method setting for the document that's currently parsed. + */ + public void setDestroyMethod(String destroyMethod) { + this.destroyMethod = destroyMethod; + } + + /** + * Return the default destroy-method setting for the document that's currently parsed. + */ + public String getDestroyMethod() { + return this.destroyMethod; + } + + /** + * Set the configuration source Object for this metadata element. + *

    The exact type of the object will depend on the configuration mechanism used. + */ + public void setSource(Object source) { + this.source = source; + } + + public Object getSource() { + return this.source; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/DocumentLoader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/DocumentLoader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/DocumentLoader.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.w3c.dom.Document; +import org.xml.sax.EntityResolver; +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; + +/** + * Strategy interface for loading an XML {@link Document}. + * + * @author Rob Harrop + * @since 2.0 + * @see DefaultDocumentLoader + */ +public interface DocumentLoader { + + /** + * Load a {@link Document document} from the supplied {@link InputSource source}. + * @param inputSource the source of the document that is to be loaded + * @param entityResolver the resolver that is to be used to resolve any entities + * @param errorHandler used to report any errors during document loading + * @param validationMode the type of validation + * {@link org.springframework.util.xml.XmlValidationModeDetector#VALIDATION_DTD DTD} + * or {@link org.springframework.util.xml.XmlValidationModeDetector#VALIDATION_XSD XSD}) + * @param namespaceAware true if the loading is provide support for XML namespaces + * @return the loaded {@link Document document} + * @throws Exception if an error occurs + */ + Document loadDocument( + InputSource inputSource, EntityResolver entityResolver, + ErrorHandler errorHandler, int validationMode, boolean namespaceAware) + throws Exception; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/NamespaceHandler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/NamespaceHandler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/NamespaceHandler.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,94 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; + +/** + * Base interface used by the {@link DefaultBeanDefinitionDocumentReader} + * for handling custom namespaces in a Spring XML configuration file. + * + *

    Implementations are expected to return implementations of the + * {@link BeanDefinitionParser} interface for custom top-level tags and + * implementations of the {@link BeanDefinitionDecorator} interface for + * custom nested tags. + * + *

    The parser will call {@link #parse} when it encounters a custom tag + * directly under the <beans> tags and {@link #decorate} when + * it encounters a custom tag directly under a <bean> tag. + * + *

    Developers writing their own custom element extensions typically will + * not implement this interface drectly, but rather make use of the provided + * {@link NamespaceHandlerSupport} class. + * + * @author Rob Harrop + * @author Erik Wiersma + * @since 2.0 + * @see DefaultBeanDefinitionDocumentReader + * @see NamespaceHandlerResolver + */ +public interface NamespaceHandler { + + /** + * Invoked by the {@link DefaultBeanDefinitionDocumentReader} after + * construction but before any custom elements are parsed. + * @see NamespaceHandlerSupport#registerBeanDefinitionParser(String, BeanDefinitionParser) + */ + void init(); + + /** + * Parse the specified {@link Element} and register any resulting + * {@link BeanDefinition BeanDefinitions} with the + * {@link org.springframework.beans.factory.support.BeanDefinitionRegistry} + * that is embedded in the supplied {@link ParserContext}. + *

    Implementations should return the primary BeanDefinition + * that results from the parse phase if they wish to be used nested + * inside (for example) a <property> tag. + *

    Implementations may return null if they will + * not be used in a nested scenario. + * @param element the element that is to be parsed into one or more BeanDefinitions + * @param parserContext the object encapsulating the current state of the parsing process + * @return the primary BeanDefinition (can be null as explained above) + */ + BeanDefinition parse(Element element, ParserContext parserContext); + + /** + * Parse the specified {@link Node} and decorate the supplied + * {@link BeanDefinitionHolder}, returning the decorated definition. + *

    The {@link Node} may be either an {@link org.w3c.dom.Attr} or an + * {@link Element}, depending on whether a custom attribute or element + * is being parsed. + *

    Implementations may choose to return a completely new definition, + * which will replace the original definition in the resulting + * {@link org.springframework.beans.factory.BeanFactory}. + *

    The supplied {@link ParserContext} can be used to register any + * additional beans needed to support the main definition. + * @param source the source element or attribute that is to be parsed + * @param definition the current bean definition + * @param parserContext the object encapsulating the current state of the parsing process + * @return the decorated definition (to be registered in the BeanFactory), + * or simply the original bean definition if no decoration is required. + * A null value is strictly speaking invalid, but will be leniently + * treated like the case where the original bean definition gets returned. + */ + BeanDefinitionHolder decorate(Node source, BeanDefinitionHolder definition, ParserContext parserContext); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/NamespaceHandlerResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/NamespaceHandlerResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/NamespaceHandlerResolver.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +/** + * Used by the {@link org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader} to + * locate a {@link NamespaceHandler} implementation for a particular namespace URI. + * + * @author Rob Harrop + * @since 2.0 + * @see NamespaceHandler + * @see org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader + */ +public interface NamespaceHandlerResolver { + + /** + * Resolve the namespace URI and return the located {@link NamespaceHandler} + * implementation. + * @param namespaceUri the relevant namespace URI + * @return the located {@link NamespaceHandler} (may be null) + */ + NamespaceHandler resolve(String namespaceUri); + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,188 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import java.util.HashMap; +import java.util.Map; + +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; + +/** + * Support class for implementing custom {@link NamespaceHandler NamespaceHandlers}. Parsing and + * decorating of individual {@link Node Nodes} is done via {@link BeanDefinitionParser} and + * {@link BeanDefinitionDecorator} strategy interfaces respectively. Provides the + * {@link #registerBeanDefinitionParser}, {@link #registerBeanDefinitionDecorator} methods + * for registering a {@link BeanDefinitionParser} or {@link BeanDefinitionDecorator} to handle + * a specific element. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + * @see #registerBeanDefinitionParser(String, BeanDefinitionParser) + * @see #registerBeanDefinitionDecorator(String, BeanDefinitionDecorator) + */ +public abstract class NamespaceHandlerSupport implements NamespaceHandler { + + /** + * Stores the {@link BeanDefinitionParser} implementations keyed by the + * local name of the {@link Element Elements} they handle. + */ + private final Map parsers = new HashMap(); + + /** + * Stores the {@link BeanDefinitionDecorator} implementations keyed by the + * local name of the {@link Element Elements} they handle. + */ + private final Map decorators = new HashMap(); + + /** + * Stores the {@link BeanDefinitionParser} implementations keyed by the local + * name of the {@link Attr Attrs} they handle. + */ + private final Map attributeDecorators = new HashMap(); + + + /** + * Parses the supplied {@link Element} by delegating to the {@link BeanDefinitionParser} that is + * registered for that {@link Element}. + */ + public final BeanDefinition parse(Element element, ParserContext parserContext) { + return findParserForElement(element, parserContext).parse(element, parserContext); + } + + /** + * Locates the {@link BeanDefinitionParser} from the register implementations using + * the local name of the supplied {@link Element}. + */ + private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) { + BeanDefinitionParser parser = (BeanDefinitionParser) this.parsers.get(element.getLocalName()); + if (parser == null) { + parserContext.getReaderContext().fatal( + "Cannot locate BeanDefinitionParser for element [" + element.getLocalName() + "]", element); + } + return parser; + } + + /** + * Locate the {@link BeanDefinitionParser} from the register implementations using + * the local name of the supplied {@link Element}. + * @deprecated as of Spring 2.0.2; there should be no need to call this directly. + */ + protected final BeanDefinitionParser findParserForElement(Element element) { + BeanDefinitionParser parser = (BeanDefinitionParser) this.parsers.get(element.getLocalName()); + if (parser == null) { + throw new IllegalStateException( + "Cannot locate BeanDefinitionParser for element [" + element.getLocalName() + "]"); + } + return parser; + } + + /** + * Decorates the supplied {@link Node} by delegating to the {@link BeanDefinitionDecorator} that + * is registered to handle that {@link Node}. + */ + public final BeanDefinitionHolder decorate( + Node node, BeanDefinitionHolder definition, ParserContext parserContext) { + + return findDecoratorForNode(node, parserContext).decorate(node, definition, parserContext); + } + + /** + * Locates the {@link BeanDefinitionParser} from the register implementations using + * the local name of the supplied {@link Node}. Supports both {@link Element Elements} + * and {@link Attr Attrs}. + */ + private BeanDefinitionDecorator findDecoratorForNode(Node node, ParserContext parserContext) { + BeanDefinitionDecorator decorator = null; + if (node instanceof Element) { + decorator = (BeanDefinitionDecorator) this.decorators.get(node.getLocalName()); + } + else if (node instanceof Attr) { + decorator = (BeanDefinitionDecorator) this.attributeDecorators.get(node.getLocalName()); + } + else { + parserContext.getReaderContext().fatal( + "Cannot decorate based on Nodes of type [" + node.getClass().getName() + "]", node); + } + if (decorator == null) { + parserContext.getReaderContext().fatal("Cannot locate BeanDefinitionDecorator for " + + (node instanceof Element ? "element" : "attribute") + " [" + node.getLocalName() + "]", node); + } + return decorator; + } + + /** + * Locate the {@link BeanDefinitionParser} from the register implementations using + * the local name of the supplied {@link Node}. Supports both {@link Element Elements} + * and {@link Attr Attrs}. + * @deprecated as of Spring 2.0.2; there should be no need to call this directly. + */ + protected final BeanDefinitionDecorator findDecoratorForNode(Node node) { + BeanDefinitionDecorator decorator = null; + if (node instanceof Element) { + decorator = (BeanDefinitionDecorator) this.decorators.get(node.getLocalName()); + } + else if (node instanceof Attr) { + decorator = (BeanDefinitionDecorator) this.attributeDecorators.get(node.getLocalName()); + } + else { + throw new IllegalStateException( + "Cannot decorate based on Nodes of type [" + node.getClass().getName() + "]"); + } + if (decorator == null) { + throw new IllegalStateException("Cannot locate BeanDefinitionDecorator for " + + (node instanceof Element ? "element" : "attribute") + " [" + node.getLocalName() + "]"); + } + return decorator; + } + + + /** + * Subclasses can call this to register the supplied {@link BeanDefinitionParser} to + * handle the specified element. The element name is the local (non-namespace qualified) + * name. + */ + protected final void registerBeanDefinitionParser(String elementName, BeanDefinitionParser parser) { + this.parsers.put(elementName, parser); + } + + /** + * Subclasses can call this to register the supplied {@link BeanDefinitionDecorator} to + * handle the specified element. The element name is the local (non-namespace qualified) + * name. + */ + protected final void registerBeanDefinitionDecorator(String elementName, BeanDefinitionDecorator decorator) { + this.decorators.put(elementName, decorator); + } + + /** + * Subclasses can call this to register the supplied {@link BeanDefinitionDecorator} to + * handle the specified attribute. The attribute name is the local (non-namespace qualified) + * name. + */ + protected final void registerBeanDefinitionDecoratorForAttribute( + String attributeName, BeanDefinitionDecorator decorator) { + + this.attributeDecorators.put(attributeName, decorator); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/ParserContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/ParserContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/ParserContext.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,124 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import java.util.Stack; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.parsing.ComponentDefinition; +import org.springframework.beans.factory.parsing.CompositeComponentDefinition; +import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; + +/** + * Context that gets passed along a bean definition parsing process, + * encapsulating all relevant configuration as well as state. + * Nested inside an {@link XmlReaderContext}. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + * @see XmlReaderContext + * @see BeanDefinitionParserDelegate + */ +public final class ParserContext { + + private final XmlReaderContext readerContext; + + private final BeanDefinitionParserDelegate delegate; + + private BeanDefinition containingBeanDefinition; + + private final Stack containingComponents = new Stack(); + + + public ParserContext(XmlReaderContext readerContext, BeanDefinitionParserDelegate delegate) { + this.readerContext = readerContext; + this.delegate = delegate; + } + + public ParserContext(XmlReaderContext readerContext, BeanDefinitionParserDelegate delegate, + BeanDefinition containingBeanDefinition) { + + this.readerContext = readerContext; + this.delegate = delegate; + this.containingBeanDefinition = containingBeanDefinition; + } + + + public final XmlReaderContext getReaderContext() { + return this.readerContext; + } + + public final BeanDefinitionRegistry getRegistry() { + return this.readerContext.getRegistry(); + } + + public final BeanDefinitionParserDelegate getDelegate() { + return this.delegate; + } + + public final BeanDefinition getContainingBeanDefinition() { + return this.containingBeanDefinition; + } + + public final boolean isNested() { + return (this.containingBeanDefinition != null); + } + + public boolean isDefaultLazyInit() { + return BeanDefinitionParserDelegate.TRUE_VALUE.equals(this.delegate.getDefaults().getLazyInit()); + } + + public Object extractSource(Object sourceCandidate) { + return this.readerContext.extractSource(sourceCandidate); + } + + public CompositeComponentDefinition getContainingComponent() { + return (!this.containingComponents.isEmpty() ? + (CompositeComponentDefinition) this.containingComponents.lastElement() : null); + } + + public void pushContainingComponent(CompositeComponentDefinition containingComponent) { + this.containingComponents.push(containingComponent); + } + + public CompositeComponentDefinition popContainingComponent() { + return (CompositeComponentDefinition) this.containingComponents.pop(); + } + + public void popAndRegisterContainingComponent() { + registerComponent(popContainingComponent()); + } + + public void registerComponent(ComponentDefinition component) { + CompositeComponentDefinition containingComponent = getContainingComponent(); + if (containingComponent != null) { + containingComponent.addNestedComponent(component); + } + else { + this.readerContext.fireComponentRegistered(component); + } + } + + public void registerBeanComponent(BeanComponentDefinition component) { + BeanDefinitionReaderUtils.registerBeanDefinition(component, getRegistry()); + registerComponent(component); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/PluggableSchemaResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/PluggableSchemaResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/PluggableSchemaResolver.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,142 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import java.io.IOException; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; + +import org.springframework.beans.FatalBeanException; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PropertiesLoaderUtils; +import org.springframework.util.Assert; + +/** + * {@link EntityResolver} implementation that attempts to resolve schema URLs into + * local {@link ClassPathResource classpath resources} using a set of mappings files. + * + *

    By default, this class will look for mapping files in the classpath using the pattern: + * META-INF/spring.schemas allowing for multiple files to exist on the + * classpath at any one time. + * + * The format of META-INF/spring.schemas is a properties + * file where each line should be of the form systemId=schema-location + * where schema-location should also be a schema file in the classpath. + * Since systemId is commonly a URL, one must be careful to escape any ':' characters + * which are treated as delimiters in properties files. + * + *

    The pattern for the mapping files can be overidden using the + * {@link #PluggableSchemaResolver(ClassLoader, String)} constructor + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public class PluggableSchemaResolver implements EntityResolver { + + /** + * The location of the file that defines schema mappings. + * Can be present in multiple JAR files. + */ + public static final String DEFAULT_SCHEMA_MAPPINGS_LOCATION = "META-INF/spring.schemas"; + + + private static final Log logger = LogFactory.getLog(PluggableSchemaResolver.class); + + private final ClassLoader classLoader; + + private final String schemaMappingsLocation; + + /** Stores the mapping of schema URL -> local schema path */ + private Properties schemaMappings; + + + /** + * Loads the schema URL -> schema file location mappings using the default + * mapping file pattern "META-INF/spring.schemas". + * @param classLoader the ClassLoader to use for loading + * (can be null) to use the default ClassLoader) + * @see PropertiesLoaderUtils#loadAllProperties(String, ClassLoader) + */ + public PluggableSchemaResolver(ClassLoader classLoader) { + this.classLoader = classLoader; + this.schemaMappingsLocation = DEFAULT_SCHEMA_MAPPINGS_LOCATION; + } + + /** + * Loads the schema URL -> schema file location mappings using the given + * mapping file pattern. + * @param classLoader the ClassLoader to use for loading + * (can be null) to use the default ClassLoader) + * @param schemaMappingsLocation the location of the file that defines schema mappings + * (must not be empty) + * @see PropertiesLoaderUtils#loadAllProperties(String, ClassLoader) + */ + public PluggableSchemaResolver(ClassLoader classLoader, String schemaMappingsLocation) { + Assert.hasText(schemaMappingsLocation, "'schemaMappingsLocation' must not be empty"); + this.classLoader = classLoader; + this.schemaMappingsLocation = schemaMappingsLocation; + } + + + public InputSource resolveEntity(String publicId, String systemId) throws IOException { + if (logger.isTraceEnabled()) { + logger.trace("Trying to resolve XML entity with public id [" + publicId + + "] and system id [" + systemId + "]"); + } + if (systemId != null) { + String resourceLocation = getSchemaMapping(systemId); + if (resourceLocation != null) { + Resource resource = new ClassPathResource(resourceLocation, this.classLoader); + InputSource source = new InputSource(resource.getInputStream()); + source.setPublicId(publicId); + source.setSystemId(systemId); + if (logger.isDebugEnabled()) { + logger.debug("Found XML schema [" + systemId + "] in classpath: " + resourceLocation); + } + return source; + } + } + return null; + } + + protected String getSchemaMapping(String systemId) { + if (this.schemaMappings == null) { + if (logger.isDebugEnabled()) { + logger.debug("Loading schema mappings from [" + this.schemaMappingsLocation + "]"); + } + try { + this.schemaMappings = + PropertiesLoaderUtils.loadAllProperties(this.schemaMappingsLocation, this.classLoader); + if (logger.isDebugEnabled()) { + logger.debug("Loaded schema mappings: " + this.schemaMappings); + } + } + catch (IOException ex) { + throw new FatalBeanException( + "Unable to load schema mappings from location [" + this.schemaMappingsLocation + "]", ex); + } + } + return this.schemaMappings.getProperty(systemId); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/ResourceEntityResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/ResourceEntityResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/ResourceEntityResolver.java 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,109 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLDecoder; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; + +/** + * EntityResolver implementation that tries to resolve entity references + * through a {@link org.springframework.core.io.ResourceLoader} (usually, + * relative to the resource base of an ApplicationContext), if applicable. + * Extends {@link DelegatingEntityResolver} to also provide DTD and XSD lookup. + * + *

    Allows to use standard XML entities to include XML snippets into an + * application context definition, for example to split a large XML file + * into various modules. The include paths can be relative to the + * application context's resource base as usual, instead of relative + * to the JVM working directory (the XML parser's default). + * + *

    Note: In addition to relative paths, every URL that specifies a + * file in the current system root, i.e. the JVM working directory, + * will be interpreted relative to the application context too. + * + * @author Juergen Hoeller + * @since 31.07.2003 + * @see org.springframework.core.io.ResourceLoader + * @see org.springframework.context.ApplicationContext + */ +public class ResourceEntityResolver extends DelegatingEntityResolver { + + private static final Log logger = LogFactory.getLog(ResourceEntityResolver.class); + + private final ResourceLoader resourceLoader; + + + /** + * Create a ResourceEntityResolver for the specified ResourceLoader + * (usually, an ApplicationContext). + * @param resourceLoader the ResourceLoader (or ApplicationContext) + * to load XML entity includes with + */ + public ResourceEntityResolver(ResourceLoader resourceLoader) { + super(resourceLoader.getClassLoader()); + this.resourceLoader = resourceLoader; + } + + + public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { + InputSource source = super.resolveEntity(publicId, systemId); + if (source == null && systemId != null) { + String resourcePath = null; + try { + String decodedSystemId = URLDecoder.decode(systemId); + String givenUrl = new URL(decodedSystemId).toString(); + String systemRootUrl = new File("").toURL().toString(); + // Try relative to resource base if currently in system root. + if (givenUrl.startsWith(systemRootUrl)) { + resourcePath = givenUrl.substring(systemRootUrl.length()); + } + } + catch (Exception ex) { + // Typically a MalformedURLException or AccessControlException. + if (logger.isDebugEnabled()) { + logger.debug("Could not resolve XML entity [" + systemId + "] against system root URL", ex); + } + // No URL (or no resolvable URL) -> try relative to resource base. + resourcePath = systemId; + } + if (resourcePath != null) { + if (logger.isTraceEnabled()) { + logger.trace("Trying to locate XML entity [" + systemId + "] as resource [" + resourcePath + "]"); + } + Resource resource = this.resourceLoader.getResource(resourcePath); + source = new InputSource(resource.getInputStream()); + source.setPublicId(publicId); + source.setSystemId(systemId); + if (logger.isDebugEnabled()) { + logger.debug("Found XML entity [" + systemId + "]: " + resource); + } + } + } + return source; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandler.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,85 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.core.Conventions; + +/** + * Simple NamespaceHandler implementation that maps custom attributes + * directly through to bean properties. An important point to note is that this + * NamespaceHandler does not have a corresponding schema since there + * is no way to know in advance all possible attribute names. + * + *

    An example of the usage of this NamespaceHandler is shown below: + * + *

    + * <bean id="rob" class="..TestBean" p:name="Rob Harrop" p:spouse-ref="sally"/>
    + * + * Here the 'p:name' corresponds directly to the 'name' + * property on class 'TestBean'. The 'p:spouse-ref' + * attributes corresponds to the 'spouse' property and, rather + * than being the concrete value, it contains the name of the bean that will + * be injected into that property. + * + * @author Rob Harrop + * @since 2.0 + */ +public class SimplePropertyNamespaceHandler implements NamespaceHandler { + + private static final String REF_SUFFIX = "-ref"; + + + public void init() { + } + + public BeanDefinition parse(Element element, ParserContext parserContext) { + parserContext.getReaderContext().error( + "Class [" + getClass().getName() + "] does not support custom elements.", element); + return null; + } + + public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) { + if (node instanceof Attr) { + Attr attr = (Attr) node; + String propertyName = attr.getLocalName(); + String propertyValue = attr.getValue(); + MutablePropertyValues pvs = definition.getBeanDefinition().getPropertyValues(); + if (pvs.contains(propertyName)) { + parserContext.getReaderContext().error("Property '" + propertyName + "' is already defined using " + + "both and inline syntax. Only one approach may be used per property.", attr); + } + if (propertyName.endsWith(REF_SUFFIX)) { + propertyName = propertyName.substring(0, propertyName.length() - REF_SUFFIX.length()); + pvs.addPropertyValue( + Conventions.attributeNameToPropertyName(propertyName), new RuntimeBeanReference(propertyValue)); + } + else { + pvs.addPropertyValue(Conventions.attributeNameToPropertyName(propertyName), propertyValue); + } + } + return definition; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/UtilNamespaceHandler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/UtilNamespaceHandler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/UtilNamespaceHandler.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,192 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.FieldRetrievingFactoryBean; +import org.springframework.beans.factory.config.ListFactoryBean; +import org.springframework.beans.factory.config.MapFactoryBean; +import org.springframework.beans.factory.config.PropertiesFactoryBean; +import org.springframework.beans.factory.config.PropertyPathFactoryBean; +import org.springframework.beans.factory.config.SetFactoryBean; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.util.StringUtils; + +/** + * {@link NamespaceHandler} for the util namespace. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public class UtilNamespaceHandler extends NamespaceHandlerSupport { + + private static final String SCOPE_ATTRIBUTE = "scope"; + + + public void init() { + registerBeanDefinitionParser("constant", new ConstantBeanDefinitionParser()); + registerBeanDefinitionParser("property-path", new PropertyPathBeanDefinitionParser()); + registerBeanDefinitionParser("list", new ListBeanDefinitionParser()); + registerBeanDefinitionParser("set", new SetBeanDefinitionParser()); + registerBeanDefinitionParser("map", new MapBeanDefinitionParser()); + registerBeanDefinitionParser("properties", new PropertiesBeanDefinitionParser()); + } + + + private static class ConstantBeanDefinitionParser extends AbstractSimpleBeanDefinitionParser { + + protected Class getBeanClass(Element element) { + return FieldRetrievingFactoryBean.class; + } + + protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) { + String id = super.resolveId(element, definition, parserContext); + if (!StringUtils.hasText(id)) { + id = element.getAttribute("static-field"); + } + return id; + } + } + + + private static class PropertyPathBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { + + protected Class getBeanClass(Element element) { + return PropertyPathFactoryBean.class; + } + + protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { + String path = element.getAttribute("path"); + if (!StringUtils.hasText(path)) { + parserContext.getReaderContext().error("Attribute 'path' must not be empty", element); + return; + } + int dotIndex = path.indexOf("."); + if (dotIndex == -1) { + parserContext.getReaderContext().error( + "Attribute 'path' must follow pattern 'beanName.propertyName'", element); + return; + } + String beanName = path.substring(0, dotIndex); + String propertyPath = path.substring(dotIndex + 1); + builder.addPropertyValue("targetBeanName", beanName); + builder.addPropertyValue("propertyPath", propertyPath); + } + + protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) { + String id = super.resolveId(element, definition, parserContext); + if (!StringUtils.hasText(id)) { + id = element.getAttribute("path"); + } + return id; + } + } + + + private static class ListBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { + + protected Class getBeanClass(Element element) { + return ListFactoryBean.class; + } + + protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { + String listClass = element.getAttribute("list-class"); + List parsedList = parserContext.getDelegate().parseListElement(element, builder.getRawBeanDefinition()); + builder.addPropertyValue("sourceList", parsedList); + if (StringUtils.hasText(listClass)) { + builder.addPropertyValue("targetListClass", listClass); + } + String scope = element.getAttribute(SCOPE_ATTRIBUTE); + if (StringUtils.hasLength(scope)) { + builder.setScope(scope); + } + } + } + + + private static class SetBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { + + protected Class getBeanClass(Element element) { + return SetFactoryBean.class; + } + + protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { + String setClass = element.getAttribute("set-class"); + Set parsedSet = parserContext.getDelegate().parseSetElement(element, builder.getRawBeanDefinition()); + builder.addPropertyValue("sourceSet", parsedSet); + if (StringUtils.hasText(setClass)) { + builder.addPropertyValue("targetSetClass", setClass); + } + String scope = element.getAttribute(SCOPE_ATTRIBUTE); + if (StringUtils.hasLength(scope)) { + builder.setScope(scope); + } + } + } + + + private static class MapBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { + + protected Class getBeanClass(Element element) { + return MapFactoryBean.class; + } + + protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { + String mapClass = element.getAttribute("map-class"); + Map parsedMap = parserContext.getDelegate().parseMapElement(element, builder.getRawBeanDefinition()); + builder.addPropertyValue("sourceMap", parsedMap); + if (StringUtils.hasText(mapClass)) { + builder.addPropertyValue("targetMapClass", mapClass); + } + String scope = element.getAttribute(SCOPE_ATTRIBUTE); + if (StringUtils.hasLength(scope)) { + builder.setScope(scope); + } + } + } + + + private static class PropertiesBeanDefinitionParser extends AbstractSimpleBeanDefinitionParser { + + protected Class getBeanClass(Element element) { + return PropertiesFactoryBean.class; + } + + protected boolean isEligibleAttribute(String attributeName) { + return super.isEligibleAttribute(attributeName) && !SCOPE_ATTRIBUTE.equals(attributeName); + } + + protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { + super.doParse(element, parserContext, builder); + Properties parsedProps = parserContext.getDelegate().parsePropsElement(element); + builder.addPropertyValue("properties", parsedProps); + String scope = element.getAttribute(SCOPE_ATTRIBUTE); + if (StringUtils.hasLength(scope)) { + builder.setScope(scope); + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlBeanDefinitionParser.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.w3c.dom.Document; + +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.support.BeanDefinitionReader; +import org.springframework.core.io.Resource; + +/** + * Strategy interface for parsing XML bean definitions. + * Used by XmlBeanDefinitionReader for actually parsing a DOM document. + * + *

    Instantiated per document to parse: Implementations can hold + * state in instance variables during the execution of the + * registerBeanDefinitions method, for example global + * settings that are defined for all bean definitions in the document. + * + * @author Juergen Hoeller + * @since 18.12.2003 + * @deprecated as of Spring 2.0: superseded by BeanDefinitionDocumentReader + * @see BeanDefinitionDocumentReader + * @see XmlBeanDefinitionReader#setParserClass + */ +public interface XmlBeanDefinitionParser { + + /** + * Parse bean definitions from the given DOM document, + * and register them with the given bean factory. + * @param reader the bean definition reader, containing the bean factory + * to work on and the bean class loader to use. Can also be used to load + * further bean definition files referenced by the given document. + * @param doc the DOM document + * @param resource descriptor of the original XML resource + * (useful for displaying parse errors) + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of parsing errors + */ + int registerBeanDefinitions(BeanDefinitionReader reader, Document doc, Resource resource) + throws BeanDefinitionStoreException; + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlBeanDefinitionReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlBeanDefinitionReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlBeanDefinitionReader.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,540 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashSet; +import java.util.Set; + +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.xml.sax.EntityResolver; +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.parsing.EmptyReaderEventListener; +import org.springframework.beans.factory.parsing.FailFastProblemReporter; +import org.springframework.beans.factory.parsing.NullSourceExtractor; +import org.springframework.beans.factory.parsing.ProblemReporter; +import org.springframework.beans.factory.parsing.ReaderEventListener; +import org.springframework.beans.factory.parsing.SourceExtractor; +import org.springframework.beans.factory.support.AbstractBeanDefinitionReader; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.core.Constants; +import org.springframework.core.NamedThreadLocal; +import org.springframework.core.io.DescriptiveResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.EncodedResource; +import org.springframework.util.Assert; +import org.springframework.util.xml.SimpleSaxErrorHandler; +import org.springframework.util.xml.XmlValidationModeDetector; + +/** + * Bean definition reader for XML bean definitions. + * Delegates the actual XML document reading to an implementation + * of the {@link BeanDefinitionDocumentReader} interface. + * + *

    Typically applied to a + * {@link org.springframework.beans.factory.support.DefaultListableBeanFactory} + * or a {@link org.springframework.context.support.GenericApplicationContext}. + * + *

    This class loads a DOM document and applies the BeanDefinitionDocumentReader to it. + * The document reader will register each bean definition with the given bean factory, + * talking to the latter's implementation of the + * {@link org.springframework.beans.factory.support.BeanDefinitionRegistry} interface. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @since 26.11.2003 + * @see #setDocumentReaderClass + * @see BeanDefinitionDocumentReader + * @see DefaultBeanDefinitionDocumentReader + * @see BeanDefinitionRegistry + * @see org.springframework.beans.factory.support.DefaultListableBeanFactory + * @see org.springframework.context.support.GenericApplicationContext + */ +public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { + + /** + * Indicates that the validation should be disabled. + */ + public static final int VALIDATION_NONE = XmlValidationModeDetector.VALIDATION_NONE; + + /** + * Indicates that the validation mode should be detected automatically. + */ + public static final int VALIDATION_AUTO = XmlValidationModeDetector.VALIDATION_AUTO; + + /** + * Indicates that DTD validation should be used. + */ + public static final int VALIDATION_DTD = XmlValidationModeDetector.VALIDATION_DTD; + + /** + * Indicates that XSD validation should be used. + */ + public static final int VALIDATION_XSD = XmlValidationModeDetector.VALIDATION_XSD; + + + /** Constants instance for this class */ + private static final Constants constants = new Constants(XmlBeanDefinitionReader.class); + + private boolean namespaceAware; + + private int validationMode = VALIDATION_AUTO; + + private Class parserClass; + + private Class documentReaderClass = DefaultBeanDefinitionDocumentReader.class; + + private ProblemReporter problemReporter = new FailFastProblemReporter(); + + private ReaderEventListener eventListener = new EmptyReaderEventListener(); + + private SourceExtractor sourceExtractor = new NullSourceExtractor(); + + private NamespaceHandlerResolver namespaceHandlerResolver; + + private DocumentLoader documentLoader = new DefaultDocumentLoader(); + + private EntityResolver entityResolver; + + private ErrorHandler errorHandler = new SimpleSaxErrorHandler(logger); + + private final XmlValidationModeDetector validationModeDetector = new XmlValidationModeDetector(); + + private final ThreadLocal resourcesCurrentlyBeingLoaded = + new NamedThreadLocal("XML bean definition resources currently being loaded"); + + + /** + * Create new XmlBeanDefinitionReader for the given bean factory. + * @param registry the BeanFactory to load bean definitions into, + * in the form of a BeanDefinitionRegistry + */ + public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) { + super(registry); + } + + + /** + * Set whether or not the XML parser should be XML namespace aware. + * Default is "false". + */ + public void setNamespaceAware(boolean namespaceAware) { + this.namespaceAware = namespaceAware; + } + + /** + * Return whether or not the XML parser should be XML namespace aware. + */ + public boolean isNamespaceAware() { + return this.namespaceAware; + } + + /** + * Set if the XML parser should validate the document and thus enforce a DTD. + * @deprecated as of Spring 2.0: superseded by "validationMode" + * @see #setValidationMode + */ + public void setValidating(boolean validating) { + this.validationMode = (validating ? VALIDATION_AUTO : VALIDATION_NONE); + } + + /** + * Set the validation mode to use by name. Defaults to {@link #VALIDATION_AUTO}. + */ + public void setValidationModeName(String validationModeName) { + setValidationMode(constants.asNumber(validationModeName).intValue()); + } + + /** + * Set the validation mode to use. Defaults to {@link #VALIDATION_AUTO}. + */ + public void setValidationMode(int validationMode) { + this.validationMode = validationMode; + } + + /** + * Return the validation mode to use. + */ + public int getValidationMode() { + return this.validationMode; + } + + /** + * Specify which {@link org.springframework.beans.factory.parsing.ProblemReporter} to use. Default implementation is + * {@link org.springframework.beans.factory.parsing.FailFastProblemReporter} which exhibits fail fast behaviour. External tools + * can provide an alternative implementation that collates errors and warnings for + * display in the tool UI. + */ + public void setProblemReporter(ProblemReporter problemReporter) { + this.problemReporter = (problemReporter != null ? problemReporter : new FailFastProblemReporter()); + } + + /** + * Specify which {@link ReaderEventListener} to use. Default implementation is + * EmptyReaderEventListener which discards every event notification. External tools + * can provide an alternative implementation to monitor the components being registered + * in the BeanFactory. + */ + public void setEventListener(ReaderEventListener eventListener) { + this.eventListener = (eventListener != null ? eventListener : new EmptyReaderEventListener()); + } + + /** + * Specify the {@link SourceExtractor} to use. The default implementation is + * {@link NullSourceExtractor} which simply returns null as the source object. + * This means that during normal runtime execution no additional source metadata is attached + * to the bean configuration metadata. + */ + public void setSourceExtractor(SourceExtractor sourceExtractor) { + this.sourceExtractor = (sourceExtractor != null ? sourceExtractor : new NullSourceExtractor()); + } + + /** + * Specify the {@link NamespaceHandlerResolver} to use. If none is specified a default + * instance will be created by {@link #createDefaultNamespaceHandlerResolver()}. + */ + public void setNamespaceHandlerResolver(NamespaceHandlerResolver namespaceHandlerResolver) { + this.namespaceHandlerResolver = namespaceHandlerResolver; + } + + /** + * Specify the {@link DocumentLoader} to use. The default implementation is + * {@link DefaultDocumentLoader} which loads {@link Document} instances using JAXP. + */ + public void setDocumentLoader(DocumentLoader documentLoader) { + this.documentLoader = (documentLoader != null ? documentLoader : new DefaultDocumentLoader()); + } + + /** + * Set a SAX entity resolver to be used for parsing. By default, + * BeansDtdResolver will be used. Can be overridden for custom entity + * resolution, for example relative to some specific base path. + * @see BeansDtdResolver + */ + public void setEntityResolver(EntityResolver entityResolver) { + this.entityResolver = entityResolver; + } + + /** + * Return the EntityResolver to use, building a default resolver + * if none specified. + */ + protected EntityResolver getEntityResolver() { + if (this.entityResolver == null) { + // Determine default EntityResolver to use. + ResourceLoader resourceLoader = getResourceLoader(); + if (resourceLoader != null) { + this.entityResolver = new ResourceEntityResolver(resourceLoader); + } + else { + this.entityResolver = new DelegatingEntityResolver(getBeanClassLoader()); + } + } + return this.entityResolver; + } + + /** + * Set an implementation of the org.xml.sax.ErrorHandler + * interface for custom handling of XML parsing errors and warnings. + *

    If not set, a default SimpleSaxErrorHandler is used that simply + * logs warnings using the logger instance of the view class, + * and rethrows errors to discontinue the XML transformation. + * @see SimpleSaxErrorHandler + */ + public void setErrorHandler(ErrorHandler errorHandler) { + this.errorHandler = errorHandler; + } + + /** + * Set the XmlBeanDefinitionParser implementation to use, + * responsible for the actual parsing of XML bean definitions. + * @deprecated as of Spring 2.0: superseded by "documentReaderClass" + * @see #setDocumentReaderClass + * @see XmlBeanDefinitionParser + */ + public void setParserClass(Class parserClass) { + if (this.parserClass == null || !XmlBeanDefinitionParser.class.isAssignableFrom(parserClass)) { + throw new IllegalArgumentException("'parserClass' must be an XmlBeanDefinitionParser"); + } + this.parserClass = parserClass; + } + + /** + * Specify the BeanDefinitionDocumentReader implementation to use, + * responsible for the actual reading of the XML bean definition document. + *

    Default is DefaultBeanDefinitionDocumentReader. + * @param documentReaderClass the desired BeanDefinitionDocumentReader implementation class + * @see BeanDefinitionDocumentReader + * @see DefaultBeanDefinitionDocumentReader + */ + public void setDocumentReaderClass(Class documentReaderClass) { + if (documentReaderClass == null || !BeanDefinitionDocumentReader.class.isAssignableFrom(documentReaderClass)) { + throw new IllegalArgumentException( + "documentReaderClass must be an implementation of the BeanDefinitionDocumentReader interface"); + } + this.documentReaderClass = documentReaderClass; + } + + + /** + * Load bean definitions from the specified XML file. + * @param resource the resource descriptor for the XML file + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + */ + public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException { + return loadBeanDefinitions(new EncodedResource(resource)); + } + + /** + * Load bean definitions from the specified XML file. + * @param encodedResource the resource descriptor for the XML file, + * allowing to specify an encoding to use for parsing the file + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + */ + public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException { + Assert.notNull(encodedResource, "EncodedResource must not be null"); + if (logger.isInfoEnabled()) { + logger.info("Loading XML bean definitions from " + encodedResource.getResource()); + } + + Set currentResources = (Set) this.resourcesCurrentlyBeingLoaded.get(); + if (currentResources == null) { + currentResources = new HashSet(4); + this.resourcesCurrentlyBeingLoaded.set(currentResources); + } + if (!currentResources.add(encodedResource)) { + throw new BeanDefinitionStoreException( + "Detected recursive loading of " + encodedResource + " - check your import definitions!"); + } + try { + InputStream inputStream = encodedResource.getResource().getInputStream(); + try { + InputSource inputSource = new InputSource(inputStream); + if (encodedResource.getEncoding() != null) { + inputSource.setEncoding(encodedResource.getEncoding()); + } + return doLoadBeanDefinitions(inputSource, encodedResource.getResource()); + } + finally { + inputStream.close(); + } + } + catch (IOException ex) { + throw new BeanDefinitionStoreException( + "IOException parsing XML document from " + encodedResource.getResource(), ex); + } + finally { + currentResources.remove(encodedResource); + if (currentResources.isEmpty()) { + this.resourcesCurrentlyBeingLoaded.set(null); + } + } + } + + /** + * Load bean definitions from the specified XML file. + * @param inputSource the SAX InputSource to read from + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + */ + public int loadBeanDefinitions(InputSource inputSource) throws BeanDefinitionStoreException { + return loadBeanDefinitions(inputSource, "resource loaded through SAX InputSource"); + } + + /** + * Load bean definitions from the specified XML file. + * @param inputSource the SAX InputSource to read from + * @param resourceDescription a description of the resource + * (can be null or empty) + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + */ + public int loadBeanDefinitions(InputSource inputSource, String resourceDescription) + throws BeanDefinitionStoreException { + + return doLoadBeanDefinitions(inputSource, new DescriptiveResource(resourceDescription)); + } + + + /** + * Actually load bean definitions from the specified XML file. + * @param inputSource the SAX InputSource to read from + * @param resource the resource descriptor for the XML file + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of loading or parsing errors + */ + protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) + throws BeanDefinitionStoreException { + try { + int validationMode = getValidationModeForResource(resource); + Document doc = this.documentLoader.loadDocument( + inputSource, getEntityResolver(), this.errorHandler, validationMode, isNamespaceAware()); + return registerBeanDefinitions(doc, resource); + } + catch (BeanDefinitionStoreException ex) { + throw ex; + } + catch (SAXParseException ex) { + throw new XmlBeanDefinitionStoreException(resource.getDescription(), + "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex); + } + catch (SAXException ex) { + throw new XmlBeanDefinitionStoreException(resource.getDescription(), + "XML document from " + resource + " is invalid", ex); + } + catch (ParserConfigurationException ex) { + throw new BeanDefinitionStoreException(resource.getDescription(), + "Parser configuration exception parsing XML from " + resource, ex); + } + catch (IOException ex) { + throw new BeanDefinitionStoreException(resource.getDescription(), + "IOException parsing XML document from " + resource, ex); + } + catch (Throwable ex) { + throw new BeanDefinitionStoreException(resource.getDescription(), + "Unexpected exception parsing XML document from " + resource, ex); + } + } + + + /** + * Gets the validation mode for the specified {@link Resource}. If no explicit + * validation mode has been configured then the validation mode is + * {@link #detectValidationMode detected}. + *

    Override this method if you would like full control over the validation + * mode, even when something other than {@link #VALIDATION_AUTO} was set. + */ + protected int getValidationModeForResource(Resource resource) { + int validationModeToUse = getValidationMode(); + if (validationModeToUse != VALIDATION_AUTO) { + return validationModeToUse; + } + int detectedMode = detectValidationMode(resource); + if (detectedMode != VALIDATION_AUTO) { + return detectedMode; + } + // Hmm, we didn't get a clear indication... Let's assume XSD, + // since apparently no DTD declaration has been found up until + // detection stopped (before finding the document's root tag). + return VALIDATION_XSD; + } + + /** + * Detects which kind of validation to perform on the XML file identified + * by the supplied {@link Resource}. If the file has a DOCTYPE + * definition then DTD validation is used otherwise XSD validation is assumed. + *

    Override this method if you would like to customize resolution + * of the {@link #VALIDATION_AUTO} mode. + */ + protected int detectValidationMode(Resource resource) { + if (resource.isOpen()) { + throw new BeanDefinitionStoreException( + "Passed-in Resource [" + resource + "] contains an open stream: " + + "cannot determine validation mode automatically. Either pass in a Resource " + + "that is able to create fresh streams, or explicitly specify the validationMode " + + "on your XmlBeanDefinitionReader instance."); + } + + InputStream inputStream; + try { + inputStream = resource.getInputStream(); + } + catch (IOException ex) { + throw new BeanDefinitionStoreException( + "Unable to determine validation mode for [" + resource + "]: cannot open InputStream. " + + "Did you attempt to load directly from a SAX InputSource without specifying the " + + "validationMode on your XmlBeanDefinitionReader instance?", ex); + } + + try { + return this.validationModeDetector.detectValidationMode(inputStream); + } + catch (IOException ex) { + throw new BeanDefinitionStoreException("Unable to determine validation mode for [" + + resource + "]: an error occurred whilst reading from the InputStream.", ex); + } + } + + /** + * Register the bean definitions contained in the given DOM document. + * Called by loadBeanDefinitions. + *

    Creates a new instance of the parser class and invokes + * registerBeanDefinitions on it. + * @param doc the DOM document + * @param resource the resource descriptor (for context information) + * @return the number of bean definitions found + * @throws BeanDefinitionStoreException in case of parsing errors + * @see #loadBeanDefinitions + * @see #setDocumentReaderClass + * @see BeanDefinitionDocumentReader#registerBeanDefinitions + */ + public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException { + // Support old XmlBeanDefinitionParser SPI for backwards-compatibility. + if (this.parserClass != null) { + XmlBeanDefinitionParser parser = + (XmlBeanDefinitionParser) BeanUtils.instantiateClass(this.parserClass); + return parser.registerBeanDefinitions(this, doc, resource); + } + // Read document based on new BeanDefinitionDocumentReader SPI. + BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader(); + int countBefore = getRegistry().getBeanDefinitionCount(); + documentReader.registerBeanDefinitions(doc, createReaderContext(resource)); + return getRegistry().getBeanDefinitionCount() - countBefore; + } + + /** + * Create the {@link BeanDefinitionDocumentReader} to use for actually + * reading bean definitions from an XML document. + *

    Default implementation instantiates the specified "documentReaderClass". + * @see #setDocumentReaderClass + */ + protected BeanDefinitionDocumentReader createBeanDefinitionDocumentReader() { + return (BeanDefinitionDocumentReader) BeanUtils.instantiateClass(this.documentReaderClass); + } + + /** + * Create the {@link XmlReaderContext} to pass over to the document reader. + */ + protected XmlReaderContext createReaderContext(Resource resource) { + if (this.namespaceHandlerResolver == null) { + this.namespaceHandlerResolver = createDefaultNamespaceHandlerResolver(); + } + return new XmlReaderContext(resource, this.problemReporter, this.eventListener, + this.sourceExtractor, this, this.namespaceHandlerResolver); + } + + /** + * Create the default implementation of {@link NamespaceHandlerResolver} used if none is specified. + * Default implementation returns an instance of {@link DefaultNamespaceHandlerResolver}. + */ + protected NamespaceHandlerResolver createDefaultNamespaceHandlerResolver() { + return new DefaultNamespaceHandlerResolver(getResourceLoader().getClassLoader()); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlBeanDefinitionStoreException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlBeanDefinitionStoreException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlBeanDefinitionStoreException.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +import org.springframework.beans.factory.BeanDefinitionStoreException; + +/** + * XML-specific BeanDefinitionStoreException subclass that wraps a + * {@link org.xml.sax.SAXException}, typically a {@link org.xml.sax.SAXParseException} + * which contains information about the error location. + * + * @author Juergen Hoeller + * @since 2.0.2 + * @see #getLineNumber() + * @see org.xml.sax.SAXParseException + */ +public class XmlBeanDefinitionStoreException extends BeanDefinitionStoreException { + + /** + * Create a new XmlBeanDefinitionStoreException. + * @param resourceDescription description of the resource that the bean definition came from + * @param msg the detail message (used as exception message as-is) + * @param cause the SAXException (typically a SAXParseException) root cause + * @see org.xml.sax.SAXParseException + */ + public XmlBeanDefinitionStoreException(String resourceDescription, String msg, SAXException cause) { + super(resourceDescription, msg, cause); + } + + /** + * Return the line number in the XML resource that failed. + * @return the line number if available (in case of a SAXParseException); -1 else + * @see org.xml.sax.SAXParseException#getLineNumber() + */ + public int getLineNumber() { + Throwable cause = getCause(); + if (cause instanceof SAXParseException) { + return ((SAXParseException) cause).getLineNumber(); + } + return -1; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlBeanFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlBeanFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlBeanFactory.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.core.io.Resource; + +/** + * Convenience extension of {@link DefaultListableBeanFactory} that reads bean definitions + * from an XML document. Delegates to {@link XmlBeanDefinitionReader} underneath; effectively + * equivalent to using an XmlBeanDefinitionReader with a DefaultListableBeanFactory. + * + *

    The structure, element and attribute names of the required XML document + * are hard-coded in this class. (Of course a transform could be run if necessary + * to produce this format). "beans" doesn't need to be the root element of the XML + * document: This class will parse all bean definition elements in the XML file. + * + *

    This class registers each bean definition with the {@link DefaultListableBeanFactory} + * superclass, and relies on the latter's implementation of the {@link BeanFactory} interface. + * It supports singletons, prototypes, and references to either of these kinds of bean. + * See "spring-beans-2.0.dtd" for details on options and configuration style. + * + *

    For advanced needs, consider using a {@link DefaultListableBeanFactory} with + * an {@link XmlBeanDefinitionReader}. The latter allows for reading from multiple XML + * resources and is highly configurable in its actual XML parsing behavior. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 15 April 2001 + * @see org.springframework.beans.factory.support.DefaultListableBeanFactory + * @see XmlBeanDefinitionReader + */ +public class XmlBeanFactory extends DefaultListableBeanFactory { + + private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this); + + + /** + * Create a new XmlBeanFactory with the given resource, + * which must be parsable using DOM. + * @param resource XML resource to load bean definitions from + * @throws BeansException in case of loading or parsing errors + */ + public XmlBeanFactory(Resource resource) throws BeansException { + this(resource, null); + } + + /** + * Create a new XmlBeanFactory with the given input stream, + * which must be parsable using DOM. + * @param resource XML resource to load bean definitions from + * @param parentBeanFactory parent bean factory + * @throws BeansException in case of loading or parsing errors + */ + public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException { + super(parentBeanFactory); + this.reader.loadBeanDefinitions(resource); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlReaderContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlReaderContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/XmlReaderContext.java 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,86 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory.xml; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.parsing.ProblemReporter; +import org.springframework.beans.factory.parsing.ReaderContext; +import org.springframework.beans.factory.parsing.ReaderEventListener; +import org.springframework.beans.factory.parsing.SourceExtractor; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; + +/** + * Extension of {@link org.springframework.beans.factory.parsing.ReaderContext}, + * specific to use with an {@link XmlBeanDefinitionReader}. Provides access to the + * {@link NamespaceHandlerResolver} configured in the {@link XmlBeanDefinitionReader}. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public class XmlReaderContext extends ReaderContext { + + private final XmlBeanDefinitionReader reader; + + private final NamespaceHandlerResolver namespaceHandlerResolver; + + + public XmlReaderContext( + Resource resource, ProblemReporter problemReporter, + ReaderEventListener eventListener, SourceExtractor sourceExtractor, + XmlBeanDefinitionReader reader, NamespaceHandlerResolver namespaceHandlerResolver) { + + super(resource, problemReporter, eventListener, sourceExtractor); + this.reader = reader; + this.namespaceHandlerResolver = namespaceHandlerResolver; + } + + + public final XmlBeanDefinitionReader getReader() { + return this.reader; + } + + public final BeanDefinitionRegistry getRegistry() { + return this.reader.getRegistry(); + } + + public final ResourceLoader getResourceLoader() { + return this.reader.getResourceLoader(); + } + + public final ClassLoader getBeanClassLoader() { + return this.reader.getBeanClassLoader(); + } + + public final NamespaceHandlerResolver getNamespaceHandlerResolver() { + return this.namespaceHandlerResolver; + } + + + public String generateBeanName(BeanDefinition beanDefinition) { + return this.reader.getBeanNameGenerator().generateBeanName(beanDefinition, getRegistry()); + } + + public String registerWithGeneratedName(BeanDefinition beanDefinition) { + String generatedName = generateBeanName(beanDefinition); + getRegistry().registerBeanDefinition(generatedName, beanDefinition); + return generatedName; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/package.html 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,8 @@ + + + +Contains an abstract XML-based BeanFactory implementation, +including a standard "spring-beans" DTD. + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-beans-2.0.dtd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-beans-2.0.dtd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-beans-2.0.dtd 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,679 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-beans-2.0.xsd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-beans-2.0.xsd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-beans-2.0.xsd 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,1077 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /' element. + ]]> + + + + + + + + + + /' element. + ]]> + + + + + + + + + + + + + + /' element. + ]]> + + + + + + + + + + + + + /' element. + ]]> + + + + + /' element. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + element (or "ref" + attribute). We recommend this in most cases as it makes documentation + more explicit. + + 2. "byName" + Autowiring by property name. If a bean of class Cat exposes a dog + property, Spring will try to set this to the value of the bean "dog" + in the current container. If there is no matching bean by name, nothing + special happens; use dependency-check="objects" to raise an error in + that case. + + 3. "byType" + Autowiring if there is exactly one bean of the property type in the + container. If there is more than one, a fatal error is raised, and + you cannot use byType autowiring for that bean. If there is none, + nothing special happens; use dependency-check="objects" to raise an + error in that case. + + 4. "constructor" + Analogous to "byType" for constructor arguments. If there is not exactly + one bean of the constructor argument type in the bean factory, a fatal + error is raised. + + 5. "autodetect" + Chooses "constructor" or "byType" through introspection of the bean + class. If a default constructor is found, "byType" gets applied. + + Note that explicit dependencies, i.e. "property" and "constructor-arg" + elements, always override autowiring. Autowire behavior can be combined + with dependency checking, which will be performed after all autowiring + has been completed. + + Note: This attribute will not be inherited by child bean definitions. + Hence, it needs to be specified per concrete bean definition. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + " element. + ]]> + + + + + ..." element. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ". + ]]> + + + + + ..." + element. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ". + ]]> + + + + + ..." + element. + ]]> + + + + + ". + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-beans-2.5.xsd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-beans-2.5.xsd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-beans-2.5.xsd 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,1164 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /' element. + ]]> + + + + + + + + + + /' element. + ]]> + + + + + + + + + + + + + + /' element. + ]]> + + + + + + + + + + + + + ' element for the semantic details of autowire candidate beans. + ]]> + + + + + /' element. + ]]> + + + + + /' element. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + element (or "ref" + attribute). We recommend this in most cases as it makes documentation + more explicit. + + 2. "byName" + Autowiring by property name. If a bean of class Cat exposes a dog + property, Spring will try to set this to the value of the bean "dog" + in the current container. If there is no matching bean by name, nothing + special happens; use dependency-check="objects" to raise an error in + that case. + + 3. "byType" + Autowiring if there is exactly one bean of the property type in the + container. If there is more than one, a fatal error is raised, and + you cannot use byType autowiring for that bean. If there is none, + nothing special happens; use dependency-check="objects" to raise an + error in that case. + + 4. "constructor" + Analogous to "byType" for constructor arguments. If there is not exactly + one bean of the constructor argument type in the bean factory, a fatal + error is raised. + + 5. "autodetect" + Chooses "constructor" or "byType" through introspection of the bean + class. If a default constructor is found, "byType" gets applied. + + Note that explicit dependencies, i.e. "property" and "constructor-arg" + elements, always override autowiring. Autowire behavior can be combined + with dependency checking, which will be performed after all autowiring + has been completed. + + Note: This attribute will not be inherited by child bean definitions. + Hence, it needs to be specified per concrete bean definition. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + " element. + ]]> + + + + + ..." element. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ". + ]]> + + + + + ..." element. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ". + ]]> + + + + + ..." + element. + ]]> + + + + + ". + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-beans.dtd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-beans.dtd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-beans.dtd 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,606 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-tool-2.0.xsd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-tool-2.0.xsd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-tool-2.0.xsd 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-tool-2.5.xsd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-tool-2.5.xsd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-tool-2.5.xsd 17 Aug 2012 15:11:33 -0000 1.1 @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-util-2.0.xsd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-util-2.0.xsd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-util-2.0.xsd 17 Aug 2012 15:11:32 -0000 1.1 @@ -0,0 +1,203 @@ + + + + + + + + + + + Reference a public, static field on a type and expose its value as + a bean. For example <util:constant static-field="java.lang.Integer.MAX_VALUE"/>. + + + + + + + + + + + + Reference a property on a bean (or as a nested value) and expose its values as + a bean. For example <util:property-path path="order.customer.name"/>. + + + + + + + + + + + + Builds a List instance of the specified type, populated with the specified content. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Builds a Set instance of the specified type, populated with the specified content. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Builds a Map instance of the specified type, populated with the specified content. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Loads a Properties instance from the resource location specified by the 'location' attribute. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-util-2.5.xsd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-util-2.5.xsd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/factory/xml/spring-util-2.5.xsd 17 Aug 2012 15:11:34 -0000 1.1 @@ -0,0 +1,212 @@ + + + + + + + + + + + Reference a public, static field on a type and expose its value as + a bean. For example <util:constant static-field="java.lang.Integer.MAX_VALUE"/>. + + + + + + + + + + + + Reference a property on a bean (or as a nested value) and expose its values as + a bean. For example <util:property-path path="order.customer.name"/>. + + + + + + + + + + + + Builds a List instance of the specified type, populated with the specified content. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Builds a Set instance of the specified type, populated with the specified content. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Builds a Map instance of the specified type, populated with the specified content. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Loads a Properties instance from the resource location specified by the 'location' attribute. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/ByteArrayPropertyEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/ByteArrayPropertyEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/ByteArrayPropertyEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; + +/** + * Editor for byte arrays. Strings will simply be converted to + * their corresponding byte representations. + * + * @author Juergen Hoeller + * @since 1.0.1 + * @see java.lang.String#getBytes + */ +public class ByteArrayPropertyEditor extends PropertyEditorSupport { + + public void setAsText(String text) { + setValue(text != null ? text.getBytes() : null); + } + + public String getAsText() { + byte[] value = (byte[]) getValue(); + return (value != null ? new String(value) : ""); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CharArrayPropertyEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/CharArrayPropertyEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CharArrayPropertyEditor.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; + +/** + * Editor for char arrays. Strings will simply be converted to + * their corresponding char representations. + * + * @author Juergen Hoeller + * @since 1.2.8 + * @see String#toCharArray() + */ +public class CharArrayPropertyEditor extends PropertyEditorSupport { + + public void setAsText(String text) { + setValue(text != null ? text.toCharArray() : null); + } + + public String getAsText() { + char[] value = (char[]) getValue(); + return (value != null ? new String(value) : ""); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CharacterEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/CharacterEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CharacterEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,107 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; + +import org.springframework.util.StringUtils; + +/** + * Editor for a {@link java.lang.Character}, to populate a property + * of type Character or char from a String value. + * + *

    Note that the JDK does not contain a default + * {@link java.beans.PropertyEditor property editor} for char! + * {@link org.springframework.beans.BeanWrapperImpl} will register this + * editor by default. + * + *

    Also supports conversion from a Unicode character sequence; e.g. + * u0041 ('A'). + * + * @author Juergen Hoeller + * @author Rob Harrop + * @author Rick Evans + * @since 1.2 + * @see java.lang.Character + * @see org.springframework.beans.BeanWrapperImpl + */ +public class CharacterEditor extends PropertyEditorSupport { + + /** + * The prefix that identifies a string as being a Unicode character sequence. + */ + private static final String UNICODE_PREFIX = "\\u"; + + /** + * The length of a Unicode character sequence. + */ + private static final int UNICODE_LENGTH = 6; + + + private final boolean allowEmpty; + + + /** + * Create a new CharacterEditor instance. + *

    The "allowEmpty" parameter controls whether an empty String is + * to be allowed in parsing, i.e. be interpreted as the null + * value when {@link #setAsText(String) text is being converted}. If + * false, an {@link IllegalArgumentException} will be thrown + * at that time. + * @param allowEmpty if empty strings are to be allowed + */ + public CharacterEditor(boolean allowEmpty) { + this.allowEmpty = allowEmpty; + } + + + public void setAsText(String text) throws IllegalArgumentException { + if (this.allowEmpty && !StringUtils.hasLength(text)) { + // Treat empty String as null value. + setValue(null); + } + else if (text == null) { + throw new IllegalArgumentException("null String cannot be converted to char type"); + } + else if (isUnicodeCharacterSequence(text)) { + setAsUnicode(text); + } + else if (text.length() != 1) { + throw new IllegalArgumentException("String [" + text + "] with length " + + text.length() + " cannot be converted to char type"); + } + else { + setValue(new Character(text.charAt(0))); + } + } + + public String getAsText() { + Object value = getValue(); + return (value != null ? value.toString() : ""); + } + + + private boolean isUnicodeCharacterSequence(String sequence) { + return (sequence.startsWith(UNICODE_PREFIX) && sequence.length() == UNICODE_LENGTH); + } + + private void setAsUnicode(String text) { + int code = Integer.parseInt(text.substring(UNICODE_PREFIX.length()), 16); + setValue(new Character((char) code)); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CharsetEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/CharsetEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CharsetEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; +import java.nio.charset.Charset; + +import org.springframework.util.StringUtils; + +/** + * Editor for {@link Charset}, to directly populate a Charset property. + * + *

    Expects the same syntax as Charset's {@link java.nio.charset.Charset#name()}, + * e.g. UTF-8, ISO-8859-16, etc. + * + * @author Arjen Poutsma + * @since 2.5.4 + * @see Charset + */ +public class CharsetEditor extends PropertyEditorSupport { + + public void setAsText(String text) throws IllegalArgumentException { + if (StringUtils.hasText(text)) { + setValue(Charset.forName(text)); + } + else { + setValue(null); + } + } + + public String getAsText() { + Charset value = (Charset) getValue(); + return (value != null ? value.name() : ""); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/ClassArrayEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/ClassArrayEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/ClassArrayEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,95 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; + +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +/** + * Property editor for an array of {@link java.lang.Class Classes}, to enable + * the direct population of a Class[] property without having to + * use a String class name property as bridge. + * + *

    Also supports "java.lang.String[]"-style array class names, in contrast + * to the standard {@link Class#forName(String)} method. + * + * @author Rob Harrop + * @since 2.0 + */ +public class ClassArrayEditor extends PropertyEditorSupport { + + private final ClassLoader classLoader; + + + /** + * Create a default ClassEditor, using the thread + * context ClassLoader. + */ + public ClassArrayEditor() { + this(null); + } + + /** + * Create a default ClassArrayEditor, using the given + * ClassLoader. + * @param classLoader the ClassLoader to use + * (or pass null for the thread context ClassLoader) + */ + public ClassArrayEditor(ClassLoader classLoader) { + this.classLoader = classLoader != null + ? classLoader : ClassUtils.getDefaultClassLoader(); + } + + + public void setAsText(String text) throws IllegalArgumentException { + if (StringUtils.hasText(text)) { + String[] classNames = StringUtils.commaDelimitedListToStringArray(text); + Class[] classes = new Class[classNames.length]; + for (int i = 0; i < classNames.length; i++) { + String className = classNames[i].trim(); + classes[i] = ClassUtils.resolveClassName(className, this.classLoader); + } + setValue(classes); + } + else { + setValue(null); + } + } + + public String getAsText() { + Class[] classes = (Class[]) getValue(); + if (classes == null || classes.length == 0) { + return ""; + } + return toCommaDelimitedString(classes); + } + + + private static String toCommaDelimitedString(Class[] classes) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < classes.length; ++i) { + if (i > 0) { + buffer.append(","); + } + buffer.append(ClassUtils.getQualifiedName(classes[i])); + } + return buffer.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/ClassEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/ClassEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/ClassEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; + +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +/** + * Property editor for {@link java.lang.Class java.lang.Class}, to enable the direct + * population of a Class property without recourse to having to use a + * String class name property as bridge. + * + *

    Also supports "java.lang.String[]"-style array class names, in contrast to the + * standard {@link Class#forName(String)} method. + * + * @author Juergen Hoeller + * @author Rick Evans + * @since 13.05.2003 + * @see java.lang.Class#forName + * @see org.springframework.util.ClassUtils#forName(String, ClassLoader) + */ +public class ClassEditor extends PropertyEditorSupport { + + private final ClassLoader classLoader; + + + /** + * Create a default ClassEditor, using the thread context ClassLoader. + */ + public ClassEditor() { + this(null); + } + + /** + * Create a default ClassEditor, using the given ClassLoader. + * @param classLoader the ClassLoader to use + * (or null for the thread context ClassLoader) + */ + public ClassEditor(ClassLoader classLoader) { + this.classLoader = + (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); + } + + + public void setAsText(String text) throws IllegalArgumentException { + if (StringUtils.hasText(text)) { + setValue(ClassUtils.resolveClassName(text.trim(), this.classLoader)); + } + else { + setValue(null); + } + } + + public String getAsText() { + Class clazz = (Class) getValue(); + if (clazz != null) { + return ClassUtils.getQualifiedName(clazz); + } + else { + return ""; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomBooleanEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomBooleanEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomBooleanEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,139 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; + +import org.springframework.util.StringUtils; + +/** + * Property editor for Boolean/boolean properties. + * + *

    This is not meant to be used as system PropertyEditor but rather as + * locale-specific Boolean editor within custom controller code, to parse + * UI-caused boolean strings into boolean properties of beans and check + * them in the UI form. + * + *

    In web MVC code, this editor will typically be registered with + * binder.registerCustomEditor calls in an implementation + * of BaseCommandController's initBinder method. + * + * @author Juergen Hoeller + * @since 10.06.2003 + * @see org.springframework.validation.DataBinder#registerCustomEditor + * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder + */ +public class CustomBooleanEditor extends PropertyEditorSupport { + + public static final String VALUE_TRUE = "true"; + public static final String VALUE_FALSE = "false"; + + public static final String VALUE_ON = "on"; + public static final String VALUE_OFF = "off"; + + public static final String VALUE_YES = "yes"; + public static final String VALUE_NO = "no"; + + public static final String VALUE_1 = "1"; + public static final String VALUE_0 = "0"; + + + private final String trueString; + + private final String falseString; + + private final boolean allowEmpty; + + + /** + * Create a new CustomBooleanEditor instance, with "true"/"on"/"yes" + * and "false"/"off"/"no" as recognized String values. + *

    The "allowEmpty" parameter states if an empty String should + * be allowed for parsing, i.e. get interpreted as null value. + * Else, an IllegalArgumentException gets thrown in that case. + * @param allowEmpty if empty strings should be allowed + */ + public CustomBooleanEditor(boolean allowEmpty) { + this(null, null, allowEmpty); + } + + /** + * Create a new CustomBooleanEditor instance, + * with configurable String values for true and false. + *

    The "allowEmpty" parameter states if an empty String should + * be allowed for parsing, i.e. get interpreted as null value. + * Else, an IllegalArgumentException gets thrown in that case. + * @param trueString the String value that represents true: + * for example, "true" (VALUE_TRUE), "on" (VALUE_ON), + * "yes" (VALUE_YES) or some custom value + * @param falseString the String value that represents false: + * for example, "false" (VALUE_FALSE), "off" (VALUE_OFF), + * "no" (VALUE_NO) or some custom value + * @param allowEmpty if empty strings should be allowed + * @see #VALUE_TRUE + * @see #VALUE_FALSE + * @see #VALUE_ON + * @see #VALUE_OFF + * @see #VALUE_YES + * @see #VALUE_NO + */ + public CustomBooleanEditor(String trueString, String falseString, boolean allowEmpty) { + this.trueString = trueString; + this.falseString = falseString; + this.allowEmpty = allowEmpty; + } + + public void setAsText(String text) throws IllegalArgumentException { + String input = (text != null ? text.trim() : null); + if (this.allowEmpty && !StringUtils.hasLength(input)) { + // Treat empty String as null value. + setValue(null); + } + else if (this.trueString != null && input.equalsIgnoreCase(this.trueString)) { + setValue(Boolean.TRUE); + } + else if (this.falseString != null && input.equalsIgnoreCase(this.falseString)) { + setValue(Boolean.FALSE); + } + else if (this.trueString == null && + (input.equalsIgnoreCase(VALUE_TRUE) || input.equalsIgnoreCase(VALUE_ON) || + input.equalsIgnoreCase(VALUE_YES) || input.equals(VALUE_1))) { + setValue(Boolean.TRUE); + } + else if (this.falseString == null && + (input.equalsIgnoreCase(VALUE_FALSE) || input.equalsIgnoreCase(VALUE_OFF) || + input.equalsIgnoreCase(VALUE_NO) || input.equals(VALUE_0))) { + setValue(Boolean.FALSE); + } + else { + throw new IllegalArgumentException("Invalid boolean value [" + text + "]"); + } + } + + public String getAsText() { + if (Boolean.TRUE.equals(getValue())) { + return (this.trueString != null ? this.trueString : VALUE_TRUE); + } + else if (Boolean.FALSE.equals(getValue())) { + return (this.falseString != null ? this.falseString : VALUE_FALSE); + } + else { + return ""; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomCollectionEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomCollectionEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomCollectionEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,206 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; + +/** + * Property editor for Collections, converting any source Collection + * to a given target Collection type. + * + *

    By default registered for Set, SortedSet and List, + * to automatically convert any given Collection to one of those + * target types if the type does not match the target property. + * + * @author Juergen Hoeller + * @since 1.1.3 + * @see java.util.Collection + * @see java.util.Set + * @see java.util.SortedSet + * @see java.util.List + */ +public class CustomCollectionEditor extends PropertyEditorSupport { + + private final Class collectionType; + + private final boolean nullAsEmptyCollection; + + + /** + * Create a new CustomCollectionEditor for the given target type, + * keeping an incoming null as-is. + * @param collectionType the target type, which needs to be a + * sub-interface of Collection or a concrete Collection class + * @see java.util.Collection + * @see java.util.ArrayList + * @see java.util.TreeSet + * @see java.util.LinkedHashSet + */ + public CustomCollectionEditor(Class collectionType) { + this(collectionType, false); + } + + /** + * Create a new CustomCollectionEditor for the given target type. + *

    If the incoming value is of the given type, it will be used as-is. + * If it is a different Collection type or an array, it will be converted + * to a default implementation of the given Collection type. + * If the value is anything else, a target Collection with that single + * value will be created. + *

    The default Collection implementations are: ArrayList for List, + * TreeSet for SortedSet, and LinkedHashSet for Set. + * @param collectionType the target type, which needs to be a + * sub-interface of Collection or a concrete Collection class + * @param nullAsEmptyCollection whether to convert an incoming null + * value to an empty Collection (of the appropriate type) + * @see java.util.Collection + * @see java.util.ArrayList + * @see java.util.TreeSet + * @see java.util.LinkedHashSet + */ + public CustomCollectionEditor(Class collectionType, boolean nullAsEmptyCollection) { + if (collectionType == null) { + throw new IllegalArgumentException("Collection type is required"); + } + if (!Collection.class.isAssignableFrom(collectionType)) { + throw new IllegalArgumentException( + "Collection type [" + collectionType.getName() + "] does not implement [java.util.Collection]"); + } + this.collectionType = collectionType; + this.nullAsEmptyCollection = nullAsEmptyCollection; + } + + + /** + * Convert the given text value to a Collection with a single element. + */ + public void setAsText(String text) throws IllegalArgumentException { + setValue(text); + } + + /** + * Convert the given value to a Collection of the target type. + */ + public void setValue(Object value) { + if (value == null && this.nullAsEmptyCollection) { + super.setValue(createCollection(this.collectionType, 0)); + } + else if (value == null || (this.collectionType.isInstance(value) && !alwaysCreateNewCollection())) { + // Use the source value as-is, as it matches the target type. + super.setValue(value); + } + else if (value instanceof Collection) { + // Convert Collection elements. + Collection source = (Collection) value; + Collection target = createCollection(this.collectionType, source.size()); + for (Iterator it = source.iterator(); it.hasNext();) { + target.add(convertElement(it.next())); + } + super.setValue(target); + } + else if (value.getClass().isArray()) { + // Convert array elements to Collection elements. + int length = Array.getLength(value); + Collection target = createCollection(this.collectionType, length); + for (int i = 0; i < length; i++) { + target.add(convertElement(Array.get(value, i))); + } + super.setValue(target); + } + else { + // A plain value: convert it to a Collection with a single element. + Collection target = createCollection(this.collectionType, 1); + target.add(convertElement(value)); + super.setValue(target); + } + } + + /** + * Create a Collection of the given type, with the given + * initial capacity (if supported by the Collection type). + * @param collectionType a sub-interface of Collection + * @param initialCapacity the initial capacity + * @return the new Collection instance + */ + protected Collection createCollection(Class collectionType, int initialCapacity) { + if (!collectionType.isInterface()) { + try { + return (Collection) collectionType.newInstance(); + } + catch (Exception ex) { + throw new IllegalArgumentException( + "Could not instantiate collection class [" + collectionType.getName() + "]: " + ex.getMessage()); + } + } + else if (List.class.equals(collectionType)) { + return new ArrayList(initialCapacity); + } + else if (SortedSet.class.equals(collectionType)) { + return new TreeSet(); + } + else { + return new LinkedHashSet(initialCapacity); + } + } + + /** + * Return whether to always create a new Collection, + * even if the type of the passed-in Collection already matches. + *

    Default is "false"; can be overridden to enforce creation of a + * new Collection, for example to convert elements in any case. + * @see #convertElement + */ + protected boolean alwaysCreateNewCollection() { + return false; + } + + /** + * Hook to convert each encountered Collection/array element. + * The default implementation simply returns the passed-in element as-is. + *

    Can be overridden to perform conversion of certain elements, + * for example String to Integer if a String array comes in and + * should be converted to a Set of Integer objects. + *

    Only called if actually creating a new Collection! + * This is by default not the case if the type of the passed-in Collection + * already matches. Override {@link #alwaysCreateNewCollection()} to + * enforce creating a new Collection in every case. + * @param element the source element + * @return the element to be used in the target Collection + * @see #alwaysCreateNewCollection() + */ + protected Object convertElement(Object element) { + return element; + } + + + /** + * This implementation returns null to indicate that + * there is no appropriate text representation. + */ + public String getAsText() { + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomDateEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomDateEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomDateEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,125 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; +import java.text.DateFormat; +import java.text.ParseException; +import java.util.Date; + +import org.springframework.util.StringUtils; + +/** + * Property editor for java.util.Date, + * supporting a custom java.text.DateFormat. + * + *

    This is not meant to be used as system PropertyEditor but rather + * as locale-specific date editor within custom controller code, + * parsing user-entered number strings into Date properties of beans + * and rendering them in the UI form. + * + *

    In web MVC code, this editor will typically be registered with + * binder.registerCustomEditor calls in a custom + * initBinder method. + * + * @author Juergen Hoeller + * @since 28.04.2003 + * @see java.util.Date + * @see java.text.DateFormat + * @see org.springframework.validation.DataBinder#registerCustomEditor + * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder + */ +public class CustomDateEditor extends PropertyEditorSupport { + + private final DateFormat dateFormat; + + private final boolean allowEmpty; + + private final int exactDateLength; + + + /** + * Create a new CustomDateEditor instance, using the given DateFormat + * for parsing and rendering. + *

    The "allowEmpty" parameter states if an empty String should + * be allowed for parsing, i.e. get interpreted as null value. + * Otherwise, an IllegalArgumentException gets thrown in that case. + * @param dateFormat DateFormat to use for parsing and rendering + * @param allowEmpty if empty strings should be allowed + */ + public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty) { + this.dateFormat = dateFormat; + this.allowEmpty = allowEmpty; + this.exactDateLength = -1; + } + + /** + * Create a new CustomDateEditor instance, using the given DateFormat + * for parsing and rendering. + *

    The "allowEmpty" parameter states if an empty String should + * be allowed for parsing, i.e. get interpreted as null value. + * Otherwise, an IllegalArgumentException gets thrown in that case. + *

    The "exactDateLength" parameter states that IllegalArgumentException gets + * thrown if the String does not exactly match the length specified. This is useful + * because SimpleDateFormat does not enforce strict parsing of the year part, + * not even with setLenient(false). Without an "exactDateLength" + * specified, the "01/01/05" would get parsed to "01/01/0005". + * @param dateFormat DateFormat to use for parsing and rendering + * @param allowEmpty if empty strings should be allowed + * @param exactDateLength the exact expected length of the date String + */ + public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) { + this.dateFormat = dateFormat; + this.allowEmpty = allowEmpty; + this.exactDateLength = exactDateLength; + } + + + /** + * Parse the Date from the given text, using the specified DateFormat. + */ + public void setAsText(String text) throws IllegalArgumentException { + if (this.allowEmpty && !StringUtils.hasText(text)) { + // Treat empty String as null value. + setValue(null); + } + else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) { + throw new IllegalArgumentException( + "Could not parse date: it is not exactly" + this.exactDateLength + "characters long"); + } + else { + try { + setValue(this.dateFormat.parse(text)); + } + catch (ParseException ex) { + IllegalArgumentException iae = + new IllegalArgumentException("Could not parse date: " + ex.getMessage()); + iae.initCause(ex); + throw iae; + } + } + } + + /** + * Format the Date as String, using the specified DateFormat. + */ + public String getAsText() { + Date value = (Date) getValue(); + return (value != null ? this.dateFormat.format(value) : ""); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomMapEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomMapEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomMapEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,199 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; + +/** + * Property editor for Maps, converting any source Map + * to a given target Map type. + * + * @author Juergen Hoeller + * @since 2.0.1 + * @see java.util.Map + * @see java.util.SortedMap + */ +public class CustomMapEditor extends PropertyEditorSupport { + + private final Class mapType; + + private final boolean nullAsEmptyMap; + + + /** + * Create a new CustomMapEditor for the given target type, + * keeping an incoming null as-is. + * @param mapType the target type, which needs to be a + * sub-interface of Map or a concrete Map class + * @see java.util.Map + * @see java.util.HashMap + * @see java.util.TreeMap + * @see java.util.LinkedHashMap + */ + public CustomMapEditor(Class mapType) { + this(mapType, false); + } + + /** + * Create a new CustomMapEditor for the given target type. + *

    If the incoming value is of the given type, it will be used as-is. + * If it is a different Map type or an array, it will be converted + * to a default implementation of the given Map type. + * If the value is anything else, a target Map with that single + * value will be created. + *

    The default Map implementations are: TreeMap for SortedMap, + * and LinkedHashMap for Map. + * @param mapType the target type, which needs to be a + * sub-interface of Map or a concrete Map class + * @param nullAsEmptyMap ap whether to convert an incoming null + * value to an empty Map (of the appropriate type) + * @see java.util.Map + * @see java.util.TreeMap + * @see java.util.LinkedHashMap + */ + public CustomMapEditor(Class mapType, boolean nullAsEmptyMap) { + if (mapType == null) { + throw new IllegalArgumentException("Map type is required"); + } + if (!Map.class.isAssignableFrom(mapType)) { + throw new IllegalArgumentException( + "Map type [" + mapType.getName() + "] does not implement [java.util.Map]"); + } + this.mapType = mapType; + this.nullAsEmptyMap = nullAsEmptyMap; + } + + + /** + * Convert the given text value to a Map with a single element. + */ + public void setAsText(String text) throws IllegalArgumentException { + setValue(text); + } + + /** + * Convert the given value to a Map of the target type. + */ + public void setValue(Object value) { + if (value == null && this.nullAsEmptyMap) { + super.setValue(createMap(this.mapType, 0)); + } + else if (value == null || (this.mapType.isInstance(value) && !alwaysCreateNewMap())) { + // Use the source value as-is, as it matches the target type. + super.setValue(value); + } + else if (value instanceof Map) { + // Convert Map elements. + Map source = (Map) value; + Map target = createMap(this.mapType, source.size()); + for (Iterator it = source.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + target.put(convertKey(entry.getKey()), convertValue(entry.getValue())); + } + super.setValue(target); + } + else { + throw new IllegalArgumentException("Value cannot be converted to Map: " + value); + } + } + + /** + * Create a Map of the given type, with the given + * initial capacity (if supported by the Map type). + * @param mapType a sub-interface of Map + * @param initialCapacity the initial capacity + * @return the new Map instance + */ + protected Map createMap(Class mapType, int initialCapacity) { + if (!mapType.isInterface()) { + try { + return (Map) mapType.newInstance(); + } + catch (Exception ex) { + throw new IllegalArgumentException( + "Could not instantiate map class [" + mapType.getName() + "]: " + ex.getMessage()); + } + } + else if (SortedMap.class.equals(mapType)) { + return new TreeMap(); + } + else { + return new LinkedHashMap(initialCapacity); + } + } + + /** + * Return whether to always create a new Map, + * even if the type of the passed-in Map already matches. + *

    Default is "false"; can be overridden to enforce creation of a + * new Map, for example to convert elements in any case. + * @see #convertKey + * @see #convertValue + */ + protected boolean alwaysCreateNewMap() { + return false; + } + + /** + * Hook to convert each encountered Map key. + * The default implementation simply returns the passed-in key as-is. + *

    Can be overridden to perform conversion of certain keys, + * for example from String to Integer. + *

    Only called if actually creating a new Map! + * This is by default not the case if the type of the passed-in Map + * already matches. Override {@link #alwaysCreateNewMap()} to + * enforce creating a new Map in every case. + * @param key the source key + * @return the key to be used in the target Map + * @see #alwaysCreateNewMap + */ + protected Object convertKey(Object key) { + return key; + } + + /** + * Hook to convert each encountered Map value. + * The default implementation simply returns the passed-in value as-is. + *

    Can be overridden to perform conversion of certain values, + * for example from String to Integer. + *

    Only called if actually creating a new Map! + * This is by default not the case if the type of the passed-in Map + * already matches. Override {@link #alwaysCreateNewMap()} to + * enforce creating a new Map in every case. + * @param value the source value + * @return the value to be used in the target Map + * @see #alwaysCreateNewMap + */ + protected Object convertValue(Object value) { + return value; + } + + + /** + * This implementation returns null to indicate that + * there is no appropriate text representation. + */ + public String getAsText() { + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomNumberEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomNumberEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/CustomNumberEditor.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,148 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; +import java.text.NumberFormat; + +import org.springframework.util.NumberUtils; +import org.springframework.util.StringUtils; + +/** + * Property editor for any Number subclass such as Short, Integer, Long, + * BigInteger, Float, Double, BigDecimal. Can use a given NumberFormat for + * (locale-specific) parsing and rendering, or alternatively the default + * decode / valueOf / toString methods. + * + *

    This is not meant to be used as system PropertyEditor but rather + * as locale-specific number editor within custom controller code, + * parsing user-entered number strings into Number properties of beans + * and rendering them in the UI form. + * + *

    In web MVC code, this editor will typically be registered with + * binder.registerCustomEditor calls in a custom + * initBinder method. + * + * @author Juergen Hoeller + * @since 06.06.2003 + * @see java.lang.Number + * @see java.text.NumberFormat + * @see org.springframework.validation.DataBinder#registerCustomEditor + * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder + */ +public class CustomNumberEditor extends PropertyEditorSupport { + + private final Class numberClass; + + private final NumberFormat numberFormat; + + private final boolean allowEmpty; + + + /** + * Create a new CustomNumberEditor instance, using the default + * valueOf methods for parsing and toString + * methods for rendering. + *

    The "allowEmpty" parameter states if an empty String should + * be allowed for parsing, i.e. get interpreted as null value. + * Else, an IllegalArgumentException gets thrown in that case. + * @param numberClass Number subclass to generate + * @param allowEmpty if empty strings should be allowed + * @throws IllegalArgumentException if an invalid numberClass has been specified + * @see org.springframework.util.NumberUtils#parseNumber(String, Class) + * @see Integer#valueOf + * @see Integer#toString + */ + public CustomNumberEditor(Class numberClass, boolean allowEmpty) throws IllegalArgumentException { + this(numberClass, null, allowEmpty); + } + + /** + * Create a new CustomNumberEditor instance, using the given NumberFormat + * for parsing and rendering. + *

    The allowEmpty parameter states if an empty String should + * be allowed for parsing, i.e. get interpreted as null value. + * Else, an IllegalArgumentException gets thrown in that case. + * @param numberClass Number subclass to generate + * @param numberFormat NumberFormat to use for parsing and rendering + * @param allowEmpty if empty strings should be allowed + * @throws IllegalArgumentException if an invalid numberClass has been specified + * @see org.springframework.util.NumberUtils#parseNumber(String, Class, java.text.NumberFormat) + * @see java.text.NumberFormat#parse + * @see java.text.NumberFormat#format + */ + public CustomNumberEditor(Class numberClass, NumberFormat numberFormat, boolean allowEmpty) + throws IllegalArgumentException { + + if (numberClass == null || !Number.class.isAssignableFrom(numberClass)) { + throw new IllegalArgumentException("Property class must be a subclass of Number"); + } + this.numberClass = numberClass; + this.numberFormat = numberFormat; + this.allowEmpty = allowEmpty; + } + + + /** + * Parse the Number from the given text, using the specified NumberFormat. + */ + public void setAsText(String text) throws IllegalArgumentException { + if (this.allowEmpty && !StringUtils.hasText(text)) { + // Treat empty String as null value. + setValue(null); + } + else if (this.numberFormat != null) { + // Use given NumberFormat for parsing text. + setValue(NumberUtils.parseNumber(text, this.numberClass, this.numberFormat)); + } + else { + // Use default valueOf methods for parsing text. + setValue(NumberUtils.parseNumber(text, this.numberClass)); + } + } + + /** + * Coerce a Number value into the required target class, if necessary. + */ + public void setValue(Object value) { + if (value instanceof Number) { + super.setValue(NumberUtils.convertNumberToTargetClass((Number) value, this.numberClass)); + } + else { + super.setValue(value); + } + } + + /** + * Format the Number as String, using the specified NumberFormat. + */ + public String getAsText() { + Object value = getValue(); + if (value == null) { + return ""; + } + if (this.numberFormat != null) { + // Use NumberFormat for rendering value. + return this.numberFormat.format(value); + } + else { + // Use toString method for rendering value. + return value.toString(); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/FileEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/FileEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/FileEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,116 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; +import java.io.File; +import java.io.IOException; + +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceEditor; +import org.springframework.util.Assert; +import org.springframework.util.ResourceUtils; +import org.springframework.util.StringUtils; + +/** + * Editor for java.io.File, to directly populate a File property + * from a Spring resource location. + * + *

    Supports Spring-style URL notation: any fully qualified standard URL + * ("file:", "http:", etc) and Spring's special "classpath:" pseudo-URL. + * + *

    NOTE: The behavior of this editor has changed in Spring 2.0. + * Previously, it created a File instance directly from a filename. + * As of Spring 2.0, it takes a standard Spring resource location as input; + * this is consistent with URLEditor and InputStreamEditor now. + * + *

    NOTE: In Spring 2.5 the following modification was made. + * If a file name is specified without a URL prefix or without an absolute path + * then we try to locate the file using standard ResourceLoader semantics. + * If the file was not found, then a File instance is created assuming the file + * name refers to a relative file location. + * + * @author Juergen Hoeller + * @author Thomas Risberg + * @since 09.12.2003 + * @see java.io.File + * @see org.springframework.core.io.ResourceEditor + * @see org.springframework.core.io.ResourceLoader + * @see URLEditor + * @see InputStreamEditor + */ +public class FileEditor extends PropertyEditorSupport { + + private final ResourceEditor resourceEditor; + + + /** + * Create a new FileEditor, + * using the default ResourceEditor underneath. + */ + public FileEditor() { + this.resourceEditor = new ResourceEditor(); + } + + /** + * Create a new FileEditor, + * using the given ResourceEditor underneath. + * @param resourceEditor the ResourceEditor to use + */ + public FileEditor(ResourceEditor resourceEditor) { + Assert.notNull(resourceEditor, "ResourceEditor must not be null"); + this.resourceEditor = resourceEditor; + } + + + public void setAsText(String text) throws IllegalArgumentException { + // Check whether we got an absolute file path without "file:" prefix. + // For backwards compatibility, we'll consider those as straight file path. + if (StringUtils.hasText(text) && !ResourceUtils.isUrl(text)) { + File file = new File(text); + if (file.isAbsolute()) { + setValue(file); + return; + } + } + + // Proceed with standard resource location parsing. + this.resourceEditor.setAsText(text); + Resource resource = (Resource) this.resourceEditor.getValue(); + // Non URLs will be treated as relative paths if the resource was not found + if(ResourceUtils.isUrl(text) || resource.exists()) { + try { + setValue(resource != null ? resource.getFile() : null); + } + catch (IOException ex) { + throw new IllegalArgumentException( + "Could not retrieve File for " + resource + ": " + ex.getMessage()); + } + } + else { + // Create a relative File reference and hope for the best + File file = new File(text); + setValue(file); + } + } + + public String getAsText() { + File value = (File) getValue(); + return (value != null ? value.getPath() : ""); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/InputStreamEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/InputStreamEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/InputStreamEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; +import java.io.IOException; + +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceEditor; +import org.springframework.util.Assert; + +/** + * One-way PropertyEditor, which can convert from a text string to a + * java.io.InputStream, allowing InputStream properties + * to be set directly as a text string. + * + *

    Supports Spring-style URL notation: any fully qualified standard URL + * ("file:", "http:", etc) and Spring's special "classpath:" pseudo-URL. + * + *

    Note that in the default usage, the stream is not closed by Spring itself! + * + * @author Juergen Hoeller + * @since 1.0.1 + * @see java.io.InputStream + * @see org.springframework.core.io.ResourceEditor + * @see org.springframework.core.io.ResourceLoader + * @see URLEditor + * @see FileEditor + */ +public class InputStreamEditor extends PropertyEditorSupport { + + private final ResourceEditor resourceEditor; + + + /** + * Create a new InputStreamEditor, + * using the default ResourceEditor underneath. + */ + public InputStreamEditor() { + this.resourceEditor = new ResourceEditor(); + } + + /** + * Create a new InputStreamEditor, + * using the given ResourceEditor underneath. + * @param resourceEditor the ResourceEditor to use + */ + public InputStreamEditor(ResourceEditor resourceEditor) { + Assert.notNull(resourceEditor, "ResourceEditor must not be null"); + this.resourceEditor = resourceEditor; + } + + + public void setAsText(String text) throws IllegalArgumentException { + this.resourceEditor.setAsText(text); + Resource resource = (Resource) this.resourceEditor.getValue(); + try { + setValue(resource != null ? resource.getInputStream() : null); + } + catch (IOException ex) { + throw new IllegalArgumentException( + "Could not retrieve InputStream for " + resource + ": " + ex.getMessage()); + } + } + + /** + * This implementation returns null to indicate that + * there is no appropriate text representation. + */ + public String getAsText() { + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/LocaleEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/LocaleEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/LocaleEditor.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; + +import org.springframework.util.StringUtils; + +/** + * Editor for java.util.Locale, to directly populate a Locale property. + * + *

    Expects the same syntax as Locale's toString, i.e. language + + * optionally country + optionally variant, separated by "_" (e.g. "en", "en_US"). + * Also accepts spaces as separators, as alternative to underscores. + * + * @author Juergen Hoeller + * @since 26.05.2003 + * @see java.util.Locale + * @see org.springframework.util.StringUtils#parseLocaleString + */ +public class LocaleEditor extends PropertyEditorSupport { + + public void setAsText(String text) { + setValue(StringUtils.parseLocaleString(text)); + } + + public String getAsText() { + Object value = getValue(); + return (value != null ? value.toString() : ""); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/PatternEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/PatternEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/PatternEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; +import java.util.regex.Pattern; + +/** + * Editor for java.util.regex.Pattern, to directly populate a Pattern property. + * Expects the same syntax as Pattern's compile method. + * + * @author Juergen Hoeller + * @since 2.0.1 + * @see java.util.regex.Pattern + * @see java.util.regex.Pattern#compile(String) + */ +public class PatternEditor extends PropertyEditorSupport { + + private final int flags; + + + /** + * Create a new PatternEditor with default settings. + */ + public PatternEditor() { + this.flags = 0; + } + + /** + * Create a new PatternEditor with the given settings. + * @param flags the java.util.regex.Pattern flags to apply + * @see java.util.regex.Pattern#compile(String, int) + * @see java.util.regex.Pattern#CASE_INSENSITIVE + * @see java.util.regex.Pattern#MULTILINE + * @see java.util.regex.Pattern#DOTALL + * @see java.util.regex.Pattern#UNICODE_CASE + * @see java.util.regex.Pattern#CANON_EQ + */ + public PatternEditor(int flags) { + this.flags = flags; + } + + + public void setAsText(String text) { + setValue(text != null ? Pattern.compile(text, this.flags) : null); + } + + public String getAsText() { + Pattern value = (Pattern) getValue(); + return (value != null ? value.pattern() : ""); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/PropertiesEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/PropertiesEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/PropertiesEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.Map; +import java.util.Properties; + +/** + * Custom {@link java.beans.PropertyEditor} for {@link Properties} objects. + * + *

    Handles conversion from content {@link String} to Properties object. + * Also handles {@link Map} to Properties conversion, for populating + * a Properties object via XML "map" entries. + * + *

    The required format is defined in the standard Properties + * documentation. Each property must be on a new line. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see java.util.Properties#load + */ +public class PropertiesEditor extends PropertyEditorSupport { + + /** + * Any of these characters, if they're first after whitespace or first + * on a line, mean that the line is a comment and should be ignored. + */ + private final static String COMMENT_MARKERS = "#!"; + + + /** + * Convert {@link String} into {@link Properties}, considering it as + * properties content. + * @param text the text to be so converted + */ + public void setAsText(String text) throws IllegalArgumentException { + Properties props = new Properties(); + if (text != null) { + try { + // Must use the ISO-8859-1 encoding because Properties.load(stream) expects it. + props.load(new ByteArrayInputStream(text.getBytes("ISO-8859-1"))); + } + catch (IOException ex) { + // Should never happen. + throw new IllegalArgumentException( + "Failed to parse [" + text + "] into Properties: " + ex.getMessage()); + } + } + setValue(props); + } + + /** + * Take {@link Properties} as-is; convert {@link Map} into Properties. + */ + public void setValue(Object value) { + if (!(value instanceof Properties) && value instanceof Map) { + Properties props = new Properties(); + props.putAll((Map) value); + super.setValue(props); + } + else { + super.setValue(value); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/ResourceBundleEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/ResourceBundleEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/ResourceBundleEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,104 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +import java.beans.PropertyEditorSupport; +import java.util.Locale; +import java.util.ResourceBundle; + +/** + * {@link java.beans.PropertyEditor} implementation for + * {@link java.util.ResourceBundle ResourceBundles}. + * + *

    Only supports conversion from a String, but not + * to a String. + * + * Find below some examples of using this class in a + * (properly configured) Spring container using XML-based metadata: + * + *

     <bean id="errorDialog" class="...">
    + *    <!--
    + *        the 'messages' property is of type java.util.ResourceBundle.
    + *        the 'DialogMessages.properties' file exists at the root of the CLASSPATH
    + *    -->
    + *    <property name="messages" value="DialogMessages"/>
    + * </bean>
    + * + *
     <bean id="errorDialog" class="...">
    + *    <!--
    + *        the 'DialogMessages.properties' file exists in the 'com/messages' package
    + *    -->
    + *    <property name="messages" value="com/messages/DialogMessages"/>
    + * </bean>
    + * + *

    A 'properly configured' Spring {@link org.springframework.context.ApplicationContext container} + * might contain a {@link org.springframework.beans.factory.config.CustomEditorConfigurer} + * definition such that the conversion can be effected transparently: + * + *

     <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    + *    <property name="customEditors">
    + *        <map>
    + *            <entry key="java.util.ResourceBundle">
    + *                <bean class="org.springframework.beans.propertyeditors.ResourceBundleEditor"/>
    + *            </entry>
    + *        </map>
    + *    </property>
    + * </bean>
    + * + *

    Please note that this {@link java.beans.PropertyEditor} is + * not registered by default with any of the Spring infrastructure. + * + *

    Thanks to David Leal Valmana for the suggestion and initial prototype. + * + * @author Rick Evans + * @since 2.0 + */ +public class ResourceBundleEditor extends PropertyEditorSupport { + + /** + * The separator used to distinguish between the base name and the + * locale (if any) when {@link #setAsText(String) converting from a String}. + */ + public static final String BASE_NAME_SEPARATOR = "_"; + + + public void setAsText(String text) throws IllegalArgumentException { + Assert.hasText(text, "'text' must not be empty"); + ResourceBundle bundle; + String rawBaseName = text.trim(); + int indexOfBaseNameSeparator = rawBaseName.indexOf(BASE_NAME_SEPARATOR); + if (indexOfBaseNameSeparator == -1) { + bundle = ResourceBundle.getBundle(rawBaseName); + } else { + // it potentially has locale information + String baseName = rawBaseName.substring(0, indexOfBaseNameSeparator); + if (!StringUtils.hasText(baseName)) { + throw new IllegalArgumentException("Bad ResourceBundle name : received '" + text + "' as argument to 'setAsText(String value)'."); + } + String localeString = rawBaseName.substring(indexOfBaseNameSeparator + 1); + Locale locale = StringUtils.parseLocaleString(localeString); + bundle = (StringUtils.hasText(localeString)) + ? ResourceBundle.getBundle(baseName, locale) + : ResourceBundle.getBundle(baseName); + } + setValue(bundle); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/StringArrayPropertyEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/StringArrayPropertyEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/StringArrayPropertyEditor.java 17 Aug 2012 15:11:43 -0000 1.1 @@ -0,0 +1,107 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; + +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +/** + * Custom {@link java.beans.PropertyEditor} for String arrays. + * + *

    Strings must be in CSV format, with a customizable separator. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see org.springframework.util.StringUtils#delimitedListToStringArray + * @see org.springframework.util.StringUtils#arrayToDelimitedString + */ +public class StringArrayPropertyEditor extends PropertyEditorSupport { + + /** + * Default separator for splitting a String: a comma (",") + */ + public static final String DEFAULT_SEPARATOR = ","; + + + private final String separator; + + private final String charsToDelete; + + private final boolean emptyArrayAsNull; + + + /** + * Create a new StringArrayPropertyEditor with the default separator + * (a comma). + *

    An empty text (without elements) will be turned into an empty array. + */ + public StringArrayPropertyEditor() { + this(DEFAULT_SEPARATOR, null, false); + } + + /** + * Create a new StringArrayPropertyEditor with the given separator. + *

    An empty text (without elements) will be turned into an empty array. + * @param separator the separator to use for splitting a {@link String} + */ + public StringArrayPropertyEditor(String separator) { + this(separator, null, false); + } + + /** + * Create a new StringArrayPropertyEditor with the given separator. + * @param separator the separator to use for splitting a {@link String} + * @param emptyArrayAsNull true if an empty String array + * is to be transformed into null + */ + public StringArrayPropertyEditor(String separator, boolean emptyArrayAsNull) { + this(separator, null, emptyArrayAsNull); + } + + /** + * Create a new StringArrayPropertyEditor with the given separator. + * @param separator the separator to use for splitting a {@link String} + * @param charsToDelete a set of characters to delete, in addition to + * trimming an input String. Useful for deleting unwanted line breaks: + * e.g. "\r\n\f" will delete all new lines and line feeds in a String. + * @param emptyArrayAsNull true if an empty String array + * is to be transformed into null + */ + public StringArrayPropertyEditor(String separator, String charsToDelete, boolean emptyArrayAsNull) { + this.separator = separator; + this.charsToDelete = charsToDelete; + this.emptyArrayAsNull = emptyArrayAsNull; + } + + + public void setAsText(String text) throws IllegalArgumentException { + String[] array = StringUtils.delimitedListToStringArray(text, this.separator, this.charsToDelete); + if (this.emptyArrayAsNull && array.length == 0) { + setValue(null); + } + else { + setValue(array); + } + } + + public String getAsText() { + return StringUtils.arrayToDelimitedString(ObjectUtils.toObjectArray(getValue()), this.separator); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/StringTrimmerEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/StringTrimmerEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/StringTrimmerEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; + +import org.springframework.util.StringUtils; + +/** + * Property editor that trims Strings. + * + *

    Optionally allows transforming an empty string into a null value. + * Needs to be explictly registered, e.g. for command binding. + * + * @author Juergen Hoeller + * @see org.springframework.validation.DataBinder#registerCustomEditor + * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder + */ +public class StringTrimmerEditor extends PropertyEditorSupport { + + private final String charsToDelete; + + private final boolean emptyAsNull; + + + /** + * Create a new StringTrimmerEditor. + * @param emptyAsNull true if an empty String is to be + * transformed into null + */ + public StringTrimmerEditor(boolean emptyAsNull) { + this.charsToDelete = null; + this.emptyAsNull = emptyAsNull; + } + + /** + * Create a new StringTrimmerEditor. + * @param charsToDelete a set of characters to delete, in addition to + * trimming an input String. Useful for deleting unwanted line breaks: + * e.g. "\r\n\f" will delete all new lines and line feeds in a String. + * @param emptyAsNull true if an empty String is to be + * transformed into null + */ + public StringTrimmerEditor(String charsToDelete, boolean emptyAsNull) { + this.charsToDelete = charsToDelete; + this.emptyAsNull = emptyAsNull; + } + + + public void setAsText(String text) { + if (text == null) { + setValue(null); + } + else { + String value = text.trim(); + if (this.charsToDelete != null) { + value = StringUtils.deleteAny(value, this.charsToDelete); + } + if (this.emptyAsNull && "".equals(value)) { + setValue(null); + } + else { + setValue(value); + } + } + } + + public String getAsText() { + Object value = getValue(); + return (value != null ? value.toString() : ""); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/URIEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/URIEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/URIEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,119 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.util.ClassUtils; +import org.springframework.util.ResourceUtils; +import org.springframework.util.StringUtils; + +/** + * Editor for java.net.URI, to directly populate a URI property + * instead of using a String property as bridge. + * + *

    Supports Spring-style URI notation: any fully qualified standard URI + * ("file:", "http:", etc) and Spring's special "classpath:" pseudo-URL, + * which will be resolved to a corresponding URI. + * + *

    Note: A URI is more relaxed than a URL in that it does not require + * a valid protocol to be specified. Any scheme within a valid URI syntax + * is allowed, even without a matching protocol handler being registered. + * + * @author Juergen Hoeller + * @since 2.0.2 + * @see java.net.URI + * @see URLEditor + */ +public class URIEditor extends PropertyEditorSupport { + + private final ClassLoader classLoader; + + + /** + * Create a new URIEditor, converting "classpath:" locations into + * standard URIs (not trying to resolve them into physical resources). + */ + public URIEditor() { + this.classLoader = null; + } + + /** + * Create a new URIEditor, using the given ClassLoader to resolve + * "classpath:" locations into physical resource URLs. + * @param classLoader the ClassLoader to use for resolving "classpath:" locations + * (may be null to indicate the default ClassLoader) + */ + public URIEditor(ClassLoader classLoader) { + this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); + } + + + public void setAsText(String text) throws IllegalArgumentException { + if (StringUtils.hasText(text)) { + String uri = text.trim(); + if (this.classLoader != null && uri.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { + ClassPathResource resource = + new ClassPathResource(uri.substring(ResourceUtils.CLASSPATH_URL_PREFIX.length()), this.classLoader); + try { + String url = resource.getURL().toString(); + setValue(createURI(url)); + } + catch (IOException ex) { + throw new IllegalArgumentException("Could not retrieve URI for " + resource + ": " + ex.getMessage()); + } + catch (URISyntaxException ex) { + throw new IllegalArgumentException("Invalid URI syntax: " + ex); + } + } + else { + try { + setValue(createURI(uri)); + } + catch (URISyntaxException ex) { + throw new IllegalArgumentException("Invalid URI syntax: " + ex); + } + } + } + else { + setValue(null); + } + } + + /** + * Create a URI instance for the given (resolved) String value. + *

    The default implementation uses the URI(String) + * constructor, replacing spaces with "%20" quotes first. + * @param value the value to convert into a URI instance + * @return the URI instance + * @throws URISyntaxException if URI conversion failed + */ + protected URI createURI(String value) throws URISyntaxException { + return new URI(StringUtils.replace(value, " ", "%20")); + } + + + public String getAsText() { + URI value = (URI) getValue(); + return (value != null ? value.toString() : ""); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/URLEditor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/URLEditor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/URLEditor.java 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,85 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.propertyeditors; + +import java.beans.PropertyEditorSupport; +import java.io.IOException; +import java.net.URL; + +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceEditor; +import org.springframework.util.Assert; + +/** + * Editor for java.net.URL, to directly populate a URL property + * instead of using a String property as bridge. + * + *

    Supports Spring-style URL notation: any fully qualified standard URL + * ("file:", "http:", etc) and Spring's special "classpath:" pseudo-URL, + * as well as Spring's context-specific relative file paths. + * + *

    Note: A URL must specify a valid protocol, else it will be rejected + * upfront. However, the target resource does not necessarily have to exist + * at the time of URL creation; this depends on the specific resource type. + * + * @author Juergen Hoeller + * @since 15.12.2003 + * @see java.net.URL + * @see org.springframework.core.io.ResourceEditor + * @see org.springframework.core.io.ResourceLoader + * @see FileEditor + * @see InputStreamEditor + */ +public class URLEditor extends PropertyEditorSupport { + + private final ResourceEditor resourceEditor; + + + /** + * Create a new URLEditor, using the default ResourceEditor underneath. + */ + public URLEditor() { + this.resourceEditor = new ResourceEditor(); + } + + /** + * Create a new URLEditor, using the given ResourceEditor underneath. + * @param resourceEditor the ResourceEditor to use + */ + public URLEditor(ResourceEditor resourceEditor) { + Assert.notNull(resourceEditor, "ResourceEditor must not be null"); + this.resourceEditor = resourceEditor; + } + + + public void setAsText(String text) throws IllegalArgumentException { + this.resourceEditor.setAsText(text); + Resource resource = (Resource) this.resourceEditor.getValue(); + try { + setValue(resource != null ? resource.getURL() : null); + } + catch (IOException ex) { + throw new IllegalArgumentException("Could not retrieve URL for " + resource + ": " + ex.getMessage()); + } + } + + public String getAsText() { + URL value = (URL) getValue(); + return (value != null ? value.toExternalForm() : ""); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/propertyeditors/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/propertyeditors/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/propertyeditors/package.html 17 Aug 2012 15:11:44 -0000 1.1 @@ -0,0 +1,12 @@ + + + +Properties editors used to convert from String values to object +types such as java.util.Properties. + +

    Some of these editors are registered automatically by BeanWrapperImpl. +"CustomXxxEditor" classes are intended for manual registration in +specific binding processes, as they are localized or the like. + + + Index: 3rdParty_sources/spring/org/springframework/beans/support/ArgumentConvertingMethodInvoker.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/support/ArgumentConvertingMethodInvoker.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/support/ArgumentConvertingMethodInvoker.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,178 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.support; + +import java.beans.PropertyEditor; +import java.lang.reflect.Method; + +import org.springframework.beans.PropertyEditorRegistry; +import org.springframework.beans.SimpleTypeConverter; +import org.springframework.beans.TypeConverter; +import org.springframework.beans.TypeMismatchException; +import org.springframework.util.MethodInvoker; +import org.springframework.util.ReflectionUtils; + +/** + * Subclass of {@link MethodInvoker} that tries to convert the given + * arguments for the actual target method via a {@link TypeConverter}. + * + *

    Supports flexible argument conversions, in particular for + * invoking a specific overloaded method. + * + * @author Juergen Hoeller + * @since 1.1 + * @see org.springframework.beans.BeanWrapperImpl#convertIfNecessary + */ +public class ArgumentConvertingMethodInvoker extends MethodInvoker { + + private TypeConverter typeConverter; + + private boolean useDefaultConverter = true; + + + /** + * Set a TypeConverter to use for argument type conversion. + *

    Default is a {@link org.springframework.beans.SimpleTypeConverter}. + * Can be overridden with any TypeConverter implementation, typically + * a pre-configured SimpleTypeConverter or a BeanWrapperImpl instance. + * @see org.springframework.beans.SimpleTypeConverter + * @see org.springframework.beans.BeanWrapperImpl + */ + public void setTypeConverter(TypeConverter typeConverter) { + this.typeConverter = typeConverter; + this.useDefaultConverter = false; + } + + /** + * Return the TypeConverter used for argument type conversion. + *

    Can be cast to {@link org.springframework.beans.PropertyEditorRegistry} + * if direct access to the underlying PropertyEditors is desired + * (provided that the present TypeConverter actually implements the + * PropertyEditorRegistry interface). + */ + public TypeConverter getTypeConverter() { + if (this.typeConverter == null && this.useDefaultConverter) { + this.typeConverter = getDefaultTypeConverter(); + } + return this.typeConverter; + } + + /** + * Obtain the default TypeConverter for this method invoker. + *

    Called if no explicit TypeConverter has been specified. + * The default implementation builds a + * {@link org.springframework.beans.SimpleTypeConverter}. + * Can be overridden in subclasses. + */ + protected TypeConverter getDefaultTypeConverter() { + return new SimpleTypeConverter(); + } + + /** + * Register the given custom property editor for all properties of the given type. + *

    Typically used in conjunction with the default + * {@link org.springframework.beans.SimpleTypeConverter}; will work with any + * TypeConverter that implements the PropertyEditorRegistry interface as well. + * @param requiredType type of the property + * @param propertyEditor editor to register + * @see #setTypeConverter + * @see org.springframework.beans.PropertyEditorRegistry#registerCustomEditor + */ + public void registerCustomEditor(Class requiredType, PropertyEditor propertyEditor) { + TypeConverter converter = getTypeConverter(); + if (!(converter instanceof PropertyEditorRegistry)) { + throw new IllegalStateException( + "TypeConverter does not implement PropertyEditorRegistry interface: " + converter); + } + ((PropertyEditorRegistry) converter).registerCustomEditor(requiredType, propertyEditor); + } + + + /** + * This implementation looks for a method with matching parameter types. + * @see #doFindMatchingMethod + */ + protected Method findMatchingMethod() { + Method matchingMethod = super.findMatchingMethod(); + // Second pass: look for method where arguments can be converted to parameter types. + if (matchingMethod == null) { + // Interpret argument array as individual method arguments. + matchingMethod = doFindMatchingMethod(getArguments()); + } + if (matchingMethod == null) { + // Interpret argument array as single method argument of array type. + matchingMethod = doFindMatchingMethod(new Object[] {getArguments()}); + } + return matchingMethod; + } + + /** + * Actually find a method with matching parameter type, i.e. where each + * argument value is assignable to the corresponding parameter type. + * @param arguments the argument values to match against method parameters + * @return a matching method, or null if none + */ + protected Method doFindMatchingMethod(Object[] arguments) { + TypeConverter converter = getTypeConverter(); + if (converter != null) { + String targetMethod = getTargetMethod(); + Method matchingMethod = null; + int argCount = arguments.length; + Method[] candidates = ReflectionUtils.getAllDeclaredMethods(getTargetClass()); + int minTypeDiffWeight = Integer.MAX_VALUE; + Object[] argumentsToUse = null; + + for (int i = 0; i < candidates.length; i++) { + Method candidate = candidates[i]; + if (candidate.getName().equals(targetMethod)) { + // Check if the inspected method has the correct number of parameters. + Class[] paramTypes = candidate.getParameterTypes(); + if (paramTypes.length == argCount) { + Object[] convertedArguments = new Object[argCount]; + boolean match = true; + for (int j = 0; j < argCount && match; j++) { + // Verify that the supplied argument is assignable to the method parameter. + try { + convertedArguments[j] = converter.convertIfNecessary(arguments[j], paramTypes[j]); + } + catch (TypeMismatchException ex) { + // Ignore -> simply doesn't match. + match = false; + } + } + if (match) { + int typeDiffWeight = getTypeDifferenceWeight(paramTypes, convertedArguments); + if (typeDiffWeight < minTypeDiffWeight) { + minTypeDiffWeight = typeDiffWeight; + matchingMethod = candidate; + argumentsToUse = convertedArguments; + } + } + } + } + } + + if (matchingMethod != null) { + setArguments(argumentsToUse); + return matchingMethod; + } + } + + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/support/MutableSortDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/support/MutableSortDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/support/MutableSortDefinition.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,171 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.support; + +import java.io.Serializable; + +import org.springframework.util.StringUtils; + +/** + * Mutable implementation of the {@link SortDefinition} interface. + * Supports toggling the ascending value on setting the same property again. + * + * @author Juergen Hoeller + * @author Jean-Pierre Pawlak + * @since 26.05.2003 + * @see #setToggleAscendingOnProperty + */ +public class MutableSortDefinition implements SortDefinition, Serializable { + + private String property = ""; + + private boolean ignoreCase = true; + + private boolean ascending = true; + + private boolean toggleAscendingOnProperty = false; + + + /** + * Create an empty MutableSortDefinition, + * to be populated via its bean properties. + * @see #setProperty + * @see #setIgnoreCase + * @see #setAscending + */ + public MutableSortDefinition() { + } + + /** + * Copy constructor: create a new MutableSortDefinition + * that mirrors the given sort definition. + * @param source the original sort definition + */ + public MutableSortDefinition(SortDefinition source) { + this.property = source.getProperty(); + this.ignoreCase = source.isIgnoreCase(); + this.ascending = source.isAscending(); + } + + /** + * Create a MutableSortDefinition for the given settings. + * @param property the property to compare + * @param ignoreCase whether upper and lower case in String values should be ignored + * @param ascending whether to sort ascending (true) or descending (false) + */ + public MutableSortDefinition(String property, boolean ignoreCase, boolean ascending) { + this.property = property; + this.ignoreCase = ignoreCase; + this.ascending = ascending; + } + + /** + * Create a new MutableSortDefinition. + * @param toggleAscendingOnSameProperty whether to toggle the ascending flag + * if the same property gets set again (that is, setProperty gets + * called with already set property name again). + */ + public MutableSortDefinition(boolean toggleAscendingOnSameProperty) { + this.toggleAscendingOnProperty = toggleAscendingOnSameProperty; + } + + + /** + * Set the property to compare. + *

    If the property was the same as the current, the sort is reversed if + * "toggleAscendingOnProperty" is activated, else simply ignored. + * @see #setToggleAscendingOnProperty + */ + public void setProperty(String property) { + if (!StringUtils.hasLength(property)) { + this.property = ""; + } + else { + // Implicit toggling of ascending? + if (isToggleAscendingOnProperty()) { + this.ascending = (!property.equals(this.property) || !this.ascending); + } + this.property = property; + } + } + + public String getProperty() { + return this.property; + } + + /** + * Set whether upper and lower case in String values should be ignored. + */ + public void setIgnoreCase(boolean ignoreCase) { + this.ignoreCase = ignoreCase; + } + + public boolean isIgnoreCase() { + return this.ignoreCase; + } + + /** + * Set whether to sort ascending (true) or descending (false). + */ + public void setAscending(boolean ascending) { + this.ascending = ascending; + } + + public boolean isAscending() { + return this.ascending; + } + + /** + * Set whether to toggle the ascending flag if the same property gets set again + * (that is, {@link #setProperty} gets called with already set property name again). + *

    This is particularly useful for parameter binding through a web request, + * where clicking on the field header again might be supposed to trigger a + * resort for the same field but opposite order. + */ + public void setToggleAscendingOnProperty(boolean toggleAscendingOnProperty) { + this.toggleAscendingOnProperty = toggleAscendingOnProperty; + } + + /** + * Return whether to toggle the ascending flag if the same property gets set again + * (that is, {@link #setProperty} gets called with already set property name again). + */ + public boolean isToggleAscendingOnProperty() { + return this.toggleAscendingOnProperty; + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof SortDefinition)) { + return false; + } + SortDefinition otherSd = (SortDefinition) other; + return (getProperty().equals(otherSd.getProperty()) && + isAscending() == otherSd.isAscending() && isIgnoreCase() == otherSd.isIgnoreCase()); + } + + public int hashCode() { + int hashCode = getProperty().hashCode(); + hashCode = 29 * hashCode + (isIgnoreCase() ? 1 : 0); + hashCode = 29 * hashCode + (isAscending() ? 1 : 0); + return hashCode; + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/support/PagedListHolder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/support/PagedListHolder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/support/PagedListHolder.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,332 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.support; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.springframework.util.Assert; + +/** + * PagedListHolder is a simple state holder for handling lists of objects, + * separating them into pages. Page numbering starts with 0. + * + *

    This is mainly targetted at usage in web UIs. Typically, an instance will be + * instantiated with a list of beans, put into the session, and exported as model. + * The properties can all be set/get programmatically, but the most common way will + * be data binding, i.e. populating the bean from request parameters. The getters + * will mainly be used by the view. + * + *

    Supports sorting the underlying list via a {@link SortDefinition} implementation, + * available as property "sort". By default, a {@link MutableSortDefinition} instance + * will be used, toggling the ascending value on setting the same property again. + * + *

    The data binding names have to be called "pageSize" and "sort.ascending", + * as expected by BeanWrapper. Note that the names and the nesting syntax match + * the respective JSTL EL expressions, like "myModelAttr.pageSize" and + * "myModelAttr.sort.ascending". + * + * @author Juergen Hoeller + * @since 19.05.2003 + * @see #getPageList() + * @see org.springframework.beans.support.MutableSortDefinition + */ +public class PagedListHolder implements Serializable { + + public static final int DEFAULT_PAGE_SIZE = 10; + + public static final int DEFAULT_MAX_LINKED_PAGES = 10; + + + private List source; + + private Date refreshDate; + + private SortDefinition sort; + + private SortDefinition sortUsed; + + private int pageSize = DEFAULT_PAGE_SIZE; + + private int page = 0; + + private boolean newPageSet; + + private int maxLinkedPages = DEFAULT_MAX_LINKED_PAGES; + + + /** + * Create a new holder instance. + * You'll need to set a source list to be able to use the holder. + * @see #setSource + */ + public PagedListHolder() { + this(new ArrayList(0)); + } + + /** + * Create a new holder instance with the given source list, starting with + * a default sort definition (with "toggleAscendingOnProperty" activated). + * @param source the source List + * @see MutableSortDefinition#setToggleAscendingOnProperty + */ + public PagedListHolder(List source) { + this(source, new MutableSortDefinition(true)); + } + + /** + * Create a new holder instance with the given source list. + * @param source the source List + * @param sort the SortDefinition to start with + */ + public PagedListHolder(List source, SortDefinition sort) { + setSource(source); + setSort(sort); + } + + + /** + * Set the source list for this holder. + */ + public void setSource(List source) { + Assert.notNull(source, "Source List must not be null"); + this.source = source; + this.refreshDate = new Date(); + this.sortUsed = null; + } + + /** + * Return the source list for this holder. + */ + public List getSource() { + return this.source; + } + + /** + * Return the last time the list has been fetched from the source provider. + */ + public Date getRefreshDate() { + return this.refreshDate; + } + + /** + * Set the sort definition for this holder. + * Typically an instance of MutableSortDefinition. + * @see org.springframework.beans.support.MutableSortDefinition + */ + public void setSort(SortDefinition sort) { + this.sort = sort; + } + + /** + * Return the sort definition for this holder. + */ + public SortDefinition getSort() { + return this.sort; + } + + /** + * Set the current page size. + * Resets the current page number if changed. + *

    Default value is 10. + */ + public void setPageSize(int pageSize) { + if (pageSize != this.pageSize) { + this.pageSize = pageSize; + if (!this.newPageSet) { + this.page = 0; + } + } + } + + /** + * Return the current page size. + */ + public int getPageSize() { + return this.pageSize; + } + + /** + * Set the current page number. + * Page numbering starts with 0. + */ + public void setPage(int page) { + this.page = page; + this.newPageSet = true; + } + + /** + * Return the current page number. + * Page numbering starts with 0. + */ + public int getPage() { + this.newPageSet = false; + if (this.page >= getPageCount()) { + this.page = getPageCount() - 1; + } + return this.page; + } + + /** + * Set the maximum number of page links to a few pages around the current one. + */ + public void setMaxLinkedPages(int maxLinkedPages) { + this.maxLinkedPages = maxLinkedPages; + } + + /** + * Return the maximum number of page links to a few pages around the current one. + */ + public int getMaxLinkedPages() { + return this.maxLinkedPages; + } + + + /** + * Return the number of pages for the current source list. + */ + public int getPageCount() { + float nrOfPages = (float) getNrOfElements() / getPageSize(); + return (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages); + } + + /** + * Return if the current page is the first one. + */ + public boolean isFirstPage() { + return getPage() == 0; + } + + /** + * Return if the current page is the last one. + */ + public boolean isLastPage() { + return getPage() == getPageCount() -1; + } + + /** + * Switch to previous page. + * Will stay on first page if already on first page. + */ + public void previousPage() { + if (!isFirstPage()) { + this.page--; + } + } + + /** + * Switch to next page. + * Will stay on last page if already on last page. + */ + public void nextPage() { + if (!isLastPage()) { + this.page++; + } + } + + /** + * Return the total number of elements in the source list. + */ + public int getNrOfElements() { + return getSource().size(); + } + + /** + * Return the element index of the first element on the current page. + * Element numbering starts with 0. + */ + public int getFirstElementOnPage() { + return (getPageSize() * getPage()); + } + + /** + * Return the element index of the last element on the current page. + * Element numbering starts with 0. + */ + public int getLastElementOnPage() { + int endIndex = getPageSize() * (getPage() + 1); + int size = getNrOfElements(); + return (endIndex > size ? size : endIndex) - 1; + } + + /** + * Return a sub-list representing the current page. + */ + public List getPageList() { + return getSource().subList(getFirstElementOnPage(), getLastElementOnPage() + 1); + } + + /** + * Return the first page to which create a link around the current page. + */ + public int getFirstLinkedPage() { + return Math.max(0, getPage() - (getMaxLinkedPages() / 2)); + } + + /** + * Return the last page to which create a link around the current page. + */ + public int getLastLinkedPage() { + return Math.min(getFirstLinkedPage() + getMaxLinkedPages() - 1, getPageCount() - 1); + } + + + /** + * Resort the list if necessary, i.e. if the current sort instance + * isn't equal to the backed-up sortUsed instance. + *

    Calls doSort to trigger actual sorting. + * @see #doSort + */ + public void resort() { + SortDefinition sort = getSort(); + if (sort != null && !sort.equals(this.sortUsed)) { + this.sortUsed = copySortDefinition(sort); + doSort(getSource(), sort); + setPage(0); + } + } + + /** + * Create a deep copy of the given sort definition, + * for use as state holder to compare a modified sort definition against. + *

    Default implementation creates a MutableSortDefinition instance. + * Can be overridden in subclasses, in particular in case of custom + * extensions to the SortDefinition interface. Is allowed to return + * null, which means that no sort state will be held, triggering + * actual sorting for each resort call. + * @param sort the current SortDefinition object + * @return a deep copy of the SortDefinition object + * @see MutableSortDefinition#MutableSortDefinition(SortDefinition) + */ + protected SortDefinition copySortDefinition(SortDefinition sort) { + return new MutableSortDefinition(sort); + } + + /** + * Actually perform sorting of the given source list, according to + * the given sort definition. + *

    The default implementation uses Spring's PropertyComparator. + * Can be overridden in subclasses. + * @see PropertyComparator#sort(java.util.List, SortDefinition) + */ + protected void doSort(List source, SortDefinition sort) { + PropertyComparator.sort(source, sort); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/support/PagedListSourceProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/support/PagedListSourceProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/support/PagedListSourceProvider.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.support; + +import java.util.List; +import java.util.Locale; + +/** + * Callback that provides the source for a reloadable List. + * Used by {@link RefreshablePagedListHolder}. + * + * @author Jean-Pierre Pawlak + * @author Juergen Hoeller + * @deprecated as of Spring 2.5, to be removed in Spring 3.0 + * @see org.springframework.beans.support.RefreshablePagedListHolder#setSourceProvider + */ +public interface PagedListSourceProvider { + + /** + * Load the List for the given Locale and filter settings. + * The filter object can be of any custom class, preferably a bean + * for easy data binding from a request. An instance will simply + * get passed through to this callback method. + * @param locale Locale that the List should be loaded for, + * or null if not locale-specific + * @param filter object representing filter settings, + * or null if no filter options are used + * @return the loaded List + * @see org.springframework.beans.support.RefreshablePagedListHolder#setLocale + * @see org.springframework.beans.support.RefreshablePagedListHolder#setFilter + */ + List loadList(Locale locale, Object filter); + +} Index: 3rdParty_sources/spring/org/springframework/beans/support/PropertyComparator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/support/PropertyComparator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/support/PropertyComparator.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,152 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.support; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.BeanWrapperImpl; +import org.springframework.beans.BeansException; +import org.springframework.util.StringUtils; + +/** + * PropertyComparator performs a comparison of two beans, + * evaluating the specified bean property via a BeanWrapper. + * + * @author Juergen Hoeller + * @author Jean-Pierre Pawlak + * @since 19.05.2003 + * @see org.springframework.beans.BeanWrapper + */ +public class PropertyComparator implements Comparator { + + protected final Log logger = LogFactory.getLog(getClass()); + + private final SortDefinition sortDefinition; + + private final BeanWrapperImpl beanWrapper = new BeanWrapperImpl(false); + + + /** + * Create a new PropertyComparator for the given SortDefinition. + * @see MutableSortDefinition + */ + public PropertyComparator(SortDefinition sortDefinition) { + this.sortDefinition = sortDefinition; + } + + /** + * Create a PropertyComparator for the given settings. + * @param property the property to compare + * @param ignoreCase whether upper and lower case in String values should be ignored + * @param ascending whether to sort ascending (true) or descending (false) + */ + public PropertyComparator(String property, boolean ignoreCase, boolean ascending) { + this.sortDefinition = new MutableSortDefinition(property, ignoreCase, ascending); + } + + /** + * Return the SortDefinition that this comparator uses. + */ + public final SortDefinition getSortDefinition() { + return this.sortDefinition; + } + + + public int compare(Object o1, Object o2) { + Object v1 = getPropertyValue(o1); + Object v2 = getPropertyValue(o2); + if (this.sortDefinition.isIgnoreCase() && (v1 instanceof String) && (v2 instanceof String)) { + v1 = ((String) v1).toLowerCase(); + v2 = ((String) v2).toLowerCase(); + } + + int result; + + // Put an object with null property at the end of the sort result. + try { + if (v1 != null) { + result = (v2 != null ? ((Comparable) v1).compareTo(v2) : -1); + } + else { + result = (v2 != null ? 1 : 0); + } + } + catch (RuntimeException ex) { + if (logger.isWarnEnabled()) { + logger.warn("Could not sort objects [" + o1 + "] and [" + o2 + "]", ex); + } + return 0; + } + + return (this.sortDefinition.isAscending() ? result : -result); + } + + /** + * Get the SortDefinition's property value for the given object. + * @param obj the object to get the property value for + * @return the property value + */ + private Object getPropertyValue(Object obj) { + // If a nested property cannot be read, simply return null + // (similar to JSTL EL). If the property doesn't exist in the + // first place, let the exception through. + try { + this.beanWrapper.setWrappedInstance(obj); + return this.beanWrapper.getPropertyValue(this.sortDefinition.getProperty()); + } + catch (BeansException ex) { + logger.info("PropertyComparator could not access property - treating as null for sorting", ex); + return null; + } + } + + + /** + * Sort the given List according to the given sort definition. + *

    Note: Contained objects have to provide the given property + * in the form of a bean property, i.e. a getXXX method. + * @param source the input List + * @param sortDefinition the parameters to sort by + * @throws java.lang.IllegalArgumentException in case of a missing propertyName + */ + public static void sort(List source, SortDefinition sortDefinition) throws BeansException { + if (StringUtils.hasText(sortDefinition.getProperty())) { + Collections.sort(source, new PropertyComparator(sortDefinition)); + } + } + + /** + * Sort the given source according to the given sort definition. + *

    Note: Contained objects have to provide the given property + * in the form of a bean property, i.e. a getXXX method. + * @param source input source + * @param sortDefinition the parameters to sort by + * @throws java.lang.IllegalArgumentException in case of a missing propertyName + */ + public static void sort(Object[] source, SortDefinition sortDefinition) throws BeansException { + if (StringUtils.hasText(sortDefinition.getProperty())) { + Arrays.sort(source, new PropertyComparator(sortDefinition)); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/support/RefreshablePagedListHolder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/support/RefreshablePagedListHolder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/support/RefreshablePagedListHolder.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,180 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.support; + +import java.util.Locale; + +import org.springframework.beans.BeanUtils; + +/** + * RefreshablePagedListHolder is a PagedListHolder subclass with reloading capabilities. + * It automatically re-requests the List from the source provider, in case of Locale or + * filter changes. + * + *

    Data binding works just like with PagedListHolder. The locale can be specified in + * Locale's toString syntax, e.g. "locale=en_US". The filter object can be of any + * custom class, preferably a bean for easy data binding from a request. An instance + * will simply get passed through to PagedListSourceProvider.loadList. + * A filter property can be specified via "filter.myFilterProperty", for example. + * + *

    The scenario in the controller could be: + * + * RefreshablePagedListHolder holder = request.getSession("mySessionAttr");
    + * if (holder == null) {
    + * holder = new RefreshablePagedListHolder();
    + * holder.setSourceProvider(new MyAnonymousOrEmbeddedSourceProvider());
    + * holder.setFilter(new MyAnonymousOrEmbeddedFilter());
    + * request.getSession().setAttribute("mySessionAttr", holder);
    + * }
    + * holder.refresh(false); + * BindException ex = BindUtils.bind(request, listHolder, "myModelAttr");
    + * return ModelAndView("myViewName", ex.getModel());
    + *
    + * ...
    + *
    + * private class MyAnonymousOrEmbeddedSourceProvider implements PagedListSourceProvider {
    + * public List loadList(Locale locale, Object filter) {
    + * MyAnonymousOrEmbeddedFilter filter = (MyAnonymousOrEmbeddedFilter) filter; + * }
    + *
    + * private class MyAnonymousOrEmbeddedFilter {
    + * private String name = "";
    + * public String getName() {
    + * return name; + * public void setName(String name) {
    + * this.name = name;
    + * }
    + * }
    + *
    + * + * @author Jean-Pierre Pawlak + * @author Juergen Hoeller + * @since 24.05.2003 + * @deprecated as of Spring 2.5, to be removed in Spring 3.0 + * @see org.springframework.beans.support.PagedListSourceProvider + * @see org.springframework.beans.propertyeditors.LocaleEditor + */ +public class RefreshablePagedListHolder extends PagedListHolder { + + private PagedListSourceProvider sourceProvider; + + private Locale locale; + + private Locale localeUsed; + + private Object filter; + + private Object filterUsed; + + + /** + * Create a new list holder. + * You'll need to set a source provider to be able to use the holder. + * @see #setSourceProvider + */ + public RefreshablePagedListHolder() { + super(); + } + + /** + * Create a new list holder with the given source provider. + */ + public RefreshablePagedListHolder(PagedListSourceProvider sourceProvider) { + super(); + this.sourceProvider = sourceProvider; + } + + + /** + * Set the callback class for reloading the List when necessary. + * If the list is definitely not modifiable, i.e. not locale aware + * and no filtering, use PagedListHolder. + * @see org.springframework.beans.support.PagedListHolder + */ + public void setSourceProvider(PagedListSourceProvider sourceProvider) { + this.sourceProvider = sourceProvider; + } + + /** + * Return the callback class for reloading the List when necessary. + */ + public PagedListSourceProvider getSourceProvider() { + return this.sourceProvider; + } + + /** + * Set the Locale that the source provider should use for loading the list. + * This can either be populated programmatically (e.g. with the request locale), + * or via binding (using Locale's toString syntax, e.g. "locale=en_US"). + * @param locale the current Locale, or null + */ + public void setLocale(Locale locale) { + this.locale = locale; + } + + /** + * Return the Locale that the source provider should use for loading the list. + * @return the current Locale, or null + */ + public Locale getLocale() { + return this.locale; + } + + /** + * Set the filter object that the source provider should use for loading the list. + * This will typically be a bean, for easy data binding. + * @param filter the filter object, or null + */ + public void setFilter(Object filter) { + this.filter = filter; + } + + /** + * Return the filter that the source provider should use for loading the list. + * @return the current filter, or null + */ + public Object getFilter() { + return this.filter; + } + + + /** + * Reload the underlying list from the source provider if necessary + * (i.e. if the locale and/or the filter has changed), and resort it. + * @param force whether a reload should be performed in any case + */ + public void refresh(boolean force) { + if (this.sourceProvider != null && (force || + (this.locale != null && !this.locale.equals(this.localeUsed)) || + (this.filter != null && !this.filter.equals(this.filterUsed)))) { + setSource(this.sourceProvider.loadList(this.locale, this.filter)); + if (this.filter != null && !this.filter.equals(this.filterUsed)) { + this.setPage(0); + } + this.localeUsed = this.locale; + if (this.filter != null) { + this.filterUsed = BeanUtils.instantiateClass(this.filter.getClass()); + BeanUtils.copyProperties(this.filter, this.filterUsed); + } + } + resort(); + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/support/ResourceEditorRegistrar.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/support/ResourceEditorRegistrar.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/support/ResourceEditorRegistrar.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,95 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.support; + +import java.io.File; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; + +import org.springframework.beans.PropertyEditorRegistrar; +import org.springframework.beans.PropertyEditorRegistry; +import org.springframework.beans.propertyeditors.ClassEditor; +import org.springframework.beans.propertyeditors.FileEditor; +import org.springframework.beans.propertyeditors.InputStreamEditor; +import org.springframework.beans.propertyeditors.URIEditor; +import org.springframework.beans.propertyeditors.URLEditor; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceEditor; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.ResourceArrayPropertyEditor; +import org.springframework.core.io.support.ResourcePatternResolver; + +/** + * PropertyEditorRegistrar implementation that populates a given + * {@link org.springframework.beans.PropertyEditorRegistry} + * (typically a {@link org.springframework.beans.BeanWrapper} used for bean + * creation within an {@link org.springframework.context.ApplicationContext}) + * with resource editors. Used by + * {@link org.springframework.context.support.AbstractApplicationContext}. + * + * @author Juergen Hoeller + * @since 2.0 + */ +public class ResourceEditorRegistrar implements PropertyEditorRegistrar { + + private final ResourceLoader resourceLoader; + + + /** + * Create a new ResourceEditorRegistrar for the given ResourceLoader + * @param resourceLoader the ResourceLoader (or ResourcePatternResolver) + * to create editors for (usually an ApplicationContext) + * @see org.springframework.core.io.support.ResourcePatternResolver + * @see org.springframework.context.ApplicationContext + */ + public ResourceEditorRegistrar(ResourceLoader resourceLoader) { + this.resourceLoader = resourceLoader; + } + + + /** + * Populate the given bean factory with the following resource editors: + * ResourceEditor, InputStreamEditor, FileEditor, URLEditor, ClassEditor, URIEditor. + *

    In case of a {@link org.springframework.core.io.support.ResourcePatternResolver}, + * a ResourceArrayPropertyEditor will be registered as well. + * @see org.springframework.core.io.ResourceEditor + * @see org.springframework.beans.propertyeditors.InputStreamEditor + * @see org.springframework.beans.propertyeditors.FileEditor + * @see org.springframework.beans.propertyeditors.URLEditor + * @see org.springframework.beans.propertyeditors.ClassEditor + * @see org.springframework.beans.propertyeditors.URIEditor + * @see org.springframework.core.io.support.ResourceArrayPropertyEditor + */ + public void registerCustomEditors(PropertyEditorRegistry registry) { + ResourceEditor baseEditor = new ResourceEditor(this.resourceLoader); + registry.registerCustomEditor(Resource.class, baseEditor); + registry.registerCustomEditor(InputStream.class, new InputStreamEditor(baseEditor)); + registry.registerCustomEditor(File.class, new FileEditor(baseEditor)); + registry.registerCustomEditor(URL.class, new URLEditor(baseEditor)); + + ClassLoader classLoader = this.resourceLoader.getClassLoader(); + registry.registerCustomEditor(Class.class, new ClassEditor(classLoader)); + registry.registerCustomEditor(URI.class, new URIEditor(classLoader)); + + if (this.resourceLoader instanceof ResourcePatternResolver) { + registry.registerCustomEditor(Resource[].class, + new ResourceArrayPropertyEditor((ResourcePatternResolver) this.resourceLoader)); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/beans/support/SortDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/support/SortDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/support/SortDefinition.java 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.support; + +/** + * Definition for sorting bean instances by a property. + * + * @author Juergen Hoeller + * @since 26.05.2003 + */ +public interface SortDefinition { + + /** + * Return the name of the bean property to compare. + * Can also be a nested bean property path. + */ + String getProperty(); + + /** + * Return whether upper and lower case in String values should be ignored. + */ + boolean isIgnoreCase(); + + /** + * Return whether to sort ascending (true) or descending (false). + */ + boolean isAscending(); + +} Index: 3rdParty_sources/spring/org/springframework/beans/support/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/beans/support/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/beans/support/package.html 17 Aug 2012 15:11:47 -0000 1.1 @@ -0,0 +1,8 @@ + + + +Classes supporting the org.springframework.beans package, +such as utility classes for sorting and holding lists of beans. + + + Index: 3rdParty_sources/spring/org/springframework/cache/ehcache/EhCacheFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/cache/ehcache/EhCacheFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/cache/ehcache/EhCacheFactoryBean.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,313 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cache.ehcache; + +import java.io.IOException; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheException; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.constructs.blocking.BlockingCache; +import net.sf.ehcache.constructs.blocking.CacheEntryFactory; +import net.sf.ehcache.constructs.blocking.SelfPopulatingCache; +import net.sf.ehcache.constructs.blocking.UpdatingCacheEntryFactory; +import net.sf.ehcache.constructs.blocking.UpdatingSelfPopulatingCache; +import net.sf.ehcache.store.MemoryStoreEvictionPolicy; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.factory.BeanNameAware; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.util.Assert; + +/** + * FactoryBean that creates a named EHCache {@link net.sf.ehcache.Cache} instance + * (or a decorator that implements the {@link net.sf.ehcache.Ehcache} interface), + * representing a cache region within an EHCache {@link net.sf.ehcache.CacheManager}. + * + *

    If the specified named cache is not configured in the cache configuration descriptor, + * this FactoryBean will construct an instance of a Cache with the provided name and the + * specified cache properties and add it to the CacheManager for later retrieval. If some + * or all properties are not set at configuration time, this FactoryBean will use defaults. + * + *

    Note: If the named Cache instance is found, the properties will be ignored and the + * Cache instance will be retrieved from the CacheManager. + * + * @author Dmitriy Kopylenko + * @author Juergen Hoeller + * @since 1.1.1 + * @see #setCacheManager + * @see EhCacheManagerFactoryBean + * @see net.sf.ehcache.Cache + */ +public class EhCacheFactoryBean implements FactoryBean, BeanNameAware, InitializingBean { + + protected final Log logger = LogFactory.getLog(getClass()); + + private CacheManager cacheManager; + + private String cacheName; + + private int maxElementsInMemory = 10000; + + private int maxElementsOnDisk = 10000000; + + private MemoryStoreEvictionPolicy memoryStoreEvictionPolicy = MemoryStoreEvictionPolicy.LRU; + + private boolean overflowToDisk = true; + + private String diskStorePath; + + private boolean eternal = false; + + private int timeToLive = 120; + + private int timeToIdle = 120; + + private boolean diskPersistent = false; + + private int diskExpiryThreadIntervalSeconds = 120; + + private boolean blocking = false; + + private CacheEntryFactory cacheEntryFactory; + + private String beanName; + + private Ehcache cache; + + + /** + * Set a CacheManager from which to retrieve a named Cache instance. + * By default, CacheManager.getInstance() will be called. + *

    Note that in particular for persistent caches, it is advisable to + * properly handle the shutdown of the CacheManager: Set up a separate + * EhCacheManagerFactoryBean and pass a reference to this bean property. + *

    A separate EhCacheManagerFactoryBean is also necessary for loading + * EHCache configuration from a non-default config location. + * @see EhCacheManagerFactoryBean + * @see net.sf.ehcache.CacheManager#getInstance + */ + public void setCacheManager(CacheManager cacheManager) { + this.cacheManager = cacheManager; + } + + /** + * Set a name for which to retrieve or create a cache instance. + * Default is the bean name of this EhCacheFactoryBean. + */ + public void setCacheName(String cacheName) { + this.cacheName = cacheName; + } + + /** + * Specify the maximum number of cached objects in memory. + * Default is 10000 elements. + */ + public void setMaxElementsInMemory(int maxElementsInMemory) { + this.maxElementsInMemory = maxElementsInMemory; + } + + /** + * Specify the maximum number of cached objects on disk. + * Default is 10000000 elements. + */ + public void setMaxElementsOnDisk(int maxElementsOnDisk) { + this.maxElementsOnDisk = maxElementsOnDisk; + } + + /** + * Set the memory style eviction policy for this cache. + * Supported values are "LRU", "LFU" and "FIFO", according to the + * constants defined in EHCache's MemoryStoreEvictionPolicy class. + * Default is "LRU". + */ + public void setMemoryStoreEvictionPolicy(MemoryStoreEvictionPolicy memoryStoreEvictionPolicy) { + Assert.notNull(memoryStoreEvictionPolicy, "memoryStoreEvictionPolicy must not be null"); + this.memoryStoreEvictionPolicy = memoryStoreEvictionPolicy; + } + + /** + * Set whether elements can overflow to disk when the in-memory cache + * has reached the maximum size limit. Default is "true". + */ + public void setOverflowToDisk(boolean overflowToDisk) { + this.overflowToDisk = overflowToDisk; + } + + /** + * Set whether elements are considered as eternal. If "true", timeouts + * are ignored and the element is never expired. Default is "false". + */ + public void setEternal(boolean eternal) { + this.eternal = eternal; + } + + /** + * Set t he time in seconds to live for an element before it expires, + * i.e. the maximum time between creation time and when an element expires. + * It is only used if the element is not eternal. Default is 120 seconds. + */ + public void setTimeToLive(int timeToLive) { + this.timeToLive = timeToLive; + } + + /** + * Set the time in seconds to idle for an element before it expires, that is, + * the maximum amount of time between accesses before an element expires. + * This is only used if the element is not eternal. Default is 120 seconds. + */ + public void setTimeToIdle(int timeToIdle) { + this.timeToIdle = timeToIdle; + } + + /** + * Set whether the disk store persists between restarts of the Virtual Machine. + * The default is "false". + */ + public void setDiskPersistent(boolean diskPersistent) { + this.diskPersistent = diskPersistent; + } + + /** + * Set the number of seconds between runs of the disk expiry thread. + * The default is 120 seconds. + */ + public void setDiskExpiryThreadIntervalSeconds(int diskExpiryThreadIntervalSeconds) { + this.diskExpiryThreadIntervalSeconds = diskExpiryThreadIntervalSeconds; + } + + /** + * Set whether to use a blocking cache that lets read attempts block + * until the requested element is created. + *

    If you intend to build a self-populating blocking cache, + * consider specifying a {@link #setCacheEntryFactory CacheEntryFactory}. + * @see net.sf.ehcache.constructs.blocking.BlockingCache + * @see #setCacheEntryFactory + */ + public void setBlocking(boolean blocking) { + this.blocking = blocking; + } + + /** + * Set an EHCache {@link net.sf.ehcache.constructs.blocking.CacheEntryFactory} + * to use for a self-populating cache. If such a factory is specified, + * the cache will be decorated with EHCache's + * {@link net.sf.ehcache.constructs.blocking.SelfPopulatingCache}. + *

    The specified factory can be of type + * {@link net.sf.ehcache.constructs.blocking.UpdatingCacheEntryFactory}, + * which will lead to the use of an + * {@link net.sf.ehcache.constructs.blocking.UpdatingSelfPopulatingCache}. + *

    Note: Any such self-populating cache is automatically a blocking cache. + * @see net.sf.ehcache.constructs.blocking.SelfPopulatingCache + * @see net.sf.ehcache.constructs.blocking.UpdatingSelfPopulatingCache + * @see net.sf.ehcache.constructs.blocking.UpdatingCacheEntryFactory + */ + public void setCacheEntryFactory(CacheEntryFactory cacheEntryFactory) { + this.cacheEntryFactory = cacheEntryFactory; + } + + public void setBeanName(String name) { + this.beanName = name; + } + + + public void afterPropertiesSet() throws CacheException, IOException { + // If no CacheManager given, fetch the default. + if (this.cacheManager == null) { + if (logger.isDebugEnabled()) { + logger.debug("Using default EHCache CacheManager for cache region '" + this.cacheName + "'"); + } + this.cacheManager = CacheManager.getInstance(); + } + + // If no cache name given, use bean name as cache name. + if (this.cacheName == null) { + this.cacheName = this.beanName; + } + + // Fetch cache region: If none with the given name exists, + // create one on the fly. + Ehcache rawCache = null; + if (this.cacheManager.cacheExists(this.cacheName)) { + if (logger.isDebugEnabled()) { + logger.debug("Using existing EHCache cache region '" + this.cacheName + "'"); + } + rawCache = this.cacheManager.getEhcache(this.cacheName); + } + else { + if (logger.isDebugEnabled()) { + logger.debug("Creating new EHCache cache region '" + this.cacheName + "'"); + } + rawCache = createCache(); + this.cacheManager.addCache(rawCache); + } + + // Decorate cache if necessary. + Ehcache decoratedCache = decorateCache(rawCache); + if (decoratedCache != rawCache) { + this.cacheManager.replaceCacheWithDecoratedCache(rawCache, decoratedCache); + } + this.cache = decoratedCache; + } + + /** + * Create a raw Cache object based on the configuration of this FactoryBean. + */ + private Cache createCache() { + return new Cache( + this.cacheName, this.maxElementsInMemory, this.memoryStoreEvictionPolicy, + this.overflowToDisk, null, this.eternal, this.timeToLive, this.timeToIdle, + this.diskPersistent, this.diskExpiryThreadIntervalSeconds, null, null, this.maxElementsOnDisk); + } + + /** + * Decorate the given Cache, if necessary. + * @param cache the raw Cache object, based on the configuration of this FactoryBean + * @return the (potentially decorated) cache object to be registered with the CacheManager + */ + protected Ehcache decorateCache(Ehcache cache) { + if (this.cacheEntryFactory != null) { + if (this.cacheEntryFactory instanceof UpdatingCacheEntryFactory) { + return new UpdatingSelfPopulatingCache(cache, (UpdatingCacheEntryFactory) this.cacheEntryFactory); + } + else { + return new SelfPopulatingCache(cache, this.cacheEntryFactory); + } + } + if (this.blocking) { + return new BlockingCache(cache); + } + return cache; + } + + + public Object getObject() { + return this.cache; + } + + public Class getObjectType() { + return (this.cache != null ? this.cache.getClass() : Ehcache.class); + } + + public boolean isSingleton() { + return true; + } + +} Index: 3rdParty_sources/spring/org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,143 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cache.ehcache; + +import java.io.IOException; + +import net.sf.ehcache.CacheException; +import net.sf.ehcache.CacheManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.core.io.Resource; + +/** + * FactoryBean that exposes an EHCache {@link net.sf.ehcache.CacheManager} instance + * (independent or shared), configured from a specified config location. + * + *

    If no config location is specified, a CacheManager will be configured from + * "ehcache.xml" in the root of the class path (that is, default EHCache initialization + * - as defined in the EHCache docs - will apply). + * + *

    Setting up a separate EhCacheManagerFactoryBean is also advisable when using + * EhCacheFactoryBean, as it provides a (by default) independent CacheManager instance + * and cares for proper shutdown of the CacheManager. EhCacheManagerFactoryBean is + * also necessary for loading EHCache configuration from a non-default config location. + * + *

    Note: As of Spring 2.0, this FactoryBean will by default create an independent + * CacheManager instance, which requires EHCache 1.2 or higher. + * + * @author Dmitriy Kopylenko + * @author Juergen Hoeller + * @since 1.1.1 + * @see #setConfigLocation + * @see #setShared + * @see EhCacheFactoryBean + * @see net.sf.ehcache.CacheManager + */ +public class EhCacheManagerFactoryBean implements FactoryBean, InitializingBean, DisposableBean { + + protected final Log logger = LogFactory.getLog(getClass()); + + private Resource configLocation; + + private boolean shared = false; + + private String cacheManagerName; + + private CacheManager cacheManager; + + + /** + * Set the location of the EHCache config file. A typical value is "/WEB-INF/ehcache.xml". + *

    Default is "ehcache.xml" in the root of the class path, or if not found, + * "ehcache-failsafe.xml" in the EHCache jar (default EHCache initialization). + * @see net.sf.ehcache.CacheManager#create(java.io.InputStream) + * @see net.sf.ehcache.CacheManager#CacheManager(java.io.InputStream) + */ + public void setConfigLocation(Resource configLocation) { + this.configLocation = configLocation; + } + + /** + * Set whether the EHCache CacheManager should be shared (as a singleton at the VM level) + * or independent (typically local within the application). Default is "false", creating + * an independent instance. + * @see net.sf.ehcache.CacheManager#create() + * @see net.sf.ehcache.CacheManager#CacheManager() + */ + public void setShared(boolean shared) { + this.shared = shared; + } + + /** + * Set the name of the EHCache CacheManager (if a specific name is desired). + * @see net.sf.ehcache.CacheManager#setName(String) + */ + public void setCacheManagerName(String cacheManagerName) { + this.cacheManagerName = cacheManagerName; + } + + + public void afterPropertiesSet() throws IOException, CacheException { + logger.info("Initializing EHCache CacheManager"); + if (this.shared) { + // Shared CacheManager singleton at the VM level. + if (this.configLocation != null) { + this.cacheManager = CacheManager.create(this.configLocation.getInputStream()); + } + else { + this.cacheManager = CacheManager.create(); + } + } + else { + // Independent CacheManager instance (the default). + if (this.configLocation != null) { + this.cacheManager = new CacheManager(this.configLocation.getInputStream()); + } + else { + this.cacheManager = new CacheManager(); + } + } + if (this.cacheManagerName != null) { + this.cacheManager.setName(this.cacheManagerName); + } + } + + + public Object getObject() { + return this.cacheManager; + } + + public Class getObjectType() { + return (this.cacheManager != null ? this.cacheManager.getClass() : CacheManager.class); + } + + public boolean isSingleton() { + return true; + } + + + public void destroy() { + logger.info("Shutting down EHCache CacheManager"); + this.cacheManager.shutdown(); + } + +} Index: 3rdParty_sources/spring/org/springframework/cache/ehcache/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/cache/ehcache/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/cache/ehcache/package.html 17 Aug 2012 15:11:48 -0000 1.1 @@ -0,0 +1,10 @@ + + + +Support classes for the open source cache +EHCache, +allowing to set up an EHCache CacheManager and Caches +as beans in a Spring context. + + + Index: 3rdParty_sources/spring/org/springframework/context/ApplicationContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/ApplicationContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/ApplicationContext.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,103 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +import org.springframework.beans.factory.HierarchicalBeanFactory; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.core.io.support.ResourcePatternResolver; + +/** + * Central interface to provide configuration for an application. + * This is read-only while the application is running, but may be + * reloaded if the implementation supports this. + * + *

    An ApplicationContext provides: + *

      + *
    • Bean factory methods for accessing application components. + * Inherited from {@link org.springframework.beans.factory.ListableBeanFactory}. + *
    • The ability to load file resources in a generic fashion. + * Inherited from the {@link org.springframework.core.io.ResourceLoader} interface. + *
    • The ability to publish events to registered listeners. + * Inherited from the {@link ApplicationEventPublisher} interface. + *
    • The ability to resolve messages, supporting internationalization. + * Inherited from the {@link MessageSource} interface. + *
    • Inheritance from a parent context. Definitions in a descendant context + * will always take priority. This means, for example, that a single parent + * context can be used by an entire web application, while each servlet has + * its own child context that is independent of that of any other servlet. + *
    + * + *

    In addition to standard {@link org.springframework.beans.factory.BeanFactory} + * lifecycle capabilities, ApplicationContext implementations detect and invoke + * {@link ApplicationContextAware} beans as well as {@link ResourceLoaderAware}, + * {@link ApplicationEventPublisherAware} and {@link MessageSourceAware} beans. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see ConfigurableApplicationContext + * @see org.springframework.beans.factory.BeanFactory + * @see org.springframework.core.io.ResourceLoader + */ +public interface ApplicationContext extends ListableBeanFactory, HierarchicalBeanFactory, + MessageSource, ApplicationEventPublisher, ResourcePatternResolver { + + /** + * Return the unique id of this application context. + * @return the unique id of the context + */ + String getId(); + + /** + * Return a friendly name for this context. + * @return a display name for this context + */ + String getDisplayName(); + + /** + * Return the timestamp when this context was first loaded. + * @return the timestamp (ms) when this context was first loaded + */ + long getStartupDate(); + + /** + * Return the parent context, or null if there is no parent + * and this is the root of the context hierarchy. + * @return the parent context, or null if there is no parent + */ + ApplicationContext getParent(); + + /** + * Expose AutowireCapableBeanFactory functionality for this context. + *

    This is not typically used by application code, except for the purpose + * of initializing bean instances that live outside the application context, + * applying the Spring bean lifecycle (fully or partly) to them. + *

    Alternatively, the internal BeanFactory exposed by the + * {@link ConfigurableApplicationContext} interface offers access to the + * AutowireCapableBeanFactory interface too. The present method mainly + * serves as convenient, specific facility on the ApplicationContext + * interface itself. + * @return the AutowireCapableBeanFactory for this context + * @throws IllegalStateException if the context does not support + * the AutowireCapableBeanFactory interface or does not hold an autowire-capable + * bean factory yet (usually if refresh() has never been called) + * @see ConfigurableApplicationContext#refresh() + * @see ConfigurableApplicationContext#getBeanFactory() + */ + AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException; + +} Index: 3rdParty_sources/spring/org/springframework/context/ApplicationContextAware.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/ApplicationContextAware.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/ApplicationContextAware.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,74 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +import org.springframework.beans.BeansException; + +/** + * Interface to be implemented by any object that wishes to be notified + * of the {@link ApplicationContext} that it runs in. + * + *

    Implementing this interface makes sense for example when an object + * requires access to a set of collaborating beans. Note that configuration + * via bean references is preferable to implementing this interface just + * for bean lookup purposes. + * + *

    This interface can also be implemented if an object needs access to file + * resources, i.e. wants to call getResource, wants to publish + * an application event, or requires access to the MessageSource. However, + * it is preferable to implement the more specific {@link ResourceLoaderAware}, + * {@link ApplicationEventPublisherAware} or {@link MessageSourceAware} interface + * in such a specific scenario. + * + *

    Note that file resource dependencies can also be exposed as bean properties + * of type {@link org.springframework.core.io.Resource}, populated via Strings + * with automatic type conversion by the bean factory. This removes the need + * for implementing any callback interface just for the purpose of accessing + * a specific file resource. + * + *

    {@link org.springframework.context.support.ApplicationObjectSupport} is a + * convenience base class for application objects, implementing this interface. + * + *

    For a list of all bean lifecycle methods, see the + * {@link org.springframework.beans.factory.BeanFactory BeanFactory javadocs}. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see ResourceLoaderAware + * @see ApplicationEventPublisherAware + * @see MessageSourceAware + * @see org.springframework.context.support.ApplicationObjectSupport + * @see org.springframework.beans.factory.BeanFactoryAware + */ +public interface ApplicationContextAware { + + /** + * Set the ApplicationContext that this object runs in. + * Normally this call will be used to initialize the object. + *

    Invoked after population of normal bean properties but before an init callback such + * as {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()} + * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader}, + * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and + * {@link MessageSourceAware}, if applicable. + * @param applicationContext the ApplicationContext object to be used by this object + * @throws ApplicationContextException in case of context initialization errors + * @throws BeansException if thrown by application context methods + * @see org.springframework.beans.factory.BeanInitializationException + */ + void setApplicationContext(ApplicationContext applicationContext) throws BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/context/ApplicationContextException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/ApplicationContextException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/ApplicationContextException.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +import org.springframework.beans.FatalBeanException; + +/** + * Exception thrown during application context initialization. + * + * @author Rod Johnson + */ +public class ApplicationContextException extends FatalBeanException { + + /** + * Create a new ApplicationContextException + * with the specified detail message and no root cause. + * @param msg the detail message + */ + public ApplicationContextException(String msg) { + super(msg); + } + + /** + * Create a new ApplicationContextException + * with the specified detail message and the given root cause. + * @param msg the detail message + * @param cause the root cause + */ + public ApplicationContextException(String msg, Throwable cause) { + super(msg, cause); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/ApplicationEvent.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/ApplicationEvent.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/ApplicationEvent.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +import java.util.EventObject; + +/** + * Class to be extended by all application events. Abstract as it + * doesn't make sense for generic events to be published directly. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public abstract class ApplicationEvent extends EventObject { + + /** use serialVersionUID from Spring 1.2 for interoperability */ + private static final long serialVersionUID = 7099057708183571937L; + + /** System time when the event happened */ + private final long timestamp; + + + /** + * Create a new ApplicationEvent. + * @param source the component that published the event (never null) + */ + public ApplicationEvent(Object source) { + super(source); + this.timestamp = System.currentTimeMillis(); + } + + + /** + * Return the system time in milliseconds when the event happened. + */ + public final long getTimestamp() { + return this.timestamp; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/ApplicationEventPublisher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/ApplicationEventPublisher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/ApplicationEventPublisher.java 17 Aug 2012 15:14:40 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +/** + * Interface that encapsulates event publication functionality. + * Serves as super-interface for ApplicationContext. + * + * @author Juergen Hoeller + * @since 1.1.1 + * @see ApplicationContext + * @see ApplicationEventPublisherAware + * @see org.springframework.context.ApplicationEvent + * @see org.springframework.context.event.EventPublicationInterceptor + */ +public interface ApplicationEventPublisher { + + /** + * Notify all listeners registered with this application of an application + * event. Events may be framework events (such as RequestHandledEvent) + * or application-specific events. + * @param event the event to publish + * @see org.springframework.web.context.support.RequestHandledEvent + */ + void publishEvent(ApplicationEvent event); + +} Index: 3rdParty_sources/spring/org/springframework/context/ApplicationEventPublisherAware.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/ApplicationEventPublisherAware.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/ApplicationEventPublisherAware.java 17 Aug 2012 15:14:40 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +/** + * Interface to be implemented by any object that wishes to be notified + * of the ApplicationEventPublisher (typically the ApplicationContext) + * that it runs in. + * + * @author Juergen Hoeller + * @since 1.1.1 + * @see ApplicationContextAware + */ +public interface ApplicationEventPublisherAware { + + /** + * Set the ApplicationEventPublisher that this object runs in. + *

    Invoked after population of normal bean properties but before an init + * callback like InitializingBean's afterPropertiesSet or a custom init-method. + * Invoked before ApplicationContextAware's setApplicationContext. + * @param applicationEventPublisher event publisher to be used by this object + */ + void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher); + +} Index: 3rdParty_sources/spring/org/springframework/context/ApplicationListener.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/ApplicationListener.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/ApplicationListener.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +import java.util.EventListener; + +/** + * Interface to be implemented by application event listeners. + * Based on the standard java.util.EventListener interface + * for the Observer design pattern. + * + * @author Rod Johnson + * @see org.springframework.context.event.ApplicationEventMulticaster + */ +public interface ApplicationListener extends EventListener { + + /** + * Handle an application event. + * @param event the event to respond to + */ + void onApplicationEvent(ApplicationEvent event); + +} Index: 3rdParty_sources/spring/org/springframework/context/ConfigurableApplicationContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/ConfigurableApplicationContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/ConfigurableApplicationContext.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,149 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; + +/** + * SPI interface to be implemented by most if not all application contexts. + * Provides facilities to configure an application context in addition + * to the application context client methods in the + * {@link org.springframework.context.ApplicationContext} interface. + * + *

    Configuration and lifecycle methods are encapsulated here to avoid + * making them obvious to ApplicationContext client code. The present + * methods should only be used by startup and shutdown code. + * + * @author Juergen Hoeller + * @since 03.11.2003 + */ +public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle { + + /** + * Any number of these characters are considered delimiters between + * multiple context config paths in a single String value. + * @see org.springframework.context.support.AbstractXmlApplicationContext#setConfigLocation + * @see org.springframework.web.context.ContextLoader#CONFIG_LOCATION_PARAM + * @see org.springframework.web.servlet.FrameworkServlet#setContextConfigLocation + */ + String CONFIG_LOCATION_DELIMITERS = ",; \t\n"; + + /** + * Name of the LoadTimeWeaver bean in the factory. If such a bean is supplied, + * the context will use a temporary ClassLoader for type matching, in order + * to allow the LoadTimeWeaver to process all actual bean classes. + * @see org.springframework.instrument.classloading.LoadTimeWeaver + */ + String LOAD_TIME_WEAVER_BEAN_NAME = "loadTimeWeaver"; + + + /** + * Set the parent of this application context. + *

    Note that the parent shouldn't be changed: It should only be set outside + * a constructor if it isn't available when an object of this class is created, + * for example in case of WebApplicationContext setup. + * @param parent the parent context + * @see org.springframework.web.context.ConfigurableWebApplicationContext + */ + void setParent(ApplicationContext parent); + + /** + * Add a new BeanFactoryPostProcessor that will get applied to the internal + * bean factory of this application context on refresh, before any of the + * bean definitions get evaluated. To be invoked during context configuration. + * @param beanFactoryPostProcessor the factory processor to register + */ + void addBeanFactoryPostProcessor(BeanFactoryPostProcessor beanFactoryPostProcessor); + + /** + * Add a new ApplicationListener that will be notified on context events + * such as context refresh and context shutdown. + *

    Note that any ApplicationListener registered here will be applied + * on refresh of this context. If a listener is added after the initial + * refresh, it will be applied on next refresh of the context. + * @param listener the ApplicationListener to register + * @see org.springframework.context.event.ContextRefreshedEvent + * @see org.springframework.context.event.ContextClosedEvent + */ + void addApplicationListener(ApplicationListener listener); + + /** + * Load or refresh the persistent representation of the configuration, + * which might an XML file, properties file, or relational database schema. + *

    As this is a startup method, it should destroy already created singletons + * if it fails, to avoid dangling resources. In other words, after invocation + * of that method, either all or no singletons at all should be instantiated. + * @throws BeansException if the bean factory could not be initialized + * @throws IllegalStateException if already initialized and multiple refresh + * attempts are not supported + */ + void refresh() throws BeansException, IllegalStateException; + + /** + * Register a shutdown hook with the JVM runtime, closing this context + * on JVM shutdown unless it has already been closed at that time. + *

    This method can be called multiple times. Only one shutdown hook + * (at max) will be registered for each context instance. + * @see java.lang.Runtime#addShutdownHook + * @see #close() + */ + void registerShutdownHook(); + + /** + * Close this application context, releasing all resources and locks that the + * implementation might hold. This includes destroying all cached singleton beans. + *

    Note: Does not invoke close on a parent context; + * parent contexts have their own, independent lifecycle. + *

    This method can be called multiple times without side effects: Subsequent + * close calls on an already closed context will be ignored. + */ + void close(); + + /** + * Determine whether this application context is active, that is, + * whether it has been refreshed at least once and has not been closed yet. + * @return whether the context is still active + * @see #refresh() + * @see #close() + * @see #getBeanFactory() + */ + boolean isActive(); + + /** + * Return the internal bean factory of this application context. + * Can be used to access specific functionality of the underlying factory. + *

    Note: Do not use this to post-process the bean factory; singletons + * will already have been instantiated before. Use a BeanFactoryPostProcessor + * to intercept the BeanFactory setup process before beans get touched. + *

    Generally, this internal factory will only be accessible while the context + * is active, that is, inbetween {@link #refresh()} and {@link #close()}. + * The {@link #isActive()} flag can be used to check whether the context + * is in an appropriate state. + * @return the underlying bean factory + * @throws IllegalStateException if the context does not hold an internal + * bean factory (usually if {@link #refresh()} hasn't been called yet or + * if {@link #close()} has already been called) + * @see #isActive() + * @see #refresh() + * @see #close() + * @see #addBeanFactoryPostProcessor + */ + ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException; + +} Index: 3rdParty_sources/spring/org/springframework/context/HierarchicalMessageSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/HierarchicalMessageSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/HierarchicalMessageSource.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +/** + * Sub-interface of MessageSource to be implemented by objects that + * can resolve messages hierarchically. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public interface HierarchicalMessageSource extends MessageSource { + + /** + * Set the parent that will be used to try to resolve messages + * that this object can't resolve. + * @param parent the parent MessageSource that will be used to + * resolve messages that this object can't resolve. + * May be null, in which case no further resolution is possible. + */ + void setParentMessageSource(MessageSource parent); + + /** + * Return the parent of this MessageSource, or null if none. + */ + MessageSource getParentMessageSource(); + +} Index: 3rdParty_sources/spring/org/springframework/context/Lifecycle.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/Lifecycle.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/Lifecycle.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +/** + * Interface defining methods for start/stop lifecycle control. + * The typical use case for this is to control asynchronous processing. + * + *

    Can be implemented by both components (typically a Spring bean defined in + * a Spring {@link org.springframework.beans.factory.BeanFactory}) and containers + * (typically a Spring {@link ApplicationContext}). Containers will propagate + * start/stop signals to all components that apply. + * + *

    Can be used for direct invocations or for management operations via JMX. + * In the latter case, the {@link org.springframework.jmx.export.MBeanExporter} + * will typically be defined with an + * {@link org.springframework.jmx.export.assembler.InterfaceBasedMBeanInfoAssembler}, + * restricting the visibility of activity-controlled components to the Lifecycle + * interface. + * + * @author Juergen Hoeller + * @since 2.0 + * @see ConfigurableApplicationContext + * @see org.springframework.jms.listener.AbstractMessageListenerContainer + * @see org.springframework.scheduling.quartz.SchedulerFactoryBean + */ +public interface Lifecycle { + + /** + * Start this component. + * Should not throw an exception if the component is already running. + *

    In the case of a container, this will propagate the start signal + * to all components that apply. + */ + void start(); + + /** + * Stop this component. + * Should not throw an exception if the component isn't started yet. + *

    In the case of a container, this will propagate the stop signal + * to all components that apply. + */ + void stop(); + + /** + * Check whether this component is currently running. + *

    In the case of a container, this will return true + * only if all components that apply are currently running. + * @return whether the component is currently running + */ + boolean isRunning(); + +} Index: 3rdParty_sources/spring/org/springframework/context/MessageSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/MessageSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/MessageSource.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +import java.util.Locale; + +/** + * Strategy interface for resolving messages, with support for the parameterization + * and internationalization of such messages. + * + *

    Spring provides two out-of-the-box implementations for production: + *

      + *
    • {@link org.springframework.context.support.ResourceBundleMessageSource}, + * built on top of the standard {@link java.util.ResourceBundle} + *
    • {@link org.springframework.context.support.ReloadableResourceBundleMessageSource}, + * being able to reload message definitions without restarting the VM + *
    + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see org.springframework.context.support.ResourceBundleMessageSource + * @see org.springframework.context.support.ReloadableResourceBundleMessageSource + */ +public interface MessageSource { + + /** + * Try to resolve the message. Return default message if no message was found. + * @param code the code to lookup up, such as 'calculator.noRateSet'. Users of + * this class are encouraged to base message names on the relevant fully + * qualified class name, thus avoiding conflict and ensuring maximum clarity. + * @param args array of arguments that will be filled in for params within + * the message (params look like "{0}", "{1,date}", "{2,time}" within a message), + * or null if none. + * @param defaultMessage String to return if the lookup fails + * @param locale the Locale in which to do the lookup + * @return the resolved message if the lookup was successful; + * otherwise the default message passed as a parameter + * @see java.text.MessageFormat + */ + String getMessage(String code, Object[] args, String defaultMessage, Locale locale); + + /** + * Try to resolve the message. Treat as an error if the message can't be found. + * @param code the code to lookup up, such as 'calculator.noRateSet' + * @param args Array of arguments that will be filled in for params within + * the message (params look like "{0}", "{1,date}", "{2,time}" within a message), + * or null if none. + * @param locale the Locale in which to do the lookup + * @return the resolved message + * @throws NoSuchMessageException if the message wasn't found + * @see java.text.MessageFormat + */ + String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException; + + /** + * Try to resolve the message using all the attributes contained within the + * MessageSourceResolvable argument that was passed in. + *

    NOTE: We must throw a NoSuchMessageException on this method + * since at the time of calling this method we aren't able to determine if the + * defaultMessage property of the resolvable is null or not. + * @param resolvable value object storing attributes required to properly resolve a message + * @param locale the Locale in which to do the lookup + * @return the resolved message + * @throws NoSuchMessageException if the message wasn't found + * @see java.text.MessageFormat + */ + String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException; + +} Index: 3rdParty_sources/spring/org/springframework/context/MessageSourceAware.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/MessageSourceAware.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/MessageSourceAware.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +/** + * Interface to be implemented by any object that wishes to be notified + * of the MessageSource (typically the ApplicationContext) that it runs in. + * + *

    Note that the MessageSource can usually also be passed on as bean + * reference (to arbitrary bean properties or constructor arguments), because + * it is defined as bean with name "messageSource" in the application context. + * + * @author Juergen Hoeller + * @since 1.1.1 + * @see ApplicationContextAware + */ +public interface MessageSourceAware { + + /** + * Set the MessageSource that this object runs in. + *

    Invoked after population of normal bean properties but before an init + * callback like InitializingBean's afterPropertiesSet or a custom init-method. + * Invoked before ApplicationContextAware's setApplicationContext. + * @param messageSource message sourceto be used by this object + */ + void setMessageSource(MessageSource messageSource); + +} Index: 3rdParty_sources/spring/org/springframework/context/MessageSourceResolvable.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/MessageSourceResolvable.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/MessageSourceResolvable.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +/** + * Interface for objects that are suitable for message resolution in a + * {@link MessageSource}. + * + *

    Spring's own validation error classes implement this interface. + * + * @author Juergen Hoeller + * @see MessageSource#getMessage(MessageSourceResolvable, java.util.Locale) + * @see org.springframework.validation.ObjectError + * @see org.springframework.validation.FieldError + */ +public interface MessageSourceResolvable { + + /** + * Return the codes to be used to resolve this message, in the order that + * they should get tried. The last code will therefore be the default one. + * @return a String array of codes which are associated with this message + */ + public String[] getCodes(); + + /** + * Return the array of arguments to be used to resolve this message. + * @return an array of objects to be used as parameters to replace + * placeholders within the message text + * @see java.text.MessageFormat + */ + public Object[] getArguments(); + + /** + * Return the default message to be used to resolve this message. + * @return the default message, or null if no default + */ + public String getDefaultMessage(); + +} Index: 3rdParty_sources/spring/org/springframework/context/NoSuchMessageException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/NoSuchMessageException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/NoSuchMessageException.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +import java.util.Locale; + +/** + * Exception thrown when a message can't be resolved. + * + * @author Rod Johnson + */ +public class NoSuchMessageException extends RuntimeException { + + /** + * Create a new exception. + * @param code code that could not be resolved for given locale + * @param locale locale that was used to search for the code within + */ + public NoSuchMessageException(String code, Locale locale) { + super("No message found under code '" + code + "' for locale '" + locale + "'."); + } + + /** + * Create a new exception. + * @param code code that could not be resolved for given locale + */ + public NoSuchMessageException(String code) { + super("No message found under code '" + code + "' for locale '" + Locale.getDefault() + "'."); + } + +} + Index: 3rdParty_sources/spring/org/springframework/context/ResourceLoaderAware.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/ResourceLoaderAware.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/ResourceLoaderAware.java 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context; + +import org.springframework.core.io.ResourceLoader; + +/** + * Interface to be implemented by any object that wishes to be notified of + * the ResourceLoader (typically the ApplicationContext) that it runs in. + * This is an alternative to a full ApplicationContext dependency via the + * ApplicationContextAware interface. + * + *

    Note that Resource dependencies can also be exposed as bean properties + * of type Resource, populated via Strings with automatic type conversion by + * the bean factory. This removes the need for implementing any callback + * interface just for the purpose of accessing a specific file resource. + * + *

    You typically need a ResourceLoader when your application object has + * to access a variety of file resources whose names are calculated. A good + * strategy is to make the object use a DefaultResourceLoader but still + * implement ResourceLoaderAware to allow for overriding when running in an + * ApplicationContext. See ReloadableResourceBundleMessageSource for an example. + * + *

    A passed-in ResourceLoader can also be checked for the + * ResourcePatternResolver interface and cast accordingly, to be able + * to resolve resource patterns into arrays of Resource objects. This will always + * work when running in an ApplicationContext (the context interface extends + * ResourcePatternResolver). Use a PathMatchingResourcePatternResolver as default. + * See also the ResourcePatternUtils.getResourcePatternResolver method. + * + *

    As alternative to a ResourcePatternResolver dependency, consider exposing + * bean properties of type Resource array, populated via pattern Strings with + * automatic type conversion by the bean factory. + * + * @author Juergen Hoeller + * @since 10.03.2004 + * @see ApplicationContextAware + * @see org.springframework.beans.factory.InitializingBean + * @see org.springframework.core.io.Resource + * @see org.springframework.core.io.support.ResourcePatternResolver + * @see org.springframework.core.io.support.ResourcePatternUtils#getResourcePatternResolver + * @see org.springframework.core.io.DefaultResourceLoader + * @see org.springframework.core.io.support.PathMatchingResourcePatternResolver + * @see org.springframework.context.support.ReloadableResourceBundleMessageSource + */ +public interface ResourceLoaderAware { + + /** + * Set the ResourceLoader that this object runs in. + *

    This might be a ResourcePatternResolver, which can be checked + * through instanceof ResourcePatternResolver. See also the + * ResourcePatternUtils.getResourcePatternResolver method. + *

    Invoked after population of normal bean properties but before an init callback + * like InitializingBean's afterPropertiesSet or a custom init-method. + * Invoked before ApplicationContextAware's setApplicationContext. + * @param resourceLoader ResourceLoader object to be used by this object + * @see org.springframework.core.io.support.ResourcePatternResolver + * @see org.springframework.core.io.support.ResourcePatternUtils#getResourcePatternResolver + */ + void setResourceLoader(ResourceLoader resourceLoader); + +} Index: 3rdParty_sources/spring/org/springframework/context/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/package.html 17 Aug 2012 15:14:41 -0000 1.1 @@ -0,0 +1,16 @@ + + + +This package builds on the beans package to add support for +message sources and for the Observer design pattern, and the +ability for application objects to obtain resources using a +consistent API. + +

    There is no necessity for Spring applications to depend +on ApplicationContext or even BeanFactory functionality +explicitly. One of the strengths of the Spring architecture +is that application objects can often be configured without +any dependency on Spring-specific APIs. + + + Index: 3rdParty_sources/spring/org/springframework/context/access/ContextBeanFactoryReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/access/ContextBeanFactoryReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/access/ContextBeanFactoryReference.java 17 Aug 2012 15:14:44 -0000 1.1 @@ -0,0 +1,75 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.access; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.access.BeanFactoryReference; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * ApplicationContext-specific implementation of BeanFactoryReference, + * wrapping a newly created ApplicationContext, closing it on release. + * + *

    As per BeanFactoryReference contract, release may be called + * more than once, with subsequent calls not doing anything. However, calling + * getFactory after a release call will cause an exception. + * + * @author Juergen Hoeller + * @author Colin Sampaleanu + * @since 13.02.2004 + * @see org.springframework.context.ConfigurableApplicationContext#close + */ +public class ContextBeanFactoryReference implements BeanFactoryReference { + + private ApplicationContext applicationContext; + + + /** + * Create a new ContextBeanFactoryReference for the given context. + * @param applicationContext the ApplicationContext to wrap + */ + public ContextBeanFactoryReference(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + + public BeanFactory getFactory() { + if (this.applicationContext == null) { + throw new IllegalStateException( + "ApplicationContext owned by this BeanFactoryReference has been released"); + } + return this.applicationContext; + } + + public void release() { + if (this.applicationContext != null) { + ApplicationContext savedCtx; + + // We don't actually guarantee thread-safety, but it's not a lot of extra work. + synchronized (this) { + savedCtx = this.applicationContext; + this.applicationContext = null; + } + + if (savedCtx != null && savedCtx instanceof ConfigurableApplicationContext) { + ((ConfigurableApplicationContext) savedCtx).close(); + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/context/access/ContextJndiBeanFactoryLocator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/access/ContextJndiBeanFactoryLocator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/access/ContextJndiBeanFactoryLocator.java 17 Aug 2012 15:14:44 -0000 1.1 @@ -0,0 +1,105 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.access; + +import javax.naming.NamingException; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.access.BeanFactoryLocator; +import org.springframework.beans.factory.access.BeanFactoryReference; +import org.springframework.beans.factory.access.BootstrapException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.jndi.JndiLocatorSupport; +import org.springframework.util.StringUtils; + +/** + * BeanFactoryLocator implementation that creates the BeanFactory from one or + * more classpath locations specified in a JNDI environment variable. + * + *

    This default implementation creates a + * {@link org.springframework.context.support.ClassPathXmlApplicationContext}. + * Subclasses may override {@link #createBeanFactory} for custom instantiation. + * + * @author Colin Sampaleanu + * @author Juergen Hoeller + * @see #createBeanFactory + */ +public class ContextJndiBeanFactoryLocator extends JndiLocatorSupport implements BeanFactoryLocator { + + /** + * Any number of these characters are considered delimiters between + * multiple bean factory config paths in a single String value. + */ + public static final String BEAN_FACTORY_PATH_DELIMITERS = ",; \t\n"; + + + /** + * Load/use a bean factory, as specified by a factory key which is a JNDI + * address, of the form java:comp/env/ejb/BeanFactoryPath. The + * contents of this JNDI location must be a string containing one or more + * classpath resource names (separated by any of the delimiters ',; \t\n' + * if there is more than one. The resulting BeanFactory (or ApplicationContext) + * will be created from the combined resources. + * @see #createBeanFactory + */ + public BeanFactoryReference useBeanFactory(String factoryKey) throws BeansException { + try { + String beanFactoryPath = (String) lookup(factoryKey, String.class); + if (logger.isTraceEnabled()) { + logger.trace("Bean factory path from JNDI environment variable [" + factoryKey + + "] is: " + beanFactoryPath); + } + String[] paths = StringUtils.tokenizeToStringArray(beanFactoryPath, BEAN_FACTORY_PATH_DELIMITERS); + return createBeanFactory(paths); + } + catch (NamingException ex) { + throw new BootstrapException("Define an environment variable [" + factoryKey + "] containing " + + "the class path locations of XML bean definition files", ex); + } + } + + /** + * Create the BeanFactory instance, given an array of class path resource Strings + * which should be combined. This is split out as a separate method so that + * subclasses can override the actual BeanFactory implementation class. + *

    Delegates to createApplicationContext by default, + * wrapping the result in a ContextBeanFactoryReference. + * @param resources an array of Strings representing classpath resource names + * @return the created BeanFactory, wrapped in a BeanFactoryReference + * (for example, a ContextBeanFactoryReference wrapping an ApplicationContext) + * @throws BeansException if factory creation failed + * @see #createApplicationContext + * @see ContextBeanFactoryReference + */ + protected BeanFactoryReference createBeanFactory(String[] resources) throws BeansException { + ApplicationContext ctx = createApplicationContext(resources); + return new ContextBeanFactoryReference(ctx); + } + + /** + * Create the ApplicationContext instance, given an array of class path resource + * Strings which should be combined + * @param resources an array of Strings representing classpath resource names + * @return the created ApplicationContext + * @throws BeansException if context creation failed + */ + protected ApplicationContext createApplicationContext(String[] resources) throws BeansException { + return new ClassPathXmlApplicationContext(resources); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/access/ContextSingletonBeanFactoryLocator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/access/ContextSingletonBeanFactoryLocator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/access/ContextSingletonBeanFactoryLocator.java 17 Aug 2012 15:14:44 -0000 1.1 @@ -0,0 +1,159 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.access; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.access.BeanFactoryLocator; +import org.springframework.beans.factory.access.SingletonBeanFactoryLocator; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternUtils; + +/** + *

    Variant of {@link org.springframework.beans.factory.access.SingletonBeanFactoryLocator} + * which creates its internal bean factory reference as an + * {@link org.springframework.context.ApplicationContext} instead of + * SingletonBeanFactoryLocator's simple BeanFactory. For almost all usage scenarios, + * this will not make a difference, since within that ApplicationContext or BeanFactory + * you are still free to define either BeanFactory or ApplicationContext instances. + * The main reason one would need to use this class is if bean post-processing + * (or other ApplicationContext specific features are needed in the bean reference + * definition itself). + * + *

    Note: This class uses classpath*:beanRefContext.xml + * as the default resource location for the bean factory reference definition files. + * It is not possible nor legal to share definitions with SingletonBeanFactoryLocator + * at the same time. + * + * @author Colin Sampaleanu + * @author Juergen Hoeller + * @see org.springframework.beans.factory.access.SingletonBeanFactoryLocator + * @see org.springframework.context.access.DefaultLocatorFactory + */ +public class ContextSingletonBeanFactoryLocator extends SingletonBeanFactoryLocator { + + private static final String DEFAULT_RESOURCE_LOCATION = "classpath*:beanRefContext.xml"; + + /** The keyed singleton instances */ + private static final Map instances = new HashMap(); + + + /** + * Returns an instance which uses the default "classpath*:beanRefContext.xml", as + * the name of the definition file(s). All resources returned by the current + * thread's context class loader's getResources method with this + * name will be combined to create a definition, which is just a BeanFactory. + * @return the corresponding BeanFactoryLocator instance + * @throws BeansException in case of factory loading failure + */ + public static BeanFactoryLocator getInstance() throws BeansException { + return getInstance(null); + } + + /** + * Returns an instance which uses the the specified selector, as the name of the + * definition file(s). In the case of a name with a Spring "classpath*:" prefix, + * or with no prefix, which is treated the same, the current thread's context class + * loader's getResources method will be called with this value to get + * all resources having that name. These resources will then be combined to form a + * definition. In the case where the name uses a Spring "classpath:" prefix, or + * a standard URL prefix, then only one resource file will be loaded as the + * definition. + * @param selector the location of the resource(s) which will be read and + * combined to form the definition for the BeanFactoryLocator instance. + * Any such files must form a valid ApplicationContext definition. + * @return the corresponding BeanFactoryLocator instance + * @throws BeansException in case of factory loading failure + */ + public static BeanFactoryLocator getInstance(String selector) throws BeansException { + String resourceLocation = selector; + if (resourceLocation == null) { + resourceLocation = DEFAULT_RESOURCE_LOCATION; + } + + // For backwards compatibility, we prepend "classpath*:" to the selector name if there + // is no other prefix (i.e. "classpath*:", "classpath:", or some URL prefix). + if (!ResourcePatternUtils.isUrl(resourceLocation)) { + resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation; + } + + synchronized (instances) { + if (logger.isTraceEnabled()) { + logger.trace("ContextSingletonBeanFactoryLocator.getInstance(): instances.hashCode=" + + instances.hashCode() + ", instances=" + instances); + } + BeanFactoryLocator bfl = (BeanFactoryLocator) instances.get(resourceLocation); + if (bfl == null) { + bfl = new ContextSingletonBeanFactoryLocator(resourceLocation); + instances.put(resourceLocation, bfl); + } + return bfl; + } + } + + + /** + * Constructor which uses the the specified name as the resource name + * of the definition file(s). + * @param resourceLocation the Spring resource location to use + * (either a URL or a "classpath:" / "classpath*:" pseudo URL) + */ + protected ContextSingletonBeanFactoryLocator(String resourceLocation) { + super(resourceLocation); + } + + /** + * Overrides the default method to create definition object as an ApplicationContext + * instead of the default BeanFactory. This does not affect what can actually + * be loaded by that definition. + *

    The default implementation simply builds a + * {@link org.springframework.context.support.ClassPathXmlApplicationContext}. + */ + protected BeanFactory createDefinition(String resourceLocation, String factoryKey) { + return new ClassPathXmlApplicationContext(new String[] {resourceLocation}, false); + } + + /** + * Overrides the default method to refresh the ApplicationContext, invoking + * {@link ConfigurableApplicationContext#refresh ConfigurableApplicationContext.refresh()}. + */ + protected void initializeDefinition(BeanFactory groupDef) { + if (groupDef instanceof ConfigurableApplicationContext) { + ((ConfigurableApplicationContext) groupDef).refresh(); + } + } + + /** + * Overrides the default method to operate on an ApplicationContext, invoking + * {@link ConfigurableApplicationContext#refresh ConfigurableApplicationContext.close()}. + */ + protected void destroyDefinition(BeanFactory groupDef, String selector) { + if (groupDef instanceof ConfigurableApplicationContext) { + if (logger.isTraceEnabled()) { + logger.trace("Context group with selector '" + selector + + "' being released, as there are no more references to it"); + } + ((ConfigurableApplicationContext) groupDef).close(); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/context/access/DefaultLocatorFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/access/DefaultLocatorFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/access/DefaultLocatorFactory.java 17 Aug 2012 15:14:44 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.access; + +import org.springframework.beans.FatalBeanException; +import org.springframework.beans.factory.access.BeanFactoryLocator; + +/** + * A factory class to get a default ContextSingletonBeanFactoryLocator instance. + * + * @author Colin Sampaleanu + * @see org.springframework.context.access.ContextSingletonBeanFactoryLocator + */ +public class DefaultLocatorFactory { + + /** + * Return an instance object implementing BeanFactoryLocator. This will normally + * be a singleton instance of the specific ContextSingletonBeanFactoryLocator class, + * using the default resource selector. + */ + public static BeanFactoryLocator getInstance() throws FatalBeanException { + return ContextSingletonBeanFactoryLocator.getInstance(); + } + + /** + * Return an instance object implementing BeanFactoryLocator. This will normally + * be a singleton instance of the specific ContextSingletonBeanFactoryLocator class, + * using the specified resource selector. + * @param selector a selector variable which provides a hint to the factory as to + * which instance to return. + */ + public static BeanFactoryLocator getInstance(String selector) throws FatalBeanException { + return ContextSingletonBeanFactoryLocator.getInstance(selector); + } +} Index: 3rdParty_sources/spring/org/springframework/context/access/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/access/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/access/package.html 17 Aug 2012 15:14:44 -0000 1.1 @@ -0,0 +1,11 @@ + + + +Helper infrastructure to locate and access shared application contexts. + +

    Note: This package is only relevant for special sharing of application +contexts, for example behind EJB facades. It is not used in a typical +web application or standalone application. + + + Index: 3rdParty_sources/spring/org/springframework/context/annotation/AnnotationBeanNameGenerator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/AnnotationBeanNameGenerator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/AnnotationBeanNameGenerator.java 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,129 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import java.beans.Introspector; +import java.util.Map; +import java.util.Set; + +import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.BeanNameGenerator; +import org.springframework.core.type.AnnotationMetadata; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +/** + * {@link org.springframework.beans.factory.support.BeanNameGenerator} + * implementation for bean classes annotated with the + * {@link org.springframework.stereotype.Component @Component} annotation + * or with another annotation that is itself annotated with + * {@link org.springframework.stereotype.Component @Component} as a + * meta-annotation. For example, Spring's stereotype annotations (such as + * {@link org.springframework.stereotype.Repository @Repository}) are + * themselves annotated with + * {@link org.springframework.stereotype.Component @Component}. + * + *

    If the annotation's value doesn't indicate a bean name, an appropriate + * name will be built based on the short name of the class (with the first + * letter lower-cased). For example: + * + *

    com.xyz.FooServiceImpl -> fooServiceImpl
    + * + * @author Juergen Hoeller + * @author Mark Fisher + * @since 2.5 + * @see org.springframework.stereotype.Component#value() + * @see org.springframework.stereotype.Repository#value() + * @see org.springframework.stereotype.Service#value() + * @see org.springframework.stereotype.Controller#value() + */ +public class AnnotationBeanNameGenerator implements BeanNameGenerator { + + private static final String COMPONENT_ANNOTATION_CLASSNAME = "org.springframework.stereotype.Component"; + + + public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) { + if (definition instanceof AnnotatedBeanDefinition) { + String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition); + if (StringUtils.hasText(beanName)) { + // Explicit bean name found. + return beanName; + } + } + // Fallback: generate a unique default bean name. + return buildDefaultBeanName(definition); + } + + /** + * Derive a bean name from one of the annotations on the class. + * @param annotatedDef the annotation-aware bean definition + * @return the bean name, or null if none is found + */ + protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) { + AnnotationMetadata amd = annotatedDef.getMetadata(); + Set types = amd.getAnnotationTypes(); + String beanName = null; + for (String type : types) { + Map attributes = amd.getAnnotationAttributes(type); + if (isStereotypeWithNameValue(type, amd.getMetaAnnotationTypes(type), attributes)) { + String value = (String) attributes.get("value"); + if (StringUtils.hasLength(value)) { + if (beanName != null && !value.equals(beanName)) { + throw new IllegalStateException("Stereotype annotations suggest inconsistent " + + "component names: '" + beanName + "' versus '" + value + "'"); + } + beanName = value; + } + } + } + return beanName; + } + + /** + * Check whether the given annotation is a stereotype that is allowed + * to suggest a component name through its annotation value(). + * @param annotationType the name of the annotation class to check + * @param metaAnnotationTypes the names of meta-annotations on the given annotation + * @param attributes the map of attributes for the given annotation + * @return whether the annotation qualifies as a stereotype with component name + */ + protected boolean isStereotypeWithNameValue(String annotationType, + Set metaAnnotationTypes, Map attributes) { + + boolean isStereotype = annotationType.equals(COMPONENT_ANNOTATION_CLASSNAME) || + (metaAnnotationTypes != null && metaAnnotationTypes.contains(COMPONENT_ANNOTATION_CLASSNAME)); + return (isStereotype && attributes != null && attributes.containsKey("value")); + } + + /** + * Derive a default bean name from the given bean definition. + *

    The default implementation simply builds a decapitalized version + * of the short class name: e.g. "mypackage.MyJdbcDao" -> "myJdbcDao". + *

    Note that inner classes will thus have names of the form + * "outerClassName.innerClassName", which because of the period in the + * name may be an issue if you are autowiring by name. + * @param definition the bean definition to build a bean name for + * @return the default bean name (never null) + */ + protected String buildDefaultBeanName(BeanDefinition definition) { + String shortClassName = ClassUtils.getShortName(definition.getBeanClassName()); + return Introspector.decapitalize(shortClassName); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/AnnotationConfigBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/AnnotationConfigBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/AnnotationConfigBeanDefinitionParser.java 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import java.util.Set; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.parsing.CompositeComponentDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; + +/** + * Parser for the <context:annotation-config/> element. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @author Christian Dupuis + * @since 2.5 + * @see AnnotationConfigUtils + */ +public class AnnotationConfigBeanDefinitionParser implements BeanDefinitionParser { + + public BeanDefinition parse(Element element, ParserContext parserContext) { + Object source = parserContext.extractSource(element); + + // Obtain bean definitions for all relevant BeanPostProcessors. + Set processorDefinitions = + AnnotationConfigUtils.registerAnnotationConfigProcessors(parserContext.getRegistry(), source); + + // Register component for the surrounding element. + CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source); + parserContext.pushContainingComponent(compDefinition); + + // Nest the concrete beans in the surrounding component. + for (BeanDefinitionHolder processorDefinition : processorDefinitions) { + parserContext.registerComponent(new BeanComponentDefinition(processorDefinition)); + } + + // Finally register the composite component. + parserContext.popAndRegisterContainingComponent(); + + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/AnnotationConfigUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/AnnotationConfigUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/AnnotationConfigUtils.java 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,156 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import java.util.LinkedHashSet; +import java.util.Set; + +import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor; +import org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.core.Ordered; +import org.springframework.util.ClassUtils; + +/** + * Utility class that allows for convenient registration of common + * {@link org.springframework.beans.factory.config.BeanPostProcessor} + * definitions for annotation-based configuration. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + * @see CommonAnnotationBeanPostProcessor + * @see org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor + * @see org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor + * @see org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor + */ +public class AnnotationConfigUtils { + + /** + * The bean name of the internally managed JPA annotation processor. + */ + public static final String PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME = + "org.springframework.context.annotation.internalPersistenceAnnotationProcessor"; + + /** + * The bean name of the internally managed JSR-250 annotation processor. + */ + public static final String COMMON_ANNOTATION_PROCESSOR_BEAN_NAME = + "org.springframework.context.annotation.internalCommonAnnotationProcessor"; + + /** + * The bean name of the internally managed Autowired annotation processor. + */ + public static final String AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME = + "org.springframework.context.annotation.internalAutowiredAnnotationProcessor"; + + /** + * The bean name of the internally managed Required annotation processor. + */ + public static final String REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME = + "org.springframework.context.annotation.internalRequiredAnnotationProcessor"; + + + private static final String PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME = + "org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"; + + + private static final boolean jsr250Present = + ClassUtils.isPresent("javax.annotation.Resource", AnnotationConfigUtils.class.getClassLoader()); + + private static final boolean jpaPresent = + ClassUtils.isPresent("javax.persistence.EntityManagerFactory", AnnotationConfigUtils.class.getClassLoader()) && + ClassUtils.isPresent(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, AnnotationConfigUtils.class.getClassLoader()); + + + /** + * Register all relevant annotation post processors in the given registry. + * @param registry the registry to operate on + */ + public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) { + registerAnnotationConfigProcessors(registry, null); + } + + /** + * Register all relevant annotation post processors in the given registry. + * @param registry the registry to operate on + * @param source the configuration source element (already extracted) + * that this registration was triggered from. May be null. + * @return a Set of BeanDefinitionHolders, containing all bean definitions + * that have actually been registered by this call + */ + public static Set registerAnnotationConfigProcessors( + BeanDefinitionRegistry registry, Object source) { + + Set beanDefinitions = new LinkedHashSet(4); + + // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor. + if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) { + RootBeanDefinition def = new RootBeanDefinition(); + try { + ClassLoader cl = AnnotationConfigUtils.class.getClassLoader(); + def.setBeanClass(cl.loadClass(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME)); + } + catch (ClassNotFoundException ex) { + throw new IllegalStateException( + "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex); + } + def.setSource(source); + def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + beanDefinitions.add(registerBeanPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)); + } + + // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor. + if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) { + RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class); + def.setSource(source); + def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + beanDefinitions.add(registerBeanPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); + } + + if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) { + RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class); + def.setSource(source); + def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + beanDefinitions.add(registerBeanPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); + } + + if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) { + RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class); + def.setSource(source); + def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + beanDefinitions.add(registerBeanPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); + } + + return beanDefinitions; + } + + private static BeanDefinitionHolder registerBeanPostProcessor( + BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) { + + // Default infrastructure bean: lowest order value; role infrastructure. + definition.getPropertyValues().addPropertyValue("order", new Integer(Ordered.LOWEST_PRECEDENCE)); + definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + + registry.registerBeanDefinition(beanName, definition); + return new BeanDefinitionHolder(definition, beanName); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,91 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import java.lang.annotation.Annotation; +import java.util.Map; + +import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.util.Assert; + +/** + * A {@link ScopeMetadataResolver} implementation that (by default) checks for + * the presence of the {@link Scope} annotation on the bean class. + * + *

    The exact type of annotation that is checked for is configurable via the + * {@link #setScopeAnnotationType(Class)} property. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + * @see Scope + */ +public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver { + + private Class scopeAnnotationType = Scope.class; + + private ScopedProxyMode scopedProxyMode; + + + /** + * Create a new instance of the AnnotationScopeMetadataResolver class. + * @see #AnnotationScopeMetadataResolver(ScopedProxyMode) + * @see ScopedProxyMode#NO + */ + public AnnotationScopeMetadataResolver() { + this(ScopedProxyMode.NO); + } + + /** + * Create a new instance of the AnnotationScopeMetadataResolver class. + * @param scopedProxyMode the desired scoped-proxy mode + */ + public AnnotationScopeMetadataResolver(ScopedProxyMode scopedProxyMode) { + Assert.notNull(scopedProxyMode, "'scopedProxyMode' must not be null"); + this.scopedProxyMode = scopedProxyMode; + } + + + /** + * Set the type of annotation that is checked for by this + * {@link AnnotationScopeMetadataResolver}. + * @param scopeAnnotationType the target annotation type + */ + public void setScopeAnnotationType(Class scopeAnnotationType) { + Assert.notNull(scopeAnnotationType, "'scopeAnnotationType' must not be null"); + this.scopeAnnotationType = scopeAnnotationType; + } + + + public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) { + ScopeMetadata metadata = new ScopeMetadata(); + if (definition instanceof AnnotatedBeanDefinition) { + AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition; + Map attributes = + annDef.getMetadata().getAnnotationAttributes(this.scopeAnnotationType.getName()); + if (attributes != null) { + metadata.setScopeName((String) attributes.get("value")); + } + if (!metadata.getScopeName().equals(BeanDefinition.SCOPE_SINGLETON)) { + metadata.setScopedProxyMode(this.scopedProxyMode); + } + } + return metadata; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/ClassPathBeanDefinitionScanner.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/ClassPathBeanDefinitionScanner.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/ClassPathBeanDefinitionScanner.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,321 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import java.util.LinkedHashSet; +import java.util.Set; + +import org.springframework.aop.scope.ScopedProxyUtils; +import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionDefaults; +import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.BeanNameGenerator; +import org.springframework.core.io.ResourceLoader; +import org.springframework.util.Assert; +import org.springframework.util.PatternMatchUtils; + +/** + * A bean definition scanner that detects bean candidates on the classpath, + * registering corresponding bean definitions with a given registry (BeanFactory + * or ApplicationContext). + * + *

    Candidate classes are detected through configurable type filters. The + * default filters include classes that are annotated with Spring's + * {@link org.springframework.stereotype.Component @Component}, + * {@link org.springframework.stereotype.Repository @Repository}, + * {@link org.springframework.stereotype.Service @Service}, or + * {@link org.springframework.stereotype.Controller @Controller} stereotype. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + * @see org.springframework.stereotype.Component + * @see org.springframework.stereotype.Repository + * @see org.springframework.stereotype.Service + * @see org.springframework.stereotype.Controller + */ +public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider { + + private final BeanDefinitionRegistry registry; + + private BeanDefinitionDefaults beanDefinitionDefaults = new BeanDefinitionDefaults(); + + private String[] autowireCandidatePatterns; + + private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator(); + + private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver(); + + private boolean includeAnnotationConfig = true; + + + /** + * Create a new ClassPathBeanDefinitionScanner for the given bean factory. + * @param registry the BeanFactory to load bean definitions into, + * in the form of a BeanDefinitionRegistry + */ + public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) { + this(registry, true); + } + + /** + * Create a new ClassPathBeanDefinitionScanner for the given bean factory. + *

    If the passed-in bean factory does not only implement the BeanDefinitionRegistry + * interface but also the ResourceLoader interface, it will be used as default + * ResourceLoader as well. This will usually be the case for + * {@link org.springframework.context.ApplicationContext} implementations. + *

    If given a plain BeanDefinitionRegistry, the default ResourceLoader will be a + * {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}. + * @param registry the BeanFactory to load bean definitions into, + * in the form of a BeanDefinitionRegistry + * @param useDefaultFilters whether to include the default filters for the + * {@link org.springframework.stereotype.Component @Component}, + * {@link org.springframework.stereotype.Repository @Repository}, + * {@link org.springframework.stereotype.Service @Service}, and + * {@link org.springframework.stereotype.Controller @Controller} stereotype + * annotations. + * @see #setResourceLoader + */ + public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) { + super(useDefaultFilters); + + Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); + this.registry = registry; + + // Determine ResourceLoader to use. + if (this.registry instanceof ResourceLoader) { + setResourceLoader((ResourceLoader) this.registry); + } + } + + + /** + * Return the BeanDefinitionRegistry that this scanner operates on. + */ + public final BeanDefinitionRegistry getRegistry() { + return this.registry; + } + + /** + * Set the defaults to use for detected beans. + * @see BeanDefinitionDefaults + */ + public void setBeanDefinitionDefaults(BeanDefinitionDefaults beanDefinitionDefaults) { + this.beanDefinitionDefaults = + (beanDefinitionDefaults != null ? beanDefinitionDefaults : new BeanDefinitionDefaults()); + } + + /** + * Set the name-matching patterns for determining autowire candidates. + * @param autowireCandidatePatterns the patterns to match against + */ + public void setAutowireCandidatePatterns(String[] autowireCandidatePatterns) { + this.autowireCandidatePatterns = autowireCandidatePatterns; + } + + /** + * Set the BeanNameGenerator to use for detected bean classes. + *

    Default is a {@link AnnotationBeanNameGenerator}. + */ + public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) { + this.beanNameGenerator = (beanNameGenerator != null ? beanNameGenerator : new AnnotationBeanNameGenerator()); + } + + /** + * Set the ScopeMetadataResolver to use for detected bean classes. + * Note that this will override any custom "scopedProxyMode" setting. + *

    The default is an {@link AnnotationScopeMetadataResolver}. + * @see #setScopedProxyMode + */ + public void setScopeMetadataResolver(ScopeMetadataResolver scopeMetadataResolver) { + this.scopeMetadataResolver = scopeMetadataResolver; + } + + /** + * Specify the proxy behavior for non-singleton scoped beans. + * Note that this will override any custom "scopeMetadataResolver" setting. + *

    The default is {@link ScopedProxyMode#NO}. + * @see #setScopeMetadataResolver + */ + public void setScopedProxyMode(ScopedProxyMode scopedProxyMode) { + this.scopeMetadataResolver = new AnnotationScopeMetadataResolver(scopedProxyMode); + } + + /** + * Specify whether to register annotation config post-processors. + *

    The default is to register the post-processors. Turn this off + * to be able to ignore the annotations or to process them differently. + */ + public void setIncludeAnnotationConfig(boolean includeAnnotationConfig) { + this.includeAnnotationConfig = includeAnnotationConfig; + } + + + /** + * Perform a scan within the specified base packages. + * @param basePackages the packages to check for annotated classes + * @return number of beans registered + */ + public int scan(String... basePackages) { + int beanCountAtScanStart = this.registry.getBeanDefinitionCount(); + + doScan(basePackages); + + // Register annotation config processors, if necessary. + if (this.includeAnnotationConfig) { + AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); + } + + return this.registry.getBeanDefinitionCount() - beanCountAtScanStart; + } + + /** + * Perform a scan within the specified base packages, + * returning the registered bean definitions. + *

    This method does not register an annotation config processor + * but rather leaves this up to the caller. + * @param basePackages the packages to check for annotated classes + * @return number of beans registered + */ + protected Set doScan(String... basePackages) { + Set beanDefinitions = new LinkedHashSet(); + for (int i = 0; i < basePackages.length; i++) { + Set candidates = findCandidateComponents(basePackages[i]); + for (BeanDefinition candidate : candidates) { + String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry); + if (candidate instanceof AbstractBeanDefinition) { + postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName); + } + ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate); + if (checkCandidate(beanName, candidate)) { + BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName); + definitionHolder = applyScope(definitionHolder, scopeMetadata); + beanDefinitions.add(definitionHolder); + registerBeanDefinition(definitionHolder, this.registry); + } + } + } + return beanDefinitions; + } + + /** + * Apply further settings to the given bean definition, + * beyond the contents retrieved from scanning the component class. + * @param beanDefinition the scanned bean definition + * @param beanName the generated bean name for the given bean + */ + protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) { + beanDefinition.applyDefaults(this.beanDefinitionDefaults); + if (this.autowireCandidatePatterns != null) { + beanDefinition.setAutowireCandidate(PatternMatchUtils.simpleMatch(this.autowireCandidatePatterns, beanName)); + } + } + + /** + * Register the specified bean with the given registry. + *

    Can be overridden in subclasses, e.g. to adapt the registration + * process or to register further bean definitions for each scanned bean. + * @param definitionHolder the bean definition plus bean name for the bean + * @param registry the BeanDefinitionRegistry to register the bean with + */ + protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) { + BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry); + } + + + /** + * Check the given candidate's bean name, determining whether the corresponding + * bean definition needs to be registered or conflicts with an existing definition. + * @param beanName the suggested name for the bean + * @param beanDefinition the corresponding bean definition + * @return true if the bean can be registered as-is; + * false if it should be skipped because there is an + * existing, compatible bean definition for the specified name + * @throws IllegalStateException if an existing, incompatible + * bean definition has been found for the specified name + */ + protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException { + if (!this.registry.containsBeanDefinition(beanName)) { + return true; + } + BeanDefinition existingDef = this.registry.getBeanDefinition(beanName); + BeanDefinition originatingDef = existingDef.getOriginatingBeanDefinition(); + if (originatingDef != null) { + existingDef = originatingDef; + } + if (isCompatible(beanDefinition, existingDef)) { + return false; + } + throw new IllegalStateException("Annotation-specified bean name '" + beanName + + "' for bean class [" + beanDefinition.getBeanClassName() + "] conflicts with existing, " + + "non-compatible bean definition of same name and class [" + existingDef.getBeanClassName() + "]"); + } + + /** + * Determine whether the given new bean definition is compatible with + * the given existing bean definition. + *

    The default implementation simply considers them as compatible + * when the bean class name matches. + * @param newDefinition the new bean definition, originated from scanning + * @param existingDefinition the existing bean definition, potentially an + * explicitly defined one or a previously generated one from scanning + * @return whether the definitions are considered as compatible, with the + * new definition to be skipped in favor of the existing definition + */ + protected boolean isCompatible(BeanDefinition newDefinition, BeanDefinition existingDefinition) { + return (!(existingDefinition instanceof AnnotatedBeanDefinition) || // explicitly registered overriding bean + newDefinition.getSource().equals(existingDefinition.getSource()) || // scanned same file twice + newDefinition.equals(existingDefinition)); // scanned equivalent class twice + } + + /** + * Apply the specified scope to the given bean definition. + * @param definitionHolder the bean definition to configure + * @param scopeMetadata the corresponding scope metadata + * @return the final bean definition to use (potentially a proxy) + */ + private BeanDefinitionHolder applyScope(BeanDefinitionHolder definitionHolder, ScopeMetadata scopeMetadata) { + String scope = scopeMetadata.getScopeName(); + ScopedProxyMode scopedProxyMode = scopeMetadata.getScopedProxyMode(); + definitionHolder.getBeanDefinition().setScope(scope); + if (BeanDefinition.SCOPE_SINGLETON.equals(scope) || BeanDefinition.SCOPE_PROTOTYPE.equals(scope) || + scopedProxyMode.equals(ScopedProxyMode.NO)) { + return definitionHolder; + } + boolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS); + return ScopedProxyCreator.createScopedProxy(definitionHolder, this.registry, proxyTargetClass); + } + + + /** + * Inner factory class used to just introduce an AOP framework dependency + * when actually creating a scoped proxy. + */ + private static class ScopedProxyCreator { + + public static BeanDefinitionHolder createScopedProxy( + BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry, boolean proxyTargetClass) { + + return ScopedProxyUtils.createScopedProxy(definitionHolder, registry, proxyTargetClass); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.java 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,270 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import java.io.IOException; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.ResourceLoaderAware; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternUtils; +import org.springframework.core.type.classreading.CachingMetadataReaderFactory; +import org.springframework.core.type.classreading.MetadataReader; +import org.springframework.core.type.classreading.MetadataReaderFactory; +import org.springframework.core.type.filter.AnnotationTypeFilter; +import org.springframework.core.type.filter.TypeFilter; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Controller; +import org.springframework.stereotype.Repository; +import org.springframework.stereotype.Service; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.SystemPropertyUtils; + +/** + * A component provider that scans the classpath from a base package. It then + * applies exclude and include filters to the resulting classes to find candidates. + * + *

    This implementation is based on Spring's + * {@link org.springframework.core.type.classreading.MetadataReader MetadataReader} + * facility, backed by an ASM {@link org.objectweb.asm.ClassReader ClassReader}. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @author Ramnivas Laddad + * @since 2.5 + * @see org.springframework.core.type.classreading.MetadataReaderFactory + * @see org.springframework.core.type.AnnotationMetadata + * @see ScannedGenericBeanDefinition + */ +public class ClassPathScanningCandidateComponentProvider implements ResourceLoaderAware { + + protected static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; + + + protected final Log logger = LogFactory.getLog(getClass()); + + private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); + + private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver); + + private String resourcePattern = DEFAULT_RESOURCE_PATTERN; + + private final List includeFilters = new LinkedList(); + + private final List excludeFilters = new LinkedList(); + + + /** + * Create a ClassPathScanningCandidateComponentProvider. + * @param useDefaultFilters whether to register the default filters for the + * {@link Component @Component}, {@link Repository @Repository}, + * {@link Service @Service}, and {@link Controller @Controller} + * stereotype annotations + * @see #registerDefaultFilters() + */ + public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters) { + if (useDefaultFilters) { + registerDefaultFilters(); + } + } + + + /** + * Set the ResourceLoader to use for resource locations. + * This will typically be a ResourcePatternResolver implementation. + *

    Default is PathMatchingResourcePatternResolver, also capable of + * resource pattern resolving through the ResourcePatternResolver interface. + * @see org.springframework.core.io.support.ResourcePatternResolver + * @see org.springframework.core.io.support.PathMatchingResourcePatternResolver + */ + public void setResourceLoader(ResourceLoader resourceLoader) { + this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader); + this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader); + } + + /** + * Return the ResourceLoader that this component provider uses. + */ + public final ResourceLoader getResourceLoader() { + return this.resourcePatternResolver; + } + + /** + * Set the resource pattern to use when scanning the classpath. + * This value will be appended to each base package name. + * @see #findCandidateComponents(String) + * @see #DEFAULT_RESOURCE_PATTERN + */ + public void setResourcePattern(String resourcePattern) { + Assert.notNull(resourcePattern, "'resourcePattern' must not be null"); + this.resourcePattern = resourcePattern; + } + + /** + * Add an include type filter to the end of the inclusion list. + */ + public void addIncludeFilter(TypeFilter includeFilter) { + this.includeFilters.add(includeFilter); + } + + /** + * Add an exclude type filter to the front of the exclusion list. + */ + public void addExcludeFilter(TypeFilter excludeFilter) { + this.excludeFilters.add(0, excludeFilter); + } + + /** + * Reset the configured type filters. + * @param useDefaultFilters whether to re-register the default filters for + * the {@link Component @Component}, {@link Repository @Repository}, + * {@link Service @Service}, and {@link Controller @Controller} + * stereotype annotations + * @see #registerDefaultFilters() + */ + public void resetFilters(boolean useDefaultFilters) { + this.includeFilters.clear(); + this.excludeFilters.clear(); + if (useDefaultFilters) { + registerDefaultFilters(); + } + } + + /** + * Register the default filter for {@link Component @Component}. + * This will implicitly register all annotations that have the + * {@link Component @Component} meta-annotation including the + * {@link Repository @Repository}, {@link Service @Service}, and + * {@link Controller @Controller} stereotype annotations. + */ + protected void registerDefaultFilters() { + this.includeFilters.add(new AnnotationTypeFilter(Component.class)); + } + + + /** + * Scan the class path for candidate components. + * @param basePackage the package to check for annotated classes + * @return a corresponding Set of autodetected bean definitions + */ + public Set findCandidateComponents(String basePackage) { + Set candidates = new LinkedHashSet(); + try { + String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + + resolveBasePackage(basePackage) + "/" + this.resourcePattern; + Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath); + boolean traceEnabled = logger.isTraceEnabled(); + boolean debugEnabled = logger.isDebugEnabled(); + for (int i = 0; i < resources.length; i++) { + Resource resource = resources[i]; + if (traceEnabled) { + logger.trace("Scanning " + resource); + } + if (resource.isReadable()) { + MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource); + if (isCandidateComponent(metadataReader)) { + ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader); + sbd.setResource(resource); + sbd.setSource(resource); + if (isCandidateComponent(sbd)) { + if (debugEnabled) { + logger.debug("Identified candidate component class: " + resource); + } + candidates.add(sbd); + } + else { + if (debugEnabled) { + logger.debug("Ignored because not a concrete top-level class: " + resource); + } + } + } + else { + if (traceEnabled) { + logger.trace("Ignored because not matching any filter: " + resource); + } + } + } + else { + if (traceEnabled) { + logger.trace("Ignored because not readable: " + resource); + } + } + } + } + catch (IOException ex) { + throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex); + } + return candidates; + } + + /** + * Resolve the specified base package into a pattern specification for + * the package search path. + *

    The default implementation resolves placeholders against system properties, + * and converts a "."-based package path to a "/"-based resource path. + * @param basePackage the base package as specified by the user + * @return the pattern specification to be used for package searching + */ + protected String resolveBasePackage(String basePackage) { + return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage)); + } + + /** + * Determine whether the given class does not match any exclude filter + * and does match at least one include filter. + * @param metadataReader the ASM ClassReader for the class + * @return whether the class qualifies as a candidate component + */ + protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException { + for (TypeFilter tf : this.excludeFilters) { + if (tf.match(metadataReader, this.metadataReaderFactory)) { + return false; + } + } + for (TypeFilter tf : this.includeFilters) { + if (tf.match(metadataReader, this.metadataReaderFactory)) { + return true; + } + } + return false; + } + + /** + * Determine whether the given bean definition qualifies as candidate. + *

    The default implementation checks whether the class is concrete + * (i.e. not abstract and not an interface). Can be overridden in subclasses. + * @param beanDefinition the bean definition to check + * @return whether the bean definition qualifies as a candidate component + */ + protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { + return (beanDefinition.getMetadata().isConcrete() && beanDefinition.getMetadata().isIndependent()); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,712 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.io.Serializable; +import java.lang.annotation.Annotation; +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.annotation.Resource; +import javax.ejb.EJB; +import javax.xml.namespace.QName; +import javax.xml.ws.Service; +import javax.xml.ws.WebServiceClient; +import javax.xml.ws.WebServiceRef; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.PropertyValues; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor; +import org.springframework.beans.factory.annotation.InjectionMetadata; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.beans.factory.config.DependencyDescriptor; +import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.core.MethodParameter; +import org.springframework.core.Ordered; +import org.springframework.jndi.support.SimpleJndiBeanFactory; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; + +/** + * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation + * that supports common Java annotations out of the box, in particular the JSR-250 + * annotations in the javax.annotation package. These common Java + * annotations are supported in many Java EE 5 technologies (e.g. JSF 1.2), + * as well as in Java 6's JAX-WS. + * + *

    This post-processor includes support for the {@link javax.annotation.PostConstruct} + * and {@link javax.annotation.PreDestroy} annotations - as init annotation + * and destroy annotation, respectively - through inheriting from + * {@link InitDestroyAnnotationBeanPostProcessor} with pre-configured annotation types. + * + *

    The central element is the {@link javax.annotation.Resource} annotation + * for annotation-driven injection of named beans, by default from the containing + * Spring BeanFactory, with only mappedName references resolved in JNDI. + * The {@link #setAlwaysUseJndiLookup "alwaysUseJndiLookup" flag} enforces JNDI lookups + * equivalent to standard Java EE 5 resource injection for name references + * and default names as well. The target beans can be simple POJOs, with no special + * requirements other than the type having to match. + * + *

    The JAX-WS {@link javax.xml.ws.WebServiceRef} annotation is supported too, + * analogous to {@link javax.annotation.Resource} but with the capability of creating + * specific JAX-WS service endpoints. This may either point to an explicitly defined + * resource by name or operate on a locally specified JAX-WS service class. Finally, + * this post-processor also supports the EJB 3 {@link javax.ejb.EJB} annotation, + * analogous to {@link javax.annotation.Resource} as well, with the capability to + * specify both a local bean name and a global JNDI name for fallback retrieval. + * The target beans can be plain POJOs as well as EJB 3 Session Beans in this case. + * + *

    The common annotations supported by this post-processor are available + * in Java 6 (JDK 1.6) as well as in Java EE 5 (which provides a standalone jar for + * its common annotations as well, allowing for use in any Java 5 based application). + * Hence, this post-processor works out of the box on JDK 1.6, and requires the + * JSR-250 API jar (and optionally the JAX-WS API jar and/or the EJB 3 API jar) + * to be added to the classpath on JDK 1.5 (when running outside of Java EE 5). + * + *

    For default usage, resolving resource names as Spring bean names, + * simply define the following in your application context: + * + *

    + * <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
    + * + * For direct JNDI access, resolving resource names as JNDI resource references + * within the Java EE application's "java:comp/env/" namespace, use the following: + * + *
    + * <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
    + *   <property name="alwaysUseJndiLookup" value="true"/>
    + * </bean>
    + * + * mappedName references will always be resolved in JNDI, + * allowing for global JNDI names (including "java:" prefix) as well. The + * "alwaysUseJndiLookup" flag just affects name references and + * default names (inferred from the field name / property name). + * + *

    NOTE: A default CommonAnnotationBeanPostProcessor will be registered + * by the "context:annotation-config" and "context:component-scan" XML tags. + * Remove or turn off the default annotation configuration there if you intend + * to specify a custom CommonAnnotationBeanPostProcessor bean definition! + * + * @author Juergen Hoeller + * @since 2.5 + * @see #setAlwaysUseJndiLookup + * @see #setResourceFactory + * @see org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor + * @see org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor + */ +public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor + implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable { + + private static Class webServiceRefClass = null; + + private static Class ejbRefClass = null; + + static { + try { + webServiceRefClass = ClassUtils.forName("javax.xml.ws.WebServiceRef", + CommonAnnotationBeanPostProcessor.class.getClassLoader()); + } + catch (ClassNotFoundException ex) { + webServiceRefClass = null; + } + try { + ejbRefClass = ClassUtils.forName("javax.ejb.EJB", + CommonAnnotationBeanPostProcessor.class.getClassLoader()); + } + catch (ClassNotFoundException ex) { + ejbRefClass = null; + } + } + + + private final Set ignoredResourceTypes = new HashSet(1); + + private boolean fallbackToDefaultTypeMatch = true; + + private boolean alwaysUseJndiLookup = false; + + private transient BeanFactory jndiFactory = new SimpleJndiBeanFactory(); + + private transient BeanFactory resourceFactory; + + private transient BeanFactory beanFactory; + + private transient final Map, InjectionMetadata> injectionMetadataCache = + new ConcurrentHashMap, InjectionMetadata>(); + + + /** + * Create a new CommonAnnotationBeanPostProcessor, + * with the init and destroy annotation types set to + * {@link javax.annotation.PostConstruct} and {@link javax.annotation.PreDestroy}, + * respectively. + */ + public CommonAnnotationBeanPostProcessor() { + setOrder(Ordered.LOWEST_PRECEDENCE - 3); + setInitAnnotationType(PostConstruct.class); + setDestroyAnnotationType(PreDestroy.class); + ignoreResourceType("javax.xml.ws.WebServiceContext"); + } + + + /** + * Ignore the given resource type when resolving @Resource + * annotations. + *

    By default, the javax.xml.ws.WebServiceContext interface + * will be ignored, since it will be resolved by the JAX-WS runtime. + * @param resourceType the resource type to ignore + */ + public void ignoreResourceType(String resourceType) { + Assert.notNull(resourceType, "Ignored resource type must not be null"); + this.ignoredResourceTypes.add(resourceType); + } + + /** + * Set whether to allow a fallback to a type match if no explicit name has been + * specified. The default name (i.e. the field name or bean property name) will + * still be checked first; if a bean of that name exists, it will be taken. + * However, if no bean of that name exists, a by-type resolution of the + * dependency will be attempted if this flag is "true". + *

    Default is "true". Switch this flag to "false" in order to enforce a + * by-name lookup in all cases, throwing an exception in case of no name match. + * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#resolveDependency + */ + public void setFallbackToDefaultTypeMatch(boolean fallbackToDefaultTypeMatch) { + this.fallbackToDefaultTypeMatch = fallbackToDefaultTypeMatch; + } + + /** + * Set whether to always use JNDI lookups equivalent to standard Java EE 5 resource + * injection, even for name attributes and default names. + *

    Default is "false": Resource names are used for Spring bean lookups in the + * containing BeanFactory; only mappedName attributes point directly + * into JNDI. Switch this flag to "true" for enforcing Java EE style JNDI lookups + * in any case, even for name attributes and default names. + * @see #setJndiFactory + * @see #setResourceFactory + */ + public void setAlwaysUseJndiLookup(boolean alwaysUseJndiLookup) { + this.alwaysUseJndiLookup = alwaysUseJndiLookup; + } + + /** + * Specify the factory for objects to be injected into @Resource / + * @WebServiceRef / @EJB annotated fields and setter methods, + * for mappedName attributes that point directly into JNDI. + * This factory will also be used if "alwaysUseJndiLookup" is set to "true" in order + * to enforce JNDI lookups even for name attributes and default names. + *

    The default is a {@link org.springframework.jndi.support.SimpleJndiBeanFactory} + * for JNDI lookup behavior equivalent to standard Java EE 5 resource injection. + * @see #setResourceFactory + * @see #setAlwaysUseJndiLookup + */ + public void setJndiFactory(BeanFactory jndiFactory) { + Assert.notNull(jndiFactory, "BeanFactory must not be null"); + this.jndiFactory = jndiFactory; + } + + /** + * Specify the factory for objects to be injected into @Resource / + * @WebServiceRef / @EJB annotated fields and setter methods, + * for name attributes and default names. + *

    The default is the BeanFactory that this post-processor is defined in, + * if any, looking up resource names as Spring bean names. Specify the resource + * factory explicitly for programmatic usage of this post-processor. + *

    Specifying Spring's {@link org.springframework.jndi.support.SimpleJndiBeanFactory} + * leads to JNDI lookup behavior equivalent to standard Java EE 5 resource injection, + * even for name attributes and default names. This is the same behavior + * that the "alwaysUseJndiLookup" flag enables. + * @see #setAlwaysUseJndiLookup + */ + public void setResourceFactory(BeanFactory resourceFactory) { + Assert.notNull(resourceFactory, "BeanFactory must not be null"); + this.resourceFactory = resourceFactory; + } + + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + Assert.notNull(beanFactory, "BeanFactory must not be null"); + this.beanFactory = beanFactory; + if (this.resourceFactory == null) { + this.resourceFactory = beanFactory; + } + } + + + public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) { + super.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName); + if (beanType != null) { + InjectionMetadata metadata = findResourceMetadata(beanType); + metadata.checkConfigMembers(beanDefinition); + } + } + + public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException { + return null; + } + + public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { + InjectionMetadata metadata = findResourceMetadata(bean.getClass()); + try { + metadata.injectFields(bean, beanName); + } + catch (Throwable ex) { + throw new BeanCreationException(beanName, "Injection of resource fields failed", ex); + } + return true; + } + + public PropertyValues postProcessPropertyValues( + PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { + + InjectionMetadata metadata = findResourceMetadata(bean.getClass()); + try { + metadata.injectMethods(bean, beanName, pvs); + } + catch (Throwable ex) { + throw new BeanCreationException(beanName, "Injection of resource methods failed", ex); + } + return pvs; + } + + + private InjectionMetadata findResourceMetadata(final Class clazz) { + // Quick check on the concurrent map first, with minimal locking. + InjectionMetadata metadata = this.injectionMetadataCache.get(clazz); + if (metadata == null) { + synchronized (this.injectionMetadataCache) { + metadata = this.injectionMetadataCache.get(clazz); + if (metadata == null) { + final InjectionMetadata newMetadata = new InjectionMetadata(clazz); + ReflectionUtils.doWithFields(clazz, new ReflectionUtils.FieldCallback() { + public void doWith(Field field) { + if (webServiceRefClass != null && field.isAnnotationPresent(webServiceRefClass)) { + if (Modifier.isStatic(field.getModifiers())) { + throw new IllegalStateException("@WebServiceRef annotation is not supported on static fields"); + } + newMetadata.addInjectedField(new WebServiceRefElement(field, null)); + } + else if (ejbRefClass != null && field.isAnnotationPresent(ejbRefClass)) { + if (Modifier.isStatic(field.getModifiers())) { + throw new IllegalStateException("@EJB annotation is not supported on static fields"); + } + newMetadata.addInjectedField(new EjbRefElement(field, null)); + } + else if (field.isAnnotationPresent(Resource.class)) { + if (Modifier.isStatic(field.getModifiers())) { + throw new IllegalStateException("@Resource annotation is not supported on static fields"); + } + if (!ignoredResourceTypes.contains(field.getType().getName())) { + newMetadata.addInjectedField(new ResourceElement(field, null)); + } + } + } + }); + ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() { + public void doWith(Method method) { + if (webServiceRefClass != null && method.isAnnotationPresent(webServiceRefClass) && + method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { + if (Modifier.isStatic(method.getModifiers())) { + throw new IllegalStateException("@WebServiceRef annotation is not supported on static methods"); + } + if (method.getParameterTypes().length != 1) { + throw new IllegalStateException("@WebServiceRef annotation requires a single-arg method: " + method); + } + PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method); + newMetadata.addInjectedMethod(new WebServiceRefElement(method, pd)); + } + else if (ejbRefClass != null && method.isAnnotationPresent(ejbRefClass) && + method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { + if (Modifier.isStatic(method.getModifiers())) { + throw new IllegalStateException("@EJB annotation is not supported on static methods"); + } + if (method.getParameterTypes().length != 1) { + throw new IllegalStateException("@EJB annotation requires a single-arg method: " + method); + } + PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method); + newMetadata.addInjectedMethod(new EjbRefElement(method, pd)); + } + else if (method.isAnnotationPresent(Resource.class) && + method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { + if (Modifier.isStatic(method.getModifiers())) { + throw new IllegalStateException("@Resource annotation is not supported on static methods"); + } + Class[] paramTypes = method.getParameterTypes(); + if (paramTypes.length != 1) { + throw new IllegalStateException("@Resource annotation requires a single-arg method: " + method); + } + if (!ignoredResourceTypes.contains(paramTypes[0].getName())) { + PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method); + newMetadata.addInjectedMethod(new ResourceElement(method, pd)); + } + } + } + }); + metadata = newMetadata; + this.injectionMetadataCache.put(clazz, metadata); + } + } + } + return metadata; + } + + /** + * Obtain the resource object for the given name and type. + * @param element the descriptor for the annotated field/method + * @param requestingBeanName the name of the requesting bean + * @return the resource object (never null) + * @throws BeansException if we failed to obtain the target resource + */ + protected Object getResource(LookupElement element, String requestingBeanName) throws BeansException { + if (StringUtils.hasLength(element.mappedName)) { + return this.jndiFactory.getBean(element.mappedName, element.lookupType); + } + if (this.alwaysUseJndiLookup) { + return this.jndiFactory.getBean(element.name, element.lookupType); + } + if (this.resourceFactory == null) { + throw new NoSuchBeanDefinitionException(element.lookupType, + "No resource factory configured - specify the 'resourceFactory' property"); + } + return autowireResource(this.resourceFactory, element, requestingBeanName); + } + + /** + * Obtain a resource object for the given name and type through autowiring + * based on the given factory. + * @param factory the factory to autowire against + * @param element the descriptor for the annotated field/method + * @param requestingBeanName the name of the requesting bean + * @return the resource object (never null) + * @throws BeansException if we failed to obtain the target resource + */ + protected Object autowireResource(BeanFactory factory, LookupElement element, String requestingBeanName) + throws BeansException { + + Object resource = null; + Set autowiredBeanNames = null; + String name = element.name; + + if (this.fallbackToDefaultTypeMatch && element.isDefaultName && + factory instanceof AutowireCapableBeanFactory && !factory.containsBean(name)) { + autowiredBeanNames = new LinkedHashSet(); + resource = ((AutowireCapableBeanFactory) factory).resolveDependency( + element.getDependencyDescriptor(), requestingBeanName, autowiredBeanNames, null); + } + else { + resource = factory.getBean(name, element.lookupType); + autowiredBeanNames = Collections.singleton(name); + } + + if (factory instanceof ConfigurableBeanFactory) { + ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) factory; + for (String autowiredBeanName : autowiredBeanNames) { + beanFactory.registerDependentBean(autowiredBeanName, requestingBeanName); + } + } + + return resource; + } + + + /** + * Class representing generic injection information about an annotated field + * or setter method, supporting @Resource and related annotations. + */ + protected abstract class LookupElement extends InjectionMetadata.InjectedElement { + + protected String name; + + protected boolean isDefaultName = false; + + protected Class lookupType; + + protected String mappedName; + + public LookupElement(Member member, PropertyDescriptor pd) { + super(member, pd); + initAnnotation((AnnotatedElement) member); + } + + protected abstract void initAnnotation(AnnotatedElement ae); + + /** + * Return the resource name for the lookup. + */ + public final String getName() { + return this.name; + } + + /** + * Return the desired type for the lookup. + */ + public final Class getLookupType() { + return this.lookupType; + } + + /** + * Build a DependencyDescriptor for the underlying field/method. + */ + public final DependencyDescriptor getDependencyDescriptor() { + if (this.isField) { + return new LookupDependencyDescriptor((Field) this.member, this.lookupType); + } + else { + return new LookupDependencyDescriptor((Method) this.member, this.lookupType); + } + } + } + + + /** + * Class representing injection information about an annotated field + * or setter method, supporting the @Resource annotation. + */ + private class ResourceElement extends LookupElement { + + protected boolean shareable = true; + + public ResourceElement(Member member, PropertyDescriptor pd) { + super(member, pd); + } + + protected void initAnnotation(AnnotatedElement ae) { + Resource resource = ae.getAnnotation(Resource.class); + String resourceName = resource.name(); + Class resourceType = resource.type(); + this.isDefaultName = !StringUtils.hasLength(resourceName); + if (this.isDefaultName) { + resourceName = this.member.getName(); + if (this.member instanceof Method && resourceName.startsWith("set") && resourceName.length() > 3) { + resourceName = Introspector.decapitalize(resourceName.substring(3)); + } + } + if (resourceType != null && !Object.class.equals(resourceType)) { + checkResourceType(resourceType); + } + else { + // No resource type specified... check field/method. + resourceType = getResourceType(); + } + this.name = resourceName; + this.lookupType = resourceType; + this.mappedName = resource.mappedName(); + this.shareable = resource.shareable(); + } + + @Override + protected Object getResourceToInject(Object target, String requestingBeanName) { + return getResource(this, requestingBeanName); + } + } + + + /** + * Class representing injection information about an annotated field + * or setter method, supporting the @WebServiceRef annotation. + */ + private class WebServiceRefElement extends LookupElement { + + private Class elementType; + + private String wsdlLocation; + + public WebServiceRefElement(Member member, PropertyDescriptor pd) { + super(member, pd); + } + + protected void initAnnotation(AnnotatedElement ae) { + WebServiceRef resource = ae.getAnnotation(WebServiceRef.class); + String resourceName = resource.name(); + Class resourceType = resource.type(); + this.isDefaultName = !StringUtils.hasLength(resourceName); + if (this.isDefaultName) { + resourceName = this.member.getName(); + if (this.member instanceof Method && resourceName.startsWith("set") && resourceName.length() > 3) { + resourceName = Introspector.decapitalize(resourceName.substring(3)); + } + } + if (resourceType != null && !Object.class.equals(resourceType)) { + checkResourceType(resourceType); + } + else { + // No resource type specified... check field/method. + resourceType = getResourceType(); + } + this.name = resourceName; + this.elementType = resourceType; + if (Service.class.isAssignableFrom(resourceType)) { + this.lookupType = resourceType; + } + else { + this.lookupType = (!Object.class.equals(resource.value()) ? resource.value() : Service.class); + } + this.mappedName = resource.mappedName(); + this.wsdlLocation = resource.wsdlLocation(); + } + + @Override + protected Object getResourceToInject(Object target, String requestingBeanName) { + Service service = null; + try { + service = (Service) getResource(this, requestingBeanName); + } + catch (NoSuchBeanDefinitionException notFound) { + // Service to be created through generated class. + if (Service.class.equals(this.lookupType)) { + throw new IllegalStateException("No resource with name '" + this.name + "' found in context, " + + "and no specific JAX-WS Service subclass specified. The typical solution is to either specify " + + "a LocalJaxWsServiceFactoryBean with the given name or to specify the (generated) Service " + + "subclass as @WebServiceRef(...) value."); + } + if (StringUtils.hasLength(this.wsdlLocation)) { + try { + Constructor ctor = this.lookupType.getConstructor(new Class[] {URL.class, QName.class}); + WebServiceClient clientAnn = this.lookupType.getAnnotation(WebServiceClient.class); + if (clientAnn == null) { + throw new IllegalStateException("JAX-WS Service class [" + this.lookupType.getName() + + "] does not carry a WebServiceClient annotation"); + } + service = (Service) BeanUtils.instantiateClass(ctor, + new Object[] {new URL(this.wsdlLocation), new QName(clientAnn.targetNamespace(), clientAnn.name())}); + } + catch (NoSuchMethodException ex) { + throw new IllegalStateException("JAX-WS Service class [" + this.lookupType.getName() + + "] does not have a (URL, QName) constructor. Cannot apply specified WSDL location [" + + this.wsdlLocation + "]."); + } + catch (MalformedURLException ex) { + throw new IllegalArgumentException( + "Specified WSDL location [" + this.wsdlLocation + "] isn't a valid URL"); + } + } + else { + service = (Service) BeanUtils.instantiateClass(this.lookupType); + } + } + return service.getPort(this.elementType); + } + } + + + /** + * Class representing injection information about an annotated field + * or setter method, supporting the @EJB annotation. + */ + private class EjbRefElement extends LookupElement { + + private String beanName; + + public EjbRefElement(Member member, PropertyDescriptor pd) { + super(member, pd); + } + + protected void initAnnotation(AnnotatedElement ae) { + EJB resource = ae.getAnnotation(EJB.class); + String resourceBeanName = resource.beanName(); + String resourceName = resource.name(); + this.isDefaultName = !StringUtils.hasLength(resourceName); + if (this.isDefaultName) { + resourceName = this.member.getName(); + if (this.member instanceof Method && resourceName.startsWith("set") && resourceName.length() > 3) { + resourceName = Introspector.decapitalize(resourceName.substring(3)); + } + } + Class resourceType = resource.beanInterface(); + if (resourceType != null && !Object.class.equals(resourceType)) { + checkResourceType(resourceType); + } + else { + // No resource type specified... check field/method. + resourceType = getResourceType(); + } + this.beanName = resourceBeanName; + this.name = resourceName; + this.lookupType = resourceType; + this.mappedName = resource.mappedName(); + } + + @Override + protected Object getResourceToInject(Object target, String requestingBeanName) { + if (StringUtils.hasLength(this.beanName)) { + if (beanFactory != null && beanFactory.containsBean(this.beanName)) { + // Local match found for explicitly specified local bean name. + Object bean = beanFactory.getBean(this.beanName, this.lookupType); + if (beanFactory instanceof ConfigurableBeanFactory) { + ((ConfigurableBeanFactory) beanFactory).registerDependentBean(this.beanName, requestingBeanName); + } + return bean; + } + else if (this.isDefaultName && !StringUtils.hasLength(this.mappedName)) { + throw new NoSuchBeanDefinitionException(this.beanName, + "Cannot resolve 'beanName' in local BeanFactory. Consider specifying a general 'name' value instead."); + } + } + // JNDI name lookup - may still go to a local BeanFactory. + return getResource(this, requestingBeanName); + } + } + + + /** + * Extension of the DependencyDescriptor class, + * overriding the dependency type with the specified resource type. + */ + private static class LookupDependencyDescriptor extends DependencyDescriptor { + + private final Class lookupType; + + public LookupDependencyDescriptor(Field field, Class lookupType) { + super(field, true); + this.lookupType = lookupType; + } + + public LookupDependencyDescriptor(Method method, Class lookupType) { + super(new MethodParameter(method, 0), true); + this.lookupType = lookupType; + } + + public Class getDependencyType() { + return this.lookupType; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,279 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import java.lang.annotation.Annotation; +import java.util.Iterator; +import java.util.Set; +import java.util.regex.Pattern; + +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import org.springframework.beans.BeanUtils; +import org.springframework.beans.FatalBeanException; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.parsing.CompositeComponentDefinition; +import org.springframework.beans.factory.support.BeanNameGenerator; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.beans.factory.xml.XmlReaderContext; +import org.springframework.core.type.filter.AnnotationTypeFilter; +import org.springframework.core.type.filter.AspectJTypeFilter; +import org.springframework.core.type.filter.AssignableTypeFilter; +import org.springframework.core.type.filter.RegexPatternTypeFilter; +import org.springframework.core.type.filter.TypeFilter; +import org.springframework.util.StringUtils; + +/** + * Parser for the <context:component-scan/> element. + * + * @author Mark Fisher + * @author Ramnivas Laddad + * @author Juergen Hoeller + * @since 2.5 + */ +public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser { + + private static final String BASE_PACKAGE_ATTRIBUTE = "base-package"; + + private static final String RESOURCE_PATTERN_ATTRIBUTE = "resource-pattern"; + + private static final String USE_DEFAULT_FILTERS_ATTRIBUTE = "use-default-filters"; + + private static final String ANNOTATION_CONFIG_ATTRIBUTE = "annotation-config"; + + private static final String NAME_GENERATOR_ATTRIBUTE = "name-generator"; + + private static final String SCOPE_RESOLVER_ATTRIBUTE = "scope-resolver"; + + private static final String SCOPED_PROXY_ATTRIBUTE = "scoped-proxy"; + + private static final String EXCLUDE_FILTER_ELEMENT = "exclude-filter"; + + private static final String INCLUDE_FILTER_ELEMENT = "include-filter"; + + private static final String FILTER_TYPE_ATTRIBUTE = "type"; + + private static final String FILTER_EXPRESSION_ATTRIBUTE = "expression"; + + + public BeanDefinition parse(Element element, ParserContext parserContext) { + String[] basePackages = + StringUtils.commaDelimitedListToStringArray(element.getAttribute(BASE_PACKAGE_ATTRIBUTE)); + + // Actually scan for bean definitions and register them. + ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element); + Set beanDefinitions = scanner.doScan(basePackages); + registerComponents(parserContext.getReaderContext(), beanDefinitions, element); + + return null; + } + + protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) { + XmlReaderContext readerContext = parserContext.getReaderContext(); + + boolean useDefaultFilters = true; + if (element.hasAttribute(USE_DEFAULT_FILTERS_ATTRIBUTE)) { + useDefaultFilters = Boolean.valueOf(element.getAttribute(USE_DEFAULT_FILTERS_ATTRIBUTE)); + } + + // Delegate bean definition registration to scanner class. + ClassPathBeanDefinitionScanner scanner = createScanner(readerContext, useDefaultFilters); + scanner.setResourceLoader(readerContext.getResourceLoader()); + scanner.setBeanDefinitionDefaults(parserContext.getDelegate().getBeanDefinitionDefaults()); + scanner.setAutowireCandidatePatterns(parserContext.getDelegate().getAutowireCandidatePatterns()); + + if (element.hasAttribute(RESOURCE_PATTERN_ATTRIBUTE)) { + scanner.setResourcePattern(element.getAttribute(RESOURCE_PATTERN_ATTRIBUTE)); + } + + try { + parseBeanNameGenerator(element, scanner); + } + catch (Exception ex) { + readerContext.error(ex.getMessage(), readerContext.extractSource(element), ex.getCause()); + } + + try { + parseScope(element, scanner); + } + catch (Exception ex) { + readerContext.error(ex.getMessage(), readerContext.extractSource(element), ex.getCause()); + } + + parseTypeFilters(element, scanner, readerContext); + + return scanner; + } + + protected ClassPathBeanDefinitionScanner createScanner(XmlReaderContext readerContext, boolean useDefaultFilters) { + return new ClassPathBeanDefinitionScanner(readerContext.getRegistry(), useDefaultFilters); + } + + protected void registerComponents( + XmlReaderContext readerContext, Set beanDefinitions, Element element) { + + Object source = readerContext.extractSource(element); + CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source); + + for (Iterator it = beanDefinitions.iterator(); it.hasNext();) { + BeanDefinitionHolder beanDefHolder = (BeanDefinitionHolder) it.next(); + compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder)); + } + + // Register annotation config processors, if necessary. + boolean annotationConfig = true; + if (element.hasAttribute(ANNOTATION_CONFIG_ATTRIBUTE)) { + annotationConfig = Boolean.valueOf(element.getAttribute(ANNOTATION_CONFIG_ATTRIBUTE)); + } + if (annotationConfig) { + Set processorDefinitions = + AnnotationConfigUtils.registerAnnotationConfigProcessors(readerContext.getRegistry(), source); + for (BeanDefinitionHolder processorDefinition : processorDefinitions) { + compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition)); + } + } + + readerContext.fireComponentRegistered(compositeDef); + } + + protected void parseBeanNameGenerator(Element element, ClassPathBeanDefinitionScanner scanner) { + if (element.hasAttribute(NAME_GENERATOR_ATTRIBUTE)) { + BeanNameGenerator beanNameGenerator = (BeanNameGenerator) instantiateUserDefinedStrategy( + element.getAttribute(NAME_GENERATOR_ATTRIBUTE), BeanNameGenerator.class, + scanner.getResourceLoader().getClassLoader()); + scanner.setBeanNameGenerator(beanNameGenerator); + } + } + + protected void parseScope(Element element, ClassPathBeanDefinitionScanner scanner) { + // Register ScopeMetadataResolver if class name provided. + if (element.hasAttribute(SCOPE_RESOLVER_ATTRIBUTE)) { + if (element.hasAttribute(SCOPED_PROXY_ATTRIBUTE)) { + throw new IllegalArgumentException( + "Cannot define both 'scope-resolver' and 'scoped-proxy' on tag"); + } + ScopeMetadataResolver scopeMetadataResolver = (ScopeMetadataResolver) instantiateUserDefinedStrategy( + element.getAttribute(SCOPE_RESOLVER_ATTRIBUTE), ScopeMetadataResolver.class, + scanner.getResourceLoader().getClassLoader()); + scanner.setScopeMetadataResolver(scopeMetadataResolver); + } + + if (element.hasAttribute(SCOPED_PROXY_ATTRIBUTE)) { + String mode = element.getAttribute(SCOPED_PROXY_ATTRIBUTE); + if ("targetClass".equals(mode)) { + scanner.setScopedProxyMode(ScopedProxyMode.TARGET_CLASS); + } + else if ("interfaces".equals(mode)) { + scanner.setScopedProxyMode(ScopedProxyMode.INTERFACES); + } + else if ("no".equals(mode)) { + scanner.setScopedProxyMode(ScopedProxyMode.NO); + } + else { + throw new IllegalArgumentException("scoped-proxy only supports 'no', 'interfaces' and 'targetClass'"); + } + } + } + + protected void parseTypeFilters( + Element element, ClassPathBeanDefinitionScanner scanner, XmlReaderContext readerContext) { + + // Parse exclude and include filter elements. + ClassLoader classLoader = scanner.getResourceLoader().getClassLoader(); + NodeList nodeList = element.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + String localName = node.getLocalName(); + try { + if (INCLUDE_FILTER_ELEMENT.equals(localName)) { + TypeFilter typeFilter = createTypeFilter((Element) node, classLoader); + scanner.addIncludeFilter(typeFilter); + } + else if (EXCLUDE_FILTER_ELEMENT.equals(localName)) { + TypeFilter typeFilter = createTypeFilter((Element) node, classLoader); + scanner.addExcludeFilter(typeFilter); + } + } + catch (Exception ex) { + readerContext.error(ex.getMessage(), readerContext.extractSource(element), ex.getCause()); + } + } + } + } + + @SuppressWarnings("unchecked") + protected TypeFilter createTypeFilter(Element element, ClassLoader classLoader) { + String filterType = element.getAttribute(FILTER_TYPE_ATTRIBUTE); + String expression = element.getAttribute(FILTER_EXPRESSION_ATTRIBUTE); + try { + if ("annotation".equals(filterType)) { + return new AnnotationTypeFilter((Class) classLoader.loadClass(expression)); + } + else if ("assignable".equals(filterType)) { + return new AssignableTypeFilter(classLoader.loadClass(expression)); + } + else if ("aspectj".equals(filterType)) { + return new AspectJTypeFilter(expression, classLoader); + } + else if ("regex".equals(filterType)) { + return new RegexPatternTypeFilter(Pattern.compile(expression)); + } + else if ("custom".equals(filterType)) { + Class filterClass = classLoader.loadClass(expression); + if (!TypeFilter.class.isAssignableFrom(filterClass)) { + throw new IllegalArgumentException( + "Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression); + } + return (TypeFilter) BeanUtils.instantiateClass(filterClass); + } + else { + throw new IllegalArgumentException("Unsupported filter type: " + filterType); + } + } + catch (ClassNotFoundException ex) { + throw new FatalBeanException("Type filter class not found: " + expression, ex); + } + } + + @SuppressWarnings("unchecked") + private Object instantiateUserDefinedStrategy(String className, Class strategyType, ClassLoader classLoader) { + Object result = null; + try { + result = classLoader.loadClass(className).newInstance(); + } + catch (ClassNotFoundException ex) { + throw new IllegalArgumentException("Class [" + className + "] for strategy [" + + strategyType.getName() + "] not found", ex); + } + catch (Exception ex) { + throw new IllegalArgumentException("Unable to instantiate class [" + className + "] for strategy [" + + strategyType.getName() + "]. A zero-argument constructor is required", ex); + } + + if (!strategyType.isAssignableFrom(result.getClass())) { + throw new IllegalArgumentException("Provided class name must be an implementation of " + strategyType); + } + return result; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/FilterType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/FilterType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/FilterType.java 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +/** + * Enumeration of the valid type filters to be added for annotation-driven configuration. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + */ +public enum FilterType { + + ANNOTATION, + ASSIGNABLE_TYPE, + ASPECTJ_PATTERN, + REGEX_PATTERN, + CUSTOM + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/ScannedGenericBeanDefinition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/ScannedGenericBeanDefinition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/ScannedGenericBeanDefinition.java 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; +import org.springframework.beans.factory.support.GenericBeanDefinition; +import org.springframework.core.type.AnnotationMetadata; +import org.springframework.core.type.classreading.MetadataReader; +import org.springframework.util.Assert; + +/** + * Extension of the {@link org.springframework.beans.factory.support.GenericBeanDefinition} + * class, based on an ASM ClassReader, with support for annotation metadata exposed + * through the {@link AnnotatedBeanDefinition} interface. + * + *

    This class does not load the bean Class early. + * It rather retrieves all relevant metadata from the ".class" file itself, + * parsed with the ASM ClassReader. + * + * @author Juergen Hoeller + * @since 2.5 + * @see #getMetadata() + * @see #getBeanClassName() + * @see org.springframework.core.type.classreading.MetadataReaderFactory + */ +public class ScannedGenericBeanDefinition extends GenericBeanDefinition implements AnnotatedBeanDefinition { + + private final AnnotationMetadata metadata; + + + /** + * Create a new ScannedGenericBeanDefinition for the class that the + * given MetadataReader describes. + * @param metadataReader the MetadataReader for the scanned target class + */ + public ScannedGenericBeanDefinition(MetadataReader metadataReader) { + Assert.notNull(metadataReader, "MetadataReader must not be null"); + this.metadata = metadataReader.getAnnotationMetadata(); + setBeanClassName(this.metadata.getClassName()); + } + + + public final AnnotationMetadata getMetadata() { + return this.metadata; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/Scope.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/Scope.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/Scope.java 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.springframework.beans.factory.config.BeanDefinition; + +/** + * Indicates the name of a scope to use for instances of the annotated class. + * + *

    In this context, scope means the lifecycle of an instance, such as + * 'singleton', 'prototype', and so forth. + * + * @author Mark Fisher + * @since 2.5 + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface Scope { + + /** + * Specifies the scope to use for instances of the annotated class. + * @return the desired scope + */ + String value() default BeanDefinition.SCOPE_SINGLETON; + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/ScopeMetadata.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/ScopeMetadata.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/ScopeMetadata.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import org.springframework.beans.factory.config.BeanDefinition; + +/** + * Describes scope characteristics for a Spring-managed bean including the scope + * name and the scoped-proxy behavior. + * + *

    The default scope is "singleton", and the default is to not create + * scoped-proxies. + * + * @author Mark Fisher + * @since 2.5 + * @see ScopeMetadataResolver + * @see ScopedProxyMode + */ +public class ScopeMetadata { + + private String scopeName = BeanDefinition.SCOPE_SINGLETON; + + private ScopedProxyMode scopedProxyMode = ScopedProxyMode.NO; + + + /** + * Get the name of the scope. + * @return said scope name + */ + public String getScopeName() { + return scopeName; + } + + /** + * Set the name of the scope. + * @param scopeName said scope name + */ + public void setScopeName(String scopeName) { + this.scopeName = scopeName; + } + + /** + * Get the proxy-mode to be applied to the scoped instance. + * @return said scoped-proxy mode + */ + public ScopedProxyMode getScopedProxyMode() { + return scopedProxyMode; + } + + /** + * Set the proxy-mode to be applied to the scoped instance. + * @param scopedProxyMode said scoped-proxy mode + */ + public void setScopedProxyMode(ScopedProxyMode scopedProxyMode) { + this.scopedProxyMode = scopedProxyMode; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/ScopeMetadataResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/ScopeMetadataResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/ScopeMetadataResolver.java 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import org.springframework.beans.factory.config.BeanDefinition; + +/** + * Strategy interface for resolving the scope of bean definitions. + * + * @author Mark Fisher + * @since 2.5 + * @see Scope + */ +public interface ScopeMetadataResolver { + + /** + * Resolve the {@link ScopeMetadata} appropriate to the supplied + * bean definition. + *

    Implementations can of course use any strategy they like to + * determine the scope metadata, but some implementations that spring + * immediately to mind might be to use source level annotations + * present on {@link BeanDefinition#getBeanClassName() the class} of the + * supplied definition, or to use metadata present in the + * {@link BeanDefinition#attributeNames()} of the supplied definition. + * @param definition the target bean definition + * @return the relevant scope metadata; never null + */ + ScopeMetadata resolveScopeMetadata(BeanDefinition definition); + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/ScopedProxyMode.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/ScopedProxyMode.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/ScopedProxyMode.java 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +/** + * Enumerates the various scoped-proxy options. + * + *

    For a fuller discussion of exactly what a scoped-proxy is, see that + * section of the Spring reference documentation entitled 'Scoped beans as + * dependencies'. + * + * @author Mark Fisher + * @since 2.5 + * @see ScopeMetadata + */ +public enum ScopedProxyMode { + + /** + * Do not create a scoped proxy. + *

    This proxy-mode is not typically useful when used with a + * non-singleton scoped instance, which should favor the use of the + * {@link #INTERFACES} or {@link #TARGET_CLASS} proxy-modes instead if it + * is to be used as a dependency. + */ + NO, + + /** + * Create a JDK dynamic proxy implementing all interfaces exposed by + * the class of the target object. + */ + INTERFACES, + + /** + * Create a class-based proxy (requires CGLIB). + */ + TARGET_CLASS + +} Index: 3rdParty_sources/spring/org/springframework/context/annotation/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/annotation/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/annotation/package.html 17 Aug 2012 15:14:38 -0000 1.1 @@ -0,0 +1,8 @@ + + + +Annotation support for context configuration, +including classpath scanning for autowire candidates. + + + Index: 3rdParty_sources/spring/org/springframework/context/config/AbstractPropertyLoadingBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/config/AbstractPropertyLoadingBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/config/AbstractPropertyLoadingBeanDefinitionParser.java 17 Aug 2012 15:14:29 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; +import org.springframework.util.StringUtils; + +/** + * Abstract parser for <context:property-.../> elements. + * + * @author Juergen Hoeller + * @author Arjen Poutsma + * @since 2.5.2 + */ +abstract class AbstractPropertyLoadingBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { + + protected boolean shouldGenerateId() { + return true; + } + + protected void doParse(Element element, BeanDefinitionBuilder builder) { + String location = element.getAttribute("location"); + if (StringUtils.hasLength(location)) { + String[] locations = StringUtils.commaDelimitedListToStringArray(location); + builder.addPropertyValue("locations", locations); + } + String propertiesRef = element.getAttribute("properties-ref"); + if (StringUtils.hasLength(propertiesRef)) { + builder.addPropertyReference("properties", propertiesRef); + } + builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + } + +} \ No newline at end of file Index: 3rdParty_sources/spring/org/springframework/context/config/ContextNamespaceHandler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/config/ContextNamespaceHandler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/config/ContextNamespaceHandler.java 17 Aug 2012 15:14:29 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.NamespaceHandlerSupport; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.core.JdkVersion; +import org.springframework.util.ClassUtils; + +/** + * {@link org.springframework.beans.factory.xml.NamespaceHandler} + * for the 'context' namespace. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + */ +public class ContextNamespaceHandler extends NamespaceHandlerSupport { + + public void init() { + registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser()); + registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser()); + registerJava5DependentParser("annotation-config", + "org.springframework.context.annotation.AnnotationConfigBeanDefinitionParser"); + registerJava5DependentParser("component-scan", + "org.springframework.context.annotation.ComponentScanBeanDefinitionParser"); + registerBeanDefinitionParser("load-time-weaver", new LoadTimeWeaverBeanDefinitionParser()); + registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser()); + registerBeanDefinitionParser("mbean-export", new MBeanExportBeanDefinitionParser()); + registerBeanDefinitionParser("mbean-server", new MBeanServerBeanDefinitionParser()); + } + + private void registerJava5DependentParser(final String elementName, final String parserClassName) { + BeanDefinitionParser parser = null; + if (JdkVersion.isAtLeastJava15()) { + try { + Class parserClass = ClassUtils.forName(parserClassName, ContextNamespaceHandler.class.getClassLoader()); + parser = (BeanDefinitionParser) parserClass.newInstance(); + } + catch (Throwable ex) { + throw new IllegalStateException("Unable to create Java 1.5 dependent parser: " + parserClassName, ex); + } + } + else { + parser = new BeanDefinitionParser() { + public BeanDefinition parse(Element element, ParserContext parserContext) { + throw new IllegalStateException("Context namespace element '" + elementName + + "' and its parser class [" + parserClassName + "] are only available on JDK 1.5 and higher"); + } + }; + } + registerBeanDefinitionParser(elementName, parser); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/config/LoadTimeWeaverBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/config/LoadTimeWeaverBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/config/LoadTimeWeaverBeanDefinitionParser.java 17 Aug 2012 15:14:29 -0000 1.1 @@ -0,0 +1,95 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.util.ClassUtils; + +/** + * Parser for the <context:load-time-weaver/> element. + * + * @author Juergen Hoeller + * @since 2.5 + */ +class LoadTimeWeaverBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { + + private static final String WEAVER_CLASS_ATTRIBUTE = "weaver-class"; + + private static final String ASPECTJ_WEAVING_ATTRIBUTE = "aspectj-weaving"; + + private static final String ASPECTJ_AOP_XML_RESOURCE = "META-INF/aop.xml"; + + private static final String DEFAULT_LOAD_TIME_WEAVER_CLASS_NAME = + "org.springframework.context.weaving.DefaultContextLoadTimeWeaver"; + + private static final String ASPECTJ_WEAVING_ENABLER_CLASS_NAME = + "org.springframework.context.weaving.AspectJWeavingEnabler"; + + + protected String getBeanClassName(Element element) { + if (element.hasAttribute(WEAVER_CLASS_ATTRIBUTE)) { + return element.getAttribute(WEAVER_CLASS_ATTRIBUTE); + } + return DEFAULT_LOAD_TIME_WEAVER_CLASS_NAME; + } + + protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) { + return ConfigurableApplicationContext.LOAD_TIME_WEAVER_BEAN_NAME; + } + + protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { + builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + + if (isAspectJWeavingEnabled(element.getAttribute(ASPECTJ_WEAVING_ATTRIBUTE), parserContext)) { + RootBeanDefinition weavingEnablerDef = new RootBeanDefinition(); + weavingEnablerDef.setBeanClassName(ASPECTJ_WEAVING_ENABLER_CLASS_NAME); + parserContext.getReaderContext().registerWithGeneratedName(weavingEnablerDef); + + if (isBeanConfigurerAspectEnabled(parserContext.getReaderContext().getBeanClassLoader())) { + new SpringConfiguredBeanDefinitionParser().parse(element, parserContext); + } + } + } + + protected boolean isAspectJWeavingEnabled(String value, ParserContext parserContext) { + if ("on".equals(value)) { + return true; + } + else if ("off".equals(value)) { + return false; + } + else { + // Determine default... + ClassLoader cl = parserContext.getReaderContext().getResourceLoader().getClassLoader(); + return (cl.getResource(ASPECTJ_AOP_XML_RESOURCE) != null); + } + } + + protected boolean isBeanConfigurerAspectEnabled(ClassLoader beanClassLoader) { + return ClassUtils.isPresent(SpringConfiguredBeanDefinitionParser.BEAN_CONFIGURER_ASPECT_CLASS_NAME, + beanClassLoader); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/config/MBeanExportBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/config/MBeanExportBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/config/MBeanExportBeanDefinitionParser.java 17 Aug 2012 15:14:29 -0000 1.1 @@ -0,0 +1,100 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.core.JdkVersion; +import org.springframework.jmx.support.MBeanRegistrationSupport; +import org.springframework.util.StringUtils; + +/** + * Parser for the <context:mbean-export/> element. + * + *

    Registers an instance of + * {@link org.springframework.jmx.export.annotation.AnnotationMBeanExporter} + * within the context. + * + * @author Juergen Hoeller + * @author Mark Fisher + * @since 2.5 + * @see org.springframework.jmx.export.annotation.AnnotationMBeanExporter + */ +class MBeanExportBeanDefinitionParser extends AbstractBeanDefinitionParser { + + private static final String MBEAN_EXPORTER_BEAN_NAME = "mbeanExporter"; + + private static final String DEFAULT_DOMAIN_ATTRIBUTE = "default-domain"; + + private static final String SERVER_ATTRIBUTE = "server"; + + private static final String REGISTRATION_ATTRIBUTE = "registration"; + + private static final String REGISTRATION_IGNORE_EXISTING = "ignoreExisting"; + + private static final String REGISTRATION_REPLACE_EXISTING = "replaceExisting"; + + + protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) { + return MBEAN_EXPORTER_BEAN_NAME; + } + + protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { + String beanClassName = (JdkVersion.isAtLeastJava15() ? + "org.springframework.jmx.export.annotation.AnnotationMBeanExporter" : + "org.springframework.jmx.export.MBeanExporter"); + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(beanClassName); + + // Mark as infrastructure bean and attach source location. + builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + builder.getRawBeanDefinition().setSource(parserContext.extractSource(element)); + + String defaultDomain = element.getAttribute(DEFAULT_DOMAIN_ATTRIBUTE); + if (StringUtils.hasText(defaultDomain)) { + builder.addPropertyValue("defaultDomain", defaultDomain); + } + + String serverBeanName = element.getAttribute(SERVER_ATTRIBUTE); + if (StringUtils.hasText(serverBeanName)) { + builder.addPropertyReference("server", serverBeanName); + } + else { + AbstractBeanDefinition specialServer = MBeanServerBeanDefinitionParser.findServerForSpecialEnvironment(); + if (specialServer != null) { + builder.addPropertyValue("server", specialServer); + } + } + + String registration = element.getAttribute(REGISTRATION_ATTRIBUTE); + int registrationBehavior = MBeanRegistrationSupport.REGISTRATION_FAIL_ON_EXISTING; + if (REGISTRATION_IGNORE_EXISTING.equals(registration)) { + registrationBehavior = MBeanRegistrationSupport.REGISTRATION_IGNORE_EXISTING; + } + else if (REGISTRATION_REPLACE_EXISTING.equals(registration)) { + registrationBehavior = MBeanRegistrationSupport.REGISTRATION_REPLACE_EXISTING; + } + builder.addPropertyValue("registrationBehavior", new Integer(registrationBehavior)); + + return builder.getBeanDefinition(); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/config/MBeanServerBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/config/MBeanServerBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/config/MBeanServerBeanDefinitionParser.java 17 Aug 2012 15:14:29 -0000 1.1 @@ -0,0 +1,97 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.jmx.support.MBeanServerFactoryBean; +import org.springframework.jmx.support.WebSphereMBeanServerFactoryBean; +import org.springframework.jndi.JndiObjectFactoryBean; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +/** + * Parser for the <context:mbean-server/> element. + * + *

    Registers an instance of + * {@link org.springframework.jmx.export.annotation.AnnotationMBeanExporter} + * within the context. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + * @see org.springframework.jmx.export.annotation.AnnotationMBeanExporter + */ +class MBeanServerBeanDefinitionParser extends AbstractBeanDefinitionParser { + + private static final String MBEAN_SERVER_BEAN_NAME = "mbeanServer"; + + private static final String AGENT_ID_ATTRIBUTE = "agent-id"; + + + private static final boolean weblogicPresent = ClassUtils.isPresent( + "weblogic.management.Helper", MBeanServerBeanDefinitionParser.class.getClassLoader()); + + private static final boolean webspherePresent = ClassUtils.isPresent( + "com.ibm.websphere.management.AdminServiceFactory", MBeanServerBeanDefinitionParser.class.getClassLoader()); + + + protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) { + String id = element.getAttribute(ID_ATTRIBUTE); + return (StringUtils.hasText(id) ? id : MBEAN_SERVER_BEAN_NAME); + } + + protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { + String agentId = element.getAttribute(AGENT_ID_ATTRIBUTE); + if (StringUtils.hasText(agentId)) { + RootBeanDefinition bd = new RootBeanDefinition(MBeanServerFactoryBean.class); + bd.getPropertyValues().addPropertyValue("agentId", agentId); + return bd; + } + AbstractBeanDefinition specialServer = findServerForSpecialEnvironment(); + if (specialServer != null) { + return specialServer; + } + RootBeanDefinition bd = new RootBeanDefinition(MBeanServerFactoryBean.class); + bd.getPropertyValues().addPropertyValue("locateExistingServerIfPossible", Boolean.TRUE); + + // Mark as infrastructure bean and attach source location. + bd.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + bd.setSource(parserContext.extractSource(element)); + return bd; + } + + static AbstractBeanDefinition findServerForSpecialEnvironment() { + if (weblogicPresent) { + RootBeanDefinition bd = new RootBeanDefinition(JndiObjectFactoryBean.class); + bd.getPropertyValues().addPropertyValue("jndiName", "java:comp/env/jmx/runtime"); + return bd; + } + else if (webspherePresent) { + return new RootBeanDefinition(WebSphereMBeanServerFactoryBean.class); + } + else { + return null; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/context/config/PropertyOverrideBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/config/PropertyOverrideBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/config/PropertyOverrideBeanDefinitionParser.java 17 Aug 2012 15:14:29 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.PropertyOverrideConfigurer; + +/** + * Parser for the <context:property-override/> element. + * + * @author Juergen Hoeller + * @since 2.5.2 + */ +class PropertyOverrideBeanDefinitionParser extends AbstractPropertyLoadingBeanDefinitionParser { + + protected Class getBeanClass(Element element) { + return PropertyOverrideConfigurer.class; + } + +} \ No newline at end of file Index: 3rdParty_sources/spring/org/springframework/context/config/PropertyPlaceholderBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/config/PropertyPlaceholderBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/config/PropertyPlaceholderBeanDefinitionParser.java 17 Aug 2012 15:14:29 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; + +/** + * Parser for the <context:property-placeholder/> element. + * + * @author Juergen Hoeller + * @since 2.5 + */ +class PropertyPlaceholderBeanDefinitionParser extends AbstractPropertyLoadingBeanDefinitionParser { + + protected Class getBeanClass(Element element) { + return PropertyPlaceholderConfigurer.class; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/config/SpringConfiguredBeanDefinitionParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/config/SpringConfiguredBeanDefinitionParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/config/SpringConfiguredBeanDefinitionParser.java 17 Aug 2012 15:14:29 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.config; + +import org.w3c.dom.Element; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; + +/** + * {@link BeanDefinitionParser} responsible for parsing the + * <context:spring-configured/> tag. + * + * @author Juergen Hoeller + * @since 2.5 + */ +class SpringConfiguredBeanDefinitionParser implements BeanDefinitionParser { + + /** + * The bean name of the internally managed bean configurer aspect. + */ + public static final String BEAN_CONFIGURER_ASPECT_BEAN_NAME = + "org.springframework.context.config.internalBeanConfigurerAspect"; + + static final String BEAN_CONFIGURER_ASPECT_CLASS_NAME = + "org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect"; + + + public BeanDefinition parse(Element element, ParserContext parserContext) { + if (!parserContext.getRegistry().containsBeanDefinition(BEAN_CONFIGURER_ASPECT_BEAN_NAME)) { + RootBeanDefinition def = new RootBeanDefinition(); + def.setBeanClassName(BEAN_CONFIGURER_ASPECT_CLASS_NAME); + def.setFactoryMethodName("aspectOf"); + + // Mark as infrastructure bean and attach source location. + def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + def.setSource(parserContext.extractSource(element)); + parserContext.registerBeanComponent(new BeanComponentDefinition(def, BEAN_CONFIGURER_ASPECT_BEAN_NAME)); + } + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/config/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/config/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/config/package.html 17 Aug 2012 15:14:29 -0000 1.1 @@ -0,0 +1,8 @@ + + + +Support package for advanced application context configuration, +with XML schema being the primary configuration format. + + + Index: 3rdParty_sources/spring/org/springframework/context/config/spring-context-2.5.xsd =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/config/spring-context-2.5.xsd,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/config/spring-context-2.5.xsd 17 Aug 2012 15:14:29 -0000 1.1 @@ -0,0 +1,423 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + tag for that purpose. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: 3rdParty_sources/spring/org/springframework/context/event/AbstractApplicationEventMulticaster.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/event/AbstractApplicationEventMulticaster.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/event/AbstractApplicationEventMulticaster.java 17 Aug 2012 15:14:36 -0000 1.1 @@ -0,0 +1,112 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.event; + +import java.util.Collection; +import java.util.LinkedHashSet; + +import org.springframework.beans.BeanUtils; +import org.springframework.context.ApplicationListener; +import org.springframework.core.CollectionFactory; + +/** + * Abstract implementation of the {@link ApplicationEventMulticaster} interface, + * providing the basic listener registration facility. + * + *

    Doesn't permit multiple instances of the same listener by default, + * as it keeps listeners in a linked Set. The collection class used to hold + * ApplicationListener objects can be overridden through the "collectionClass" + * bean property. + * + *

    Implementing ApplicationEventMulticaster's actual {@link #multicastEvent} method + * is left to subclasses. {@link SimpleApplicationEventMulticaster} simply multicasts + * all events to all registered listeners, invoking them in the calling thread. + * Alternative implementations could be more sophisticated in those respects. + * + * @author Juergen Hoeller + * @since 1.2.3 + * @see #setCollectionClass + * @see #getApplicationListeners() + * @see SimpleApplicationEventMulticaster + */ +public abstract class AbstractApplicationEventMulticaster implements ApplicationEventMulticaster { + + /** Collection of ApplicationListeners */ + private Collection applicationListeners = new LinkedHashSet(); + + + /** + * Set whether this multicaster should expect concurrent updates at runtime + * (i.e. after context startup finished). In case of concurrent updates, + * a copy-on-write strategy is applied, keeping iteration (for multicasting) + * without synchronization while still making listener updates thread-safe. + */ + public void setConcurrentUpdates(boolean concurrent) { + Collection newColl = (concurrent ? CollectionFactory.createCopyOnWriteSet() : new LinkedHashSet()); + // Add all previously registered listeners (usually none). + newColl.addAll(this.applicationListeners); + this.applicationListeners = newColl; + } + + /** + * Specify the collection class to use. Can be populated with a fully + * qualified class name when defined in a Spring application context. + *

    Default is a linked HashSet, keeping the registration order. + * Note that a Set class specified will not permit multiple instances + * of the same listener, while a List class will allow for registering + * the same listener multiple times. + */ + public void setCollectionClass(Class collectionClass) { + if (collectionClass == null) { + throw new IllegalArgumentException("'collectionClass' must not be null"); + } + if (!Collection.class.isAssignableFrom(collectionClass)) { + throw new IllegalArgumentException("'collectionClass' must implement [java.util.Collection]"); + } + // Create desired collection instance. + Collection newColl = (Collection) BeanUtils.instantiateClass(collectionClass); + // Add all previously registered listeners (usually none). + newColl.addAll(this.applicationListeners); + this.applicationListeners = newColl; + } + + + public void addApplicationListener(ApplicationListener listener) { + this.applicationListeners.add(listener); + } + + public void removeApplicationListener(ApplicationListener listener) { + this.applicationListeners.remove(listener); + } + + public void removeAllListeners() { + this.applicationListeners.clear(); + } + + /** + * Return the current Collection of ApplicationListeners. + *

    Note that this is the raw Collection of ApplicationListeners, + * potentially modified when new listeners get registered or + * existing ones get removed. This Collection is not a snapshot copy. + * @return a Collection of ApplicationListeners + * @see org.springframework.context.ApplicationListener + */ + protected Collection getApplicationListeners() { + return this.applicationListeners; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/event/ApplicationContextEvent.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/event/ApplicationContextEvent.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/event/ApplicationContextEvent.java 17 Aug 2012 15:14:36 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.event; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationEvent; + +/** + * Base class for events raised for an ApplicationContext. + * + * @author Juergen Hoeller + * @since 2.5 + */ +public abstract class ApplicationContextEvent extends ApplicationEvent { + + /** + * Create a new ContextStartedEvent. + * @param source the ApplicationContext that the event is raised for + * (must not be null) + */ + public ApplicationContextEvent(ApplicationContext source) { + super(source); + } + + /** + * Get the ApplicationContext that the event was raised for. + */ + public final ApplicationContext getApplicationContext() { + return (ApplicationContext) getSource(); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/event/ApplicationEventMulticaster.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/event/ApplicationEventMulticaster.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/event/ApplicationEventMulticaster.java 17 Aug 2012 15:14:36 -0000 1.1 @@ -0,0 +1,58 @@ + /* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.event; + +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationListener; + +/** + * Interface to be implemented by objects that can manage a number + * of ApplicationListeners, and publish events to them. An example + * of such an object is an ApplicationEventPublisher, typically + * the ApplicationContext, which can use an ApplicationEventMulticaster + * as a helper to publish events to listeners. + * + * @author Rod Johnson + */ +public interface ApplicationEventMulticaster { + + /** + * Add a listener to be notified of all events. + * @param listener the listener to add + */ + void addApplicationListener(ApplicationListener listener); + + /** + * Remove a listener from the notification list. + * @param listener the listener to remove + */ + void removeApplicationListener(ApplicationListener listener); + + /** + * Remove all listeners registered with this multicaster. + * It will perform no action on event notification until more + * listeners are registered. + */ + void removeAllListeners(); + + /** + * Multicast the given application event to appropriate listeners. + * @param event the event to multicast + */ + void multicastEvent(ApplicationEvent event); + +} Index: 3rdParty_sources/spring/org/springframework/context/event/ContextClosedEvent.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/event/ContextClosedEvent.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/event/ContextClosedEvent.java 17 Aug 2012 15:14:36 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.event; + +import org.springframework.context.ApplicationContext; + +/** + * Event raised when an ApplicationContext gets closed. + * + * @author Juergen Hoeller + * @since 12.08.2003 + * @see ContextRefreshedEvent + */ +public class ContextClosedEvent extends ApplicationContextEvent { + + /** + * Creates a new ContextClosedEvent. + * @param source the ApplicationContext that has been closed + * (must not be null) + */ + public ContextClosedEvent(ApplicationContext source) { + super(source); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/event/ContextRefreshedEvent.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/event/ContextRefreshedEvent.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/event/ContextRefreshedEvent.java 17 Aug 2012 15:14:36 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.event; + +import org.springframework.context.ApplicationContext; + +/** + * Event raised when an ApplicationContext gets initialized or refreshed. + * + * @author Juergen Hoeller + * @since 04.03.2003 + * @see ContextClosedEvent + */ +public class ContextRefreshedEvent extends ApplicationContextEvent { + + /** + * Create a new ContextRefreshedEvent. + * @param source the ApplicationContext that has been initialized + * or refreshed (must not be null) + */ + public ContextRefreshedEvent(ApplicationContext source) { + super(source); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/event/ContextStartedEvent.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/event/ContextStartedEvent.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/event/ContextStartedEvent.java 17 Aug 2012 15:14:36 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.event; + +import org.springframework.context.ApplicationContext; + +/** + * Event raised when an ApplicationContext gets started. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + * @see ContextStoppedEvent + */ +public class ContextStartedEvent extends ApplicationContextEvent { + + /** + * Create a new ContextStartedEvent. + * @param source the ApplicationContext that has been started + * (must not be null) + */ + public ContextStartedEvent(ApplicationContext source) { + super(source); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/event/ContextStoppedEvent.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/event/ContextStoppedEvent.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/event/ContextStoppedEvent.java 17 Aug 2012 15:14:36 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.event; + +import org.springframework.context.ApplicationContext; + +/** + * Event raised when an ApplicationContext gets stopped. + * + * @author Mark Fisher + * @author Juergen Hoeller + * @since 2.5 + * @see ContextStartedEvent + */ +public class ContextStoppedEvent extends ApplicationContextEvent { + + /** + * Create a new ContextStoppedEvent. + * @param source the ApplicationContext that has been stopped + * (must not be null) + */ + public ContextStoppedEvent(ApplicationContext source) { + super(source); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/event/EventPublicationInterceptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/event/EventPublicationInterceptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/event/EventPublicationInterceptor.java 17 Aug 2012 15:14:36 -0000 1.1 @@ -0,0 +1,101 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.event; + +import java.lang.reflect.Constructor; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.ApplicationEventPublisherAware; + +/** + * {@link MethodInterceptor Interceptor} that publishes an + * ApplicationEvent to all ApplicationListeners + * registered with an ApplicationEventPublisher after each + * successful method invocation. + * + *

    Note that this interceptor is only capable of publishing stateless + * events configured via the + * {@link #setApplicationEventClass "applicationEventClass"} property. + * + * @author Dmitriy Kopylenko + * @author Juergen Hoeller + * @author Rick Evans + * @see #setApplicationEventClass + * @see org.springframework.context.ApplicationEvent + * @see org.springframework.context.ApplicationListener + * @see org.springframework.context.ApplicationEventPublisher + * @see org.springframework.context.ApplicationContext + */ +public class EventPublicationInterceptor + implements MethodInterceptor, ApplicationEventPublisherAware, InitializingBean { + + private Constructor applicationEventClassConstructor; + + private ApplicationEventPublisher applicationEventPublisher; + + + /** + * Set the application event class to publish. + *

    The event class must have a constructor with a single + * Object argument for the event source. The interceptor + * will pass in the invoked object. + * @throws IllegalArgumentException if the supplied Class is + * null or if it is not an ApplicationEvent subclass or + * if it does not expose a constructor that takes a single Object argument + */ + public void setApplicationEventClass(Class applicationEventClass) { + if (ApplicationEvent.class.equals(applicationEventClass) || + !ApplicationEvent.class.isAssignableFrom(applicationEventClass)) { + throw new IllegalArgumentException("applicationEventClass needs to extend ApplicationEvent"); + } + try { + this.applicationEventClassConstructor = + applicationEventClass.getConstructor(new Class[] {Object.class}); + } + catch (NoSuchMethodException ex) { + throw new IllegalArgumentException("applicationEventClass [" + + applicationEventClass.getName() + "] does not have the required Object constructor: " + ex); + } + } + + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { + this.applicationEventPublisher = applicationEventPublisher; + } + + public void afterPropertiesSet() throws Exception { + if (this.applicationEventClassConstructor == null) { + throw new IllegalArgumentException("applicationEventClass is required"); + } + } + + + public Object invoke(MethodInvocation invocation) throws Throwable { + Object retVal = invocation.proceed(); + + ApplicationEvent event = (ApplicationEvent) + this.applicationEventClassConstructor.newInstance(new Object[] {invocation.getThis()}); + this.applicationEventPublisher.publishEvent(event); + + return retVal; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/event/SimpleApplicationEventMulticaster.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/event/SimpleApplicationEventMulticaster.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/event/SimpleApplicationEventMulticaster.java 17 Aug 2012 15:14:36 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.event; + +import java.util.Iterator; + +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.core.task.SyncTaskExecutor; +import org.springframework.core.task.TaskExecutor; + +/** + * Simple implementation of the {@link ApplicationEventMulticaster} interface. + * + *

    Multicasts all events to all registered listeners, leaving it up to + * the listeners to ignore events that they are not interested in. + * Listeners will usually perform corresponding instanceof + * checks on the passed-in event object. + * + *

    By default, all listeners are invoked in the calling thread. + * This allows the danger of a rogue listener blocking the entire application, + * but adds minimal overhead. Specify an alternative TaskExecutor to have + * listeners executed in different threads, for example from a thread pool. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see #setTaskExecutor + * @see #setConcurrentUpdates + */ +public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster { + + private TaskExecutor taskExecutor = new SyncTaskExecutor(); + + + /** + * Set the TaskExecutor to execute application listeners with. + *

    Default is a SyncTaskExecutor, executing the listeners synchronously + * in the calling thread. + *

    Consider specifying an asynchronous TaskExecutor here to not block the + * caller until all listeners have been executed. However, note that asynchronous + * execution will not participate in the caller's thread context (class loader, + * transaction association) unless the TaskExecutor explicitly supports this. + * @see org.springframework.core.task.SyncTaskExecutor + * @see org.springframework.core.task.SimpleAsyncTaskExecutor + * @see org.springframework.scheduling.timer.TimerTaskExecutor + */ + public void setTaskExecutor(TaskExecutor taskExecutor) { + this.taskExecutor = (taskExecutor != null ? taskExecutor : new SyncTaskExecutor()); + } + + /** + * Return the current TaskExecutor for this multicaster. + */ + protected TaskExecutor getTaskExecutor() { + return this.taskExecutor; + } + + + public void multicastEvent(final ApplicationEvent event) { + for (Iterator it = getApplicationListeners().iterator(); it.hasNext();) { + final ApplicationListener listener = (ApplicationListener) it.next(); + getTaskExecutor().execute(new Runnable() { + public void run() { + listener.onApplicationEvent(event); + } + }); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/context/event/SourceFilteringListener.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/event/SourceFilteringListener.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/event/SourceFilteringListener.java 17 Aug 2012 15:14:36 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.event; + +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationListener; + +/** + * {@link org.springframework.context.ApplicationListener} decorator that filters + * events from a specified event source, invoking its delegate listener for + * matching {@link org.springframework.context.ApplicationEvent} objects only. + * + *

    Can also be used as base class, overriding the {@link #onApplicationEventInternal} + * method instead of specifying a delegate listener. + * + * @author Juergen Hoeller + * @since 2.0.5 + */ +public class SourceFilteringListener implements ApplicationListener { + + private final Object source; + + private ApplicationListener delegate; + + + /** + * Create a SourceFilteringListener for the given event source. + * @param source the event source that this listener filters for, + * only processing events from this source + * @param delegate the delegate listener to invoke with event + * from the specified source + */ + public SourceFilteringListener(Object source, ApplicationListener delegate) { + this.source = source; + this.delegate = delegate; + } + + /** + * Create a SourceFilteringListener for the given event source, + * expecting subclasses to override the {@link #onApplicationEventInternal} + * method (instead of specifying a delegate listener). + * @param source the event source that this listener filters for, + * only processing events from this source + */ + protected SourceFilteringListener(Object source) { + this.source = source; + } + + + public void onApplicationEvent(ApplicationEvent event) { + if (event.getSource() == this.source) { + onApplicationEventInternal(event); + } + } + + /** + * Actually process the event, after having filtered according to the + * desired event source already. + *

    The default implementation invokes the specified delegate, if any. + * @param event the event to process (matching the specified source) + */ + protected void onApplicationEventInternal(ApplicationEvent event) { + if (this.delegate == null) { + throw new IllegalStateException( + "Must specify a delegate object or override the onApplicationEventInternal method"); + } + this.delegate.onApplicationEvent(event); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/event/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/event/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/event/package.html 17 Aug 2012 15:14:36 -0000 1.1 @@ -0,0 +1,8 @@ + + + +Support classes for application events, like standard context events. +To be supported by all major application context implementations. + + + Index: 3rdParty_sources/spring/org/springframework/context/i18n/LocaleContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/i18n/LocaleContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/i18n/LocaleContext.java 17 Aug 2012 15:14:42 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.i18n; + +import java.util.Locale; + +/** + * Strategy interface for determining the current Locale. + * + *

    A LocaleContext instance can be associated with a thread + * via the LocaleContextHolder class. + * + * @author Juergen Hoeller + * @since 1.2 + * @see LocaleContextHolder + * @see java.util.Locale + */ +public interface LocaleContext { + + /** + * Return the current Locale, which can be fixed or determined dynamically, + * depending on the implementation strategy. + */ + Locale getLocale(); + +} Index: 3rdParty_sources/spring/org/springframework/context/i18n/LocaleContextHolder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/i18n/LocaleContextHolder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/i18n/LocaleContextHolder.java 17 Aug 2012 15:14:42 -0000 1.1 @@ -0,0 +1,136 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.i18n; + +import java.util.Locale; + +import org.springframework.core.NamedInheritableThreadLocal; +import org.springframework.core.NamedThreadLocal; + +/** + * Simple holder class that associates a LocaleContext instance + * with the current thread. The LocaleContext will be inherited + * by any child threads spawned by the current thread. + * + *

    Used as a central holder for the current Locale in Spring, + * wherever necessary: for example, in MessageSourceAccessor. + * DispatcherServlet automatically exposes its current Locale here. + * Other applications can expose theirs too, to make classes like + * MessageSourceAccessor automatically use that Locale. + * + * @author Juergen Hoeller + * @since 1.2 + * @see LocaleContext + * @see org.springframework.context.support.MessageSourceAccessor + * @see org.springframework.web.servlet.DispatcherServlet + */ +public abstract class LocaleContextHolder { + + private static final ThreadLocal localeContextHolder = new NamedThreadLocal("Locale context"); + + private static final ThreadLocal inheritableLocaleContextHolder = + new NamedInheritableThreadLocal("Locale context"); + + + /** + * Reset the LocaleContext for the current thread. + */ + public static void resetLocaleContext() { + localeContextHolder.set(null); + inheritableLocaleContextHolder.set(null); + } + + /** + * Associate the given LocaleContext with the current thread, + * not exposing it as inheritable for child threads. + * @param localeContext the current LocaleContext, or null to reset + * the thread-bound context + */ + public static void setLocaleContext(LocaleContext localeContext) { + setLocaleContext(localeContext, false); + } + + /** + * Associate the given LocaleContext with the current thread. + * @param localeContext the current LocaleContext, or null to reset + * the thread-bound context + * @param inheritable whether to expose the LocaleContext as inheritable + * for child threads (using an {@link java.lang.InheritableThreadLocal}) + */ + public static void setLocaleContext(LocaleContext localeContext, boolean inheritable) { + if (inheritable) { + inheritableLocaleContextHolder.set(localeContext); + localeContextHolder.set(null); + } + else { + localeContextHolder.set(localeContext); + inheritableLocaleContextHolder.set(null); + } + } + + /** + * Return the LocaleContext associated with the current thread, if any. + * @return the current LocaleContext, or null if none + */ + public static LocaleContext getLocaleContext() { + LocaleContext localeContext = (LocaleContext) localeContextHolder.get(); + if (localeContext == null) { + localeContext = (LocaleContext) inheritableLocaleContextHolder.get(); + } + return localeContext; + } + + /** + * Associate the given Locale with the current thread. + *

    Will implicitly create a LocaleContext for the given Locale, + * not exposing it as inheritable for child threads. + * @param locale the current Locale, or null to reset + * the thread-bound context + * @see SimpleLocaleContext#SimpleLocaleContext(java.util.Locale) + */ + public static void setLocale(Locale locale) { + setLocale(locale, false); + } + + /** + * Associate the given Locale with the current thread. + *

    Will implicitly create a LocaleContext for the given Locale. + * @param locale the current Locale, or null to reset + * the thread-bound context + * @param inheritable whether to expose the LocaleContext as inheritable + * for child threads (using an {@link java.lang.InheritableThreadLocal}) + * @see SimpleLocaleContext#SimpleLocaleContext(java.util.Locale) + */ + public static void setLocale(Locale locale, boolean inheritable) { + LocaleContext localeContext = (locale != null ? new SimpleLocaleContext(locale) : null); + setLocaleContext(localeContext, inheritable); + } + + /** + * Return the Locale associated with the current thread, if any, + * or the system default Locale else. + * @return the current Locale, or the system default Locale if no + * specific Locale has been associated with the current thread + * @see LocaleContext#getLocale() + * @see java.util.Locale#getDefault() + */ + public static Locale getLocale() { + LocaleContext localeContext = getLocaleContext(); + return (localeContext != null ? localeContext.getLocale() : Locale.getDefault()); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/i18n/SimpleLocaleContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/i18n/SimpleLocaleContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/i18n/SimpleLocaleContext.java 17 Aug 2012 15:14:42 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.i18n; + +import java.util.Locale; + +import org.springframework.util.Assert; + +/** + * Simple implementation of the {@link LocaleContext} interface, + * always returning a specified Locale. + * + * @author Juergen Hoeller + * @since 1.2 + */ +public class SimpleLocaleContext implements LocaleContext { + + private final Locale locale; + + + /** + * Create a new SimpleLocaleContext that exposes the specified Locale. + * Every getLocale() will return this Locale. + * @param locale the Locale to expose + */ + public SimpleLocaleContext(Locale locale) { + Assert.notNull(locale, "Locale must not be null"); + this.locale = locale; + } + + public Locale getLocale() { + return this.locale; + } + + public String toString() { + return this.locale.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/i18n/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/i18n/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/i18n/package.html 17 Aug 2012 15:14:42 -0000 1.1 @@ -0,0 +1,8 @@ + + + +Abstraction for determining the current Locale, +plus global holder that exposes a thread-bound Locale. + + + Index: 3rdParty_sources/spring/org/springframework/context/support/AbstractApplicationContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/AbstractApplicationContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/AbstractApplicationContext.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,1204 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.support.ResourceEditorRegistrar; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.ApplicationEventPublisherAware; +import org.springframework.context.ApplicationListener; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.HierarchicalMessageSource; +import org.springframework.context.Lifecycle; +import org.springframework.context.MessageSource; +import org.springframework.context.MessageSourceAware; +import org.springframework.context.MessageSourceResolvable; +import org.springframework.context.NoSuchMessageException; +import org.springframework.context.ResourceLoaderAware; +import org.springframework.context.event.ApplicationEventMulticaster; +import org.springframework.context.event.ContextClosedEvent; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.ContextStartedEvent; +import org.springframework.context.event.ContextStoppedEvent; +import org.springframework.context.event.SimpleApplicationEventMulticaster; +import org.springframework.core.JdkVersion; +import org.springframework.core.OrderComparator; +import org.springframework.core.Ordered; +import org.springframework.core.PriorityOrdered; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.ObjectUtils; + +/** + * Abstract implementation of the {@link org.springframework.context.ApplicationContext} + * interface. Doesn't mandate the type of storage used for configuration; simply + * implements common context functionality. Uses the Template Method design pattern, + * requiring concrete subclasses to implement abstract methods. + * + *

    In contrast to a plain BeanFactory, an ApplicationContext is supposed + * to detect special beans defined in its internal bean factory: + * Therefore, this class automatically registers + * {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactoryPostProcessors}, + * {@link org.springframework.beans.factory.config.BeanPostProcessor BeanPostProcessors} + * and {@link org.springframework.context.ApplicationListener ApplicationListeners} + * which are defined as beans in the context. + * + *

    A {@link org.springframework.context.MessageSource} may also be supplied + * as a bean in the context, with the name "messageSource"; otherwise, message + * resolution is delegated to the parent context. Furthermore, a multicaster + * for application events can be supplied as "applicationEventMulticaster" bean + * of type {@link org.springframework.context.event.ApplicationEventMulticaster} + * in the context; otherwise, a default multicaster of type + * {@link org.springframework.context.event.SimpleApplicationEventMulticaster} will be used. + * + *

    Implements resource loading through extending + * {@link org.springframework.core.io.DefaultResourceLoader}. + * Consequently treats non-URL resource paths as class path resources + * (supporting full class path resource names that include the package path, + * e.g. "mypackage/myresource.dat"), unless the {@link #getResourceByPath} + * method is overwritten in a subclass. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Mark Fisher + * @since January 21, 2001 + * @see #refreshBeanFactory + * @see #getBeanFactory + * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor + * @see org.springframework.beans.factory.config.BeanPostProcessor + * @see org.springframework.context.event.ApplicationEventMulticaster + * @see org.springframework.context.ApplicationListener + * @see org.springframework.context.MessageSource + */ +public abstract class AbstractApplicationContext extends DefaultResourceLoader + implements ConfigurableApplicationContext, DisposableBean { + + /** + * Name of the MessageSource bean in the factory. + * If none is supplied, message resolution is delegated to the parent. + * @see MessageSource + */ + public static final String MESSAGE_SOURCE_BEAN_NAME = "messageSource"; + + /** + * Name of the ApplicationEventMulticaster bean in the factory. + * If none is supplied, a default SimpleApplicationEventMulticaster is used. + * @see org.springframework.context.event.ApplicationEventMulticaster + * @see org.springframework.context.event.SimpleApplicationEventMulticaster + */ + public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster"; + + + static { + // Eagerly load the ContextClosedEvent class to avoid weird classloader issues + // on application shutdown in WebLogic 8.1. (Reported by Dustin Woods.) + ContextClosedEvent.class.getName(); + } + + + /** Logger used by this class. Available to subclasses. */ + protected final Log logger = LogFactory.getLog(getClass()); + + /** Unique id for this context, if any */ + private String id = ObjectUtils.identityToString(this); + + /** Parent context */ + private ApplicationContext parent; + + /** BeanFactoryPostProcessors to apply on refresh */ + private final List beanFactoryPostProcessors = new ArrayList(); + + /** Display name */ + private String displayName; + + /** System time in milliseconds when this context started */ + private long startupDate; + + /** Flag that indicates whether this context is currently active */ + private boolean active = false; + + /** Synchronization monitor for the "active" flag */ + private final Object activeMonitor = new Object(); + + /** Synchronization monitor for the "refresh" and "destroy" */ + private final Object startupShutdownMonitor = new Object(); + + /** Reference to the JVM shutdown hook, if registered */ + private Thread shutdownHook; + + /** ResourcePatternResolver used by this context */ + private ResourcePatternResolver resourcePatternResolver; + + /** MessageSource we delegate our implementation of this interface to */ + private MessageSource messageSource; + + /** Helper class used in event publishing */ + private ApplicationEventMulticaster applicationEventMulticaster; + + /** Statically specified listeners */ + private List applicationListeners = new ArrayList(); + + + /** + * Create a new AbstractApplicationContext with no parent. + */ + public AbstractApplicationContext() { + this(null); + } + + /** + * Create a new AbstractApplicationContext with the given parent context. + * @param parent the parent context + */ + public AbstractApplicationContext(ApplicationContext parent) { + this.parent = parent; + this.resourcePatternResolver = getResourcePatternResolver(); + } + + + //--------------------------------------------------------------------- + // Implementation of ApplicationContext interface + //--------------------------------------------------------------------- + + /** + * Set the unique id of this application context. + *

    Default is the object id of the context instance, or the name + * of the context bean if the context is itself defined as a bean. + * @param id the unique id of the context + */ + public void setId(String id) { + this.id = id; + } + + public String getId() { + return this.id; + } + + /** + * Return the parent context, or null if there is no parent + * (that is, this context is the root of the context hierarchy). + */ + public ApplicationContext getParent() { + return this.parent; + } + + /** + * Return this context's internal bean factory as AutowireCapableBeanFactory, + * if already available. + * @see #getBeanFactory() + */ + public AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException { + return getBeanFactory(); + } + + /** + * Set a friendly name for this context. + * Typically done during initialization of concrete context implementations. + */ + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + /** + * Return a friendly name for this context. + */ + public String getDisplayName() { + return (this.displayName != null ? this.displayName : getId()); + } + + /** + * Return the timestamp (ms) when this context was first loaded. + */ + public long getStartupDate() { + return this.startupDate; + } + + /** + * Publish the given event to all listeners. + *

    Note: Listeners get initialized after the MessageSource, to be able + * to access it within listener implementations. Thus, MessageSource + * implementations cannot publish events. + * @param event the event to publish (may be application-specific or a + * standard framework event) + */ + public void publishEvent(ApplicationEvent event) { + Assert.notNull(event, "Event must not be null"); + if (logger.isTraceEnabled()) { + logger.trace("Publishing event in context [" + getId() + "]: " + event); + } + getApplicationEventMulticaster().multicastEvent(event); + if (this.parent != null) { + this.parent.publishEvent(event); + } + } + + /** + * Return the internal MessageSource used by the context. + * @return the internal MessageSource (never null) + * @throws IllegalStateException if the context has not been initialized yet + */ + private ApplicationEventMulticaster getApplicationEventMulticaster() throws IllegalStateException { + if (this.applicationEventMulticaster == null) { + throw new IllegalStateException("ApplicationEventMulticaster not initialized - " + + "call 'refresh' before multicasting events via the context: " + this); + } + return this.applicationEventMulticaster; + } + + /** + * Return the ResourcePatternResolver to use for resolving location patterns + * into Resource instances. Default is a + * {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}, + * supporting Ant-style location patterns. + *

    Can be overridden in subclasses, for extended resolution strategies, + * for example in a web environment. + *

    Do not call this when needing to resolve a location pattern. + * Call the context's getResources method instead, which + * will delegate to the ResourcePatternResolver. + * @return the ResourcePatternResolver for this context + * @see #getResources + * @see org.springframework.core.io.support.PathMatchingResourcePatternResolver + */ + protected ResourcePatternResolver getResourcePatternResolver() { + return new PathMatchingResourcePatternResolver(this); + } + + + //--------------------------------------------------------------------- + // Implementation of ConfigurableApplicationContext interface + //--------------------------------------------------------------------- + + public void setParent(ApplicationContext parent) { + this.parent = parent; + } + + public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor beanFactoryPostProcessor) { + this.beanFactoryPostProcessors.add(beanFactoryPostProcessor); + } + + /** + * Return the list of BeanFactoryPostProcessors that will get applied + * to the internal BeanFactory. + * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor + */ + public List getBeanFactoryPostProcessors() { + return this.beanFactoryPostProcessors; + } + + public void addApplicationListener(ApplicationListener listener) { + this.applicationListeners.add(listener); + } + + /** + * Return the list of statically specified ApplicationListeners. + * @see org.springframework.context.ApplicationListener + */ + public List getApplicationListeners() { + return this.applicationListeners; + } + + + public void refresh() throws BeansException, IllegalStateException { + synchronized (this.startupShutdownMonitor) { + // Prepare this context for refreshing. + prepareRefresh(); + + // Tell the subclass to refresh the internal bean factory. + ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); + + // Prepare the bean factory for use in this context. + prepareBeanFactory(beanFactory); + + try { + // Allows post-processing of the bean factory in context subclasses. + postProcessBeanFactory(beanFactory); + + // Invoke factory processors registered as beans in the context. + invokeBeanFactoryPostProcessors(beanFactory); + + // Register bean processors that intercept bean creation. + registerBeanPostProcessors(beanFactory); + + // Initialize message source for this context. + initMessageSource(); + + // Initialize event multicaster for this context. + initApplicationEventMulticaster(); + + // Initialize other special beans in specific context subclasses. + onRefresh(); + + // Check for listener beans and register them. + registerListeners(); + + // Instantiate all remaining (non-lazy-init) singletons. + finishBeanFactoryInitialization(beanFactory); + + // Last step: publish corresponding event. + finishRefresh(); + } + + catch (BeansException ex) { + // Destroy already created singletons to avoid dangling resources. + beanFactory.destroySingletons(); + + // Reset 'active' flag. + cancelRefresh(ex); + + // Propagate exception to caller. + throw ex; + } + } + } + + /** + * Prepare this context for refreshing, setting its startup date and + * active flag. + */ + protected void prepareRefresh() { + this.startupDate = System.currentTimeMillis(); + + synchronized (this.activeMonitor) { + this.active = true; + } + + if (logger.isInfoEnabled()) { + logger.info("Refreshing " + this); + } + } + + /** + * Tell the subclass to refresh the internal bean factory. + * @return the fresh BeanFactory instance + * @see #refreshBeanFactory() + * @see #getBeanFactory() + */ + protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { + refreshBeanFactory(); + ConfigurableListableBeanFactory beanFactory = getBeanFactory(); + + if (logger.isInfoEnabled()) { + logger.info("Bean factory for application context [" + getId() + "]: " + + ObjectUtils.identityToString(beanFactory)); + } + if (logger.isDebugEnabled()) { + logger.debug(beanFactory.getBeanDefinitionCount() + " beans defined in " + this); + } + + return beanFactory; + } + + /** + * Configure the factory's standard context characteristics, + * such as the context's ClassLoader and post-processors. + * @param beanFactory the BeanFactory to configure + */ + protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { + // Tell the internal bean factory to use the context's class loader. + beanFactory.setBeanClassLoader(getClassLoader()); + + // Populate the bean factory with context-specific resource editors. + beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this)); + + // Configure the bean factory with context callbacks. + beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); + beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); + beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); + beanFactory.ignoreDependencyInterface(MessageSourceAware.class); + beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); + + // BeanFactory interface not registered as resolvable type in a plain factory. + // MessageSource registered (and found for autowiring) as a bean. + beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); + beanFactory.registerResolvableDependency(ResourceLoader.class, this); + beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); + beanFactory.registerResolvableDependency(ApplicationContext.class, this); + + // Detect a LoadTimeWeaver and prepare for weaving, if found. + if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME) && JdkVersion.isAtLeastJava15()) { + // Register the (JDK 1.5 specific) LoadTimeWeaverAwareProcessor. + try { + Class ltwapClass = ClassUtils.forName( + "org.springframework.context.weaving.LoadTimeWeaverAwareProcessor", + AbstractApplicationContext.class.getClassLoader()); + BeanPostProcessor ltwap = (BeanPostProcessor) BeanUtils.instantiateClass(ltwapClass); + ((BeanFactoryAware) ltwap).setBeanFactory(beanFactory); + beanFactory.addBeanPostProcessor(ltwap); + } + catch (ClassNotFoundException ex) { + throw new IllegalStateException("Spring's LoadTimeWeaverAwareProcessor class is not available"); + } + // Set a temporary ClassLoader for type matching. + beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); + } + } + + /** + * Modify the application context's internal bean factory after its standard + * initialization. All bean definitions will have been loaded, but no beans + * will have been instantiated yet. This allows for registering special + * BeanPostProcessors etc in certain ApplicationContext implementations. + * @param beanFactory the bean factory used by the application context + */ + protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { + } + + /** + * Instantiate and invoke all registered BeanFactoryPostProcessor beans, + * respecting explicit order if given. + *

    Must be called before singleton instantiation. + */ + protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { + // Invoke factory processors registered with the context instance. + for (Iterator it = getBeanFactoryPostProcessors().iterator(); it.hasNext();) { + BeanFactoryPostProcessor factoryProcessor = (BeanFactoryPostProcessor) it.next(); + factoryProcessor.postProcessBeanFactory(beanFactory); + } + + // Do not initialize FactoryBeans here: We need to leave all regular beans + // uninitialized to let the bean factory post-processors apply to them! + String[] postProcessorNames = + beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); + + // Separate between BeanFactoryPostProcessors that implement PriorityOrdered, + // Ordered, and the rest. + List priorityOrderedPostProcessors = new ArrayList(); + List orderedPostProcessorNames = new ArrayList(); + List nonOrderedPostProcessorNames = new ArrayList(); + for (int i = 0; i < postProcessorNames.length; i++) { + if (isTypeMatch(postProcessorNames[i], PriorityOrdered.class)) { + priorityOrderedPostProcessors.add(beanFactory.getBean(postProcessorNames[i])); + } + else if (isTypeMatch(postProcessorNames[i], Ordered.class)) { + orderedPostProcessorNames.add(postProcessorNames[i]); + } + else { + nonOrderedPostProcessorNames.add(postProcessorNames[i]); + } + } + + // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. + Collections.sort(priorityOrderedPostProcessors, new OrderComparator()); + invokeBeanFactoryPostProcessors(beanFactory, priorityOrderedPostProcessors); + + // Next, invoke the BeanFactoryPostProcessors that implement Ordered. + List orderedPostProcessors = new ArrayList(); + for (Iterator it = orderedPostProcessorNames.iterator(); it.hasNext();) { + String postProcessorName = (String) it.next(); + orderedPostProcessors.add(getBean(postProcessorName)); + } + Collections.sort(orderedPostProcessors, new OrderComparator()); + invokeBeanFactoryPostProcessors(beanFactory, orderedPostProcessors); + + // Finally, invoke all other BeanFactoryPostProcessors. + List nonOrderedPostProcessors = new ArrayList(); + for (Iterator it = nonOrderedPostProcessorNames.iterator(); it.hasNext();) { + String postProcessorName = (String) it.next(); + nonOrderedPostProcessors.add(getBean(postProcessorName)); + } + invokeBeanFactoryPostProcessors(beanFactory, nonOrderedPostProcessors); + } + + /** + * Invoke the given BeanFactoryPostProcessor beans. + */ + private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List postProcessors) { + for (Iterator it = postProcessors.iterator(); it.hasNext();) { + BeanFactoryPostProcessor postProcessor = (BeanFactoryPostProcessor) it.next(); + postProcessor.postProcessBeanFactory(beanFactory); + } + } + + /** + * Instantiate and invoke all registered BeanPostProcessor beans, + * respecting explicit order if given. + *

    Must be called before any instantiation of application beans. + */ + protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { + String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); + + // Register BeanPostProcessorChecker that logs an info message when + // a bean is created during BeanPostProcessor instantiation, i.e. when + // a bean is not eligible for getting processed by all BeanPostProcessors. + int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; + beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); + + // Separate between BeanPostProcessors that implement PriorityOrdered, + // Ordered, and the rest. + List priorityOrderedPostProcessors = new ArrayList(); + List orderedPostProcessorNames = new ArrayList(); + List nonOrderedPostProcessorNames = new ArrayList(); + for (int i = 0; i < postProcessorNames.length; i++) { + if (isTypeMatch(postProcessorNames[i], PriorityOrdered.class)) { + priorityOrderedPostProcessors.add(beanFactory.getBean(postProcessorNames[i])); + } + else if (isTypeMatch(postProcessorNames[i], Ordered.class)) { + orderedPostProcessorNames.add(postProcessorNames[i]); + } + else { + nonOrderedPostProcessorNames.add(postProcessorNames[i]); + } + } + + // First, register the BeanPostProcessors that implement PriorityOrdered. + Collections.sort(priorityOrderedPostProcessors, new OrderComparator()); + registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); + + // Next, register the BeanPostProcessors that implement Ordered. + List orderedPostProcessors = new ArrayList(); + for (Iterator it = orderedPostProcessorNames.iterator(); it.hasNext();) { + String postProcessorName = (String) it.next(); + orderedPostProcessors.add(getBean(postProcessorName)); + } + Collections.sort(orderedPostProcessors, new OrderComparator()); + registerBeanPostProcessors(beanFactory, orderedPostProcessors); + + // Finally, register all other BeanPostProcessors. + List nonOrderedPostProcessors = new ArrayList(); + for (Iterator it = nonOrderedPostProcessorNames.iterator(); it.hasNext();) { + String postProcessorName = (String) it.next(); + nonOrderedPostProcessors.add(getBean(postProcessorName)); + } + registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); + } + + /** + * Register the given BeanPostProcessor beans. + */ + private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, List postProcessors) { + for (Iterator it = postProcessors.iterator(); it.hasNext();) { + BeanPostProcessor postProcessor = (BeanPostProcessor) it.next(); + beanFactory.addBeanPostProcessor(postProcessor); + } + } + + /** + * Initialize the MessageSource. + * Use parent's if none defined in this context. + */ + protected void initMessageSource() { + ConfigurableListableBeanFactory beanFactory = getBeanFactory(); + if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { + this.messageSource = (MessageSource) beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); + // Make MessageSource aware of parent MessageSource. + if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { + HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; + if (hms.getParentMessageSource() == null) { + // Only set parent context as parent MessageSource if no parent MessageSource + // registered already. + hms.setParentMessageSource(getInternalParentMessageSource()); + } + } + if (logger.isDebugEnabled()) { + logger.debug("Using MessageSource [" + this.messageSource + "]"); + } + } + else { + // Use empty MessageSource to be able to accept getMessage calls. + DelegatingMessageSource dms = new DelegatingMessageSource(); + dms.setParentMessageSource(getInternalParentMessageSource()); + this.messageSource = dms; + beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); + if (logger.isDebugEnabled()) { + logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME + + "': using default [" + this.messageSource + "]"); + } + } + } + + /** + * Initialize the ApplicationEventMulticaster. + * Uses SimpleApplicationEventMulticaster if none defined in the context. + * @see org.springframework.context.event.SimpleApplicationEventMulticaster + */ + protected void initApplicationEventMulticaster() { + ConfigurableListableBeanFactory beanFactory = getBeanFactory(); + if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { + this.applicationEventMulticaster = (ApplicationEventMulticaster) + beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); + if (logger.isDebugEnabled()) { + logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); + } + } + else { + this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(); + beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); + if (logger.isDebugEnabled()) { + logger.debug("Unable to locate ApplicationEventMulticaster with name '" + + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + + "': using default [" + this.applicationEventMulticaster + "]"); + } + } + } + + /** + * Template method which can be overridden to add context-specific refresh work. + * Called on initialization of special beans, before instantiation of singletons. + *

    This implementation is empty. + * @throws BeansException in case of errors + * @see #refresh() + */ + protected void onRefresh() throws BeansException { + // For subclasses: do nothing by default. + } + + /** + * Add beans that implement ApplicationListener as listeners. + * Doesn't affect other listeners, which can be added without being beans. + */ + protected void registerListeners() { + // Register statically specified listeners first. + for (Iterator it = getApplicationListeners().iterator(); it.hasNext();) { + addListener((ApplicationListener) it.next()); + } + // Do not initialize FactoryBeans here: We need to leave all regular beans + // uninitialized to let post-processors apply to them! + Collection listenerBeans = getBeansOfType(ApplicationListener.class, true, false).values(); + for (Iterator it = listenerBeans.iterator(); it.hasNext();) { + addListener((ApplicationListener) it.next()); + } + } + + /** + * Subclasses can invoke this method to register a listener. + * Any beans in the context that are listeners are automatically added. + * @param listener the listener to register + */ + protected void addListener(ApplicationListener listener) { + getApplicationEventMulticaster().addApplicationListener(listener); + } + + /** + * Finish the initialization of this context's bean factory, + * initializing all remaining singleton beans. + */ + protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { + // Stop using the temporary ClassLoader for type matching. + beanFactory.setTempClassLoader(null); + + // Allow for caching all bean definition metadata, not expecting further changes. + beanFactory.freezeConfiguration(); + + // Instantiate all remaining (non-lazy-init) singletons. + beanFactory.preInstantiateSingletons(); + } + + /** + * Finish the refresh of this context, publishing the + * {@link org.springframework.context.event.ContextRefreshedEvent}. + */ + protected void finishRefresh() { + publishEvent(new ContextRefreshedEvent(this)); + } + + /** + * Cancel this context's refresh attempt, resetting the active flag + * after an exception got thrown. + * @param ex the exception that led to the cancellation + */ + protected void cancelRefresh(BeansException ex) { + synchronized (this.activeMonitor) { + this.active = false; + } + } + + + /** + * Register a shutdown hook with the JVM runtime, closing this context + * on JVM shutdown unless it has already been closed at that time. + *

    Delegates to doClose() for the actual closing procedure. + * @see java.lang.Runtime#addShutdownHook + * @see #close() + * @see #doClose() + */ + public void registerShutdownHook() { + if (this.shutdownHook == null) { + // No shutdown hook registered yet. + this.shutdownHook = new Thread() { + public void run() { + doClose(); + } + }; + Runtime.getRuntime().addShutdownHook(this.shutdownHook); + } + } + + /** + * DisposableBean callback for destruction of this instance. + * Only called when the ApplicationContext itself is running + * as a bean in another BeanFactory or ApplicationContext, + * which is rather unusual. + *

    The close method is the native way to + * shut down an ApplicationContext. + * @see #close() + * @see org.springframework.beans.factory.access.SingletonBeanFactoryLocator + */ + public void destroy() { + close(); + } + + /** + * Close this application context, destroying all beans in its bean factory. + *

    Delegates to doClose() for the actual closing procedure. + * Also removes a JVM shutdown hook, if registered, as it's not needed anymore. + * @see #doClose() + * @see #registerShutdownHook() + */ + public void close() { + synchronized (this.startupShutdownMonitor) { + doClose(); + // If we registered a JVM shutdown hook, we don't need it anymore now: + // We've already explicitly closed the context. + if (this.shutdownHook != null) { + Runtime.getRuntime().removeShutdownHook(this.shutdownHook); + } + } + } + + /** + * Actually performs context closing: publishes a ContextClosedEvent and + * destroys the singletons in the bean factory of this application context. + *

    Called by both close() and a JVM shutdown hook, if any. + * @see org.springframework.context.event.ContextClosedEvent + * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#destroySingletons() + * @see #close() + * @see #registerShutdownHook() + */ + protected void doClose() { + if (isActive()) { + if (logger.isInfoEnabled()) { + logger.info("Closing " + this); + } + try { + // Publish shutdown event. + publishEvent(new ContextClosedEvent(this)); + } + catch (Throwable ex) { + logger.error("Exception thrown from ApplicationListener handling ContextClosedEvent", ex); + } + // Stop all Lifecycle beans, to avoid delays during individual destruction. + Map lifecycleBeans = getLifecycleBeans(); + for (Iterator it = new LinkedHashSet(lifecycleBeans.keySet()).iterator(); it.hasNext();) { + String beanName = (String) it.next(); + doStop(lifecycleBeans, beanName); + } + // Destroy all cached singletons in the context's BeanFactory. + destroyBeans(); + // Close the state of this context itself. + closeBeanFactory(); + onClose(); + synchronized (this.activeMonitor) { + this.active = false; + } + } + } + + /** + * Template method for destroying all beans that this context manages. + * The default implementation destroy all cached singletons in this context, + * invoking DisposableBean.destroy() and/or the specified + * "destroy-method". + *

    Can be overridden to add context-specific bean destruction steps + * right before or right after standard singleton destruction, + * while the context's BeanFactory is still active. + * @see #getBeanFactory() + * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#destroySingletons() + */ + protected void destroyBeans() { + getBeanFactory().destroySingletons(); + } + + /** + * Template method which can be overridden to add context-specific shutdown work. + * The default implementation is empty. + *

    Called at the end of {@link #doClose}'s shutdown procedure, after + * this context's BeanFactory has been closed. If custom shutdown logic + * needs to execute while the BeanFactory is still active, override + * the {@link #destroyBeans()} method instead. + */ + protected void onClose() { + // For subclasses: do nothing by default. + } + + public boolean isActive() { + synchronized (this.activeMonitor) { + return this.active; + } + } + + + //--------------------------------------------------------------------- + // Implementation of BeanFactory interface + //--------------------------------------------------------------------- + + public Object getBean(String name) throws BeansException { + return getBeanFactory().getBean(name); + } + + public Object getBean(String name, Class requiredType) throws BeansException { + return getBeanFactory().getBean(name, requiredType); + } + + public Object getBean(String name, Object[] args) throws BeansException { + return getBeanFactory().getBean(name, args); + } + + public boolean containsBean(String name) { + return getBeanFactory().containsBean(name); + } + + public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { + return getBeanFactory().isSingleton(name); + } + + public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { + return getBeanFactory().isPrototype(name); + } + + public boolean isTypeMatch(String name, Class targetType) throws NoSuchBeanDefinitionException { + return getBeanFactory().isTypeMatch(name, targetType); + } + + public Class getType(String name) throws NoSuchBeanDefinitionException { + return getBeanFactory().getType(name); + } + + public String[] getAliases(String name) { + return getBeanFactory().getAliases(name); + } + + + //--------------------------------------------------------------------- + // Implementation of ListableBeanFactory interface + //--------------------------------------------------------------------- + + public boolean containsBeanDefinition(String name) { + return getBeanFactory().containsBeanDefinition(name); + } + + public int getBeanDefinitionCount() { + return getBeanFactory().getBeanDefinitionCount(); + } + + public String[] getBeanDefinitionNames() { + return getBeanFactory().getBeanDefinitionNames(); + } + + public String[] getBeanNamesForType(Class type) { + return getBeanFactory().getBeanNamesForType(type); + } + + public String[] getBeanNamesForType(Class type, boolean includePrototypes, boolean allowEagerInit) { + return getBeanFactory().getBeanNamesForType(type, includePrototypes, allowEagerInit); + } + + public Map getBeansOfType(Class type) throws BeansException { + return getBeanFactory().getBeansOfType(type); + } + + public Map getBeansOfType(Class type, boolean includePrototypes, boolean allowEagerInit) + throws BeansException { + + return getBeanFactory().getBeansOfType(type, includePrototypes, allowEagerInit); + } + + + //--------------------------------------------------------------------- + // Implementation of HierarchicalBeanFactory interface + //--------------------------------------------------------------------- + + public BeanFactory getParentBeanFactory() { + return getParent(); + } + + public boolean containsLocalBean(String name) { + return getBeanFactory().containsLocalBean(name); + } + + /** + * Return the internal bean factory of the parent context if it implements + * ConfigurableApplicationContext; else, return the parent context itself. + * @see org.springframework.context.ConfigurableApplicationContext#getBeanFactory + */ + protected BeanFactory getInternalParentBeanFactory() { + return (getParent() instanceof ConfigurableApplicationContext) ? + ((ConfigurableApplicationContext) getParent()).getBeanFactory() : (BeanFactory) getParent(); + } + + + //--------------------------------------------------------------------- + // Implementation of MessageSource interface + //--------------------------------------------------------------------- + + public String getMessage(String code, Object args[], String defaultMessage, Locale locale) { + return getMessageSource().getMessage(code, args, defaultMessage, locale); + } + + public String getMessage(String code, Object args[], Locale locale) throws NoSuchMessageException { + return getMessageSource().getMessage(code, args, locale); + } + + public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException { + return getMessageSource().getMessage(resolvable, locale); + } + + /** + * Return the internal MessageSource used by the context. + * @return the internal MessageSource (never null) + * @throws IllegalStateException if the context has not been initialized yet + */ + private MessageSource getMessageSource() throws IllegalStateException { + if (this.messageSource == null) { + throw new IllegalStateException("MessageSource not initialized - " + + "call 'refresh' before accessing messages via the context: " + this); + } + return this.messageSource; + } + + /** + * Return the internal message source of the parent context if it is an + * AbstractApplicationContext too; else, return the parent context itself. + */ + protected MessageSource getInternalParentMessageSource() { + return (getParent() instanceof AbstractApplicationContext) ? + ((AbstractApplicationContext) getParent()).messageSource : getParent(); + } + + + //--------------------------------------------------------------------- + // Implementation of ResourcePatternResolver interface + //--------------------------------------------------------------------- + + public Resource[] getResources(String locationPattern) throws IOException { + return this.resourcePatternResolver.getResources(locationPattern); + } + + + //--------------------------------------------------------------------- + // Implementation of Lifecycle interface + //--------------------------------------------------------------------- + + public void start() { + Map lifecycleBeans = getLifecycleBeans(); + for (Iterator it = new LinkedHashSet(lifecycleBeans.keySet()).iterator(); it.hasNext();) { + String beanName = (String) it.next(); + doStart(lifecycleBeans, beanName); + } + publishEvent(new ContextStartedEvent(this)); + } + + public void stop() { + Map lifecycleBeans = getLifecycleBeans(); + for (Iterator it = new LinkedHashSet(lifecycleBeans.keySet()).iterator(); it.hasNext();) { + String beanName = (String) it.next(); + doStop(lifecycleBeans, beanName); + } + publishEvent(new ContextStoppedEvent(this)); + } + + public boolean isRunning() { + Iterator it = getLifecycleBeans().values().iterator(); + while (it.hasNext()) { + Lifecycle lifecycle = (Lifecycle) it.next(); + if (!lifecycle.isRunning()) { + return false; + } + } + return true; + } + + /** + * Return a Map of all singleton beans that implement the + * Lifecycle interface in this context. + * @return Map of Lifecycle beans with bean name as key + */ + private Map getLifecycleBeans() { + ConfigurableListableBeanFactory beanFactory = getBeanFactory(); + String[] beanNames = beanFactory.getSingletonNames(); + Map beans = new LinkedHashMap(); + for (int i = 0; i < beanNames.length; i++) { + Object bean = beanFactory.getSingleton(beanNames[i]); + if (bean instanceof Lifecycle) { + beans.put(beanNames[i], bean); + } + } + return beans; + } + + /** + * Start the specified bean as part of the given set of Lifecycle beans, + * making sure that any beans that it depends on are started first. + * @param lifecycleBeans Map with bean name as key and Lifecycle instance as value + * @param beanName the name of the bean to start + */ + private void doStart(Map lifecycleBeans, String beanName) { + Lifecycle bean = (Lifecycle) lifecycleBeans.get(beanName); + if (bean != null) { + String[] dependenciesForBean = getBeanFactory().getDependenciesForBean(beanName); + for (int i = 0; i < dependenciesForBean.length; i++) { + doStart(lifecycleBeans, dependenciesForBean[i]); + } + if (!bean.isRunning()) { + bean.start(); + } + lifecycleBeans.remove(beanName); + } + } + + /** + * Stop the specified bean as part of the given set of Lifecycle beans, + * making sure that any beans that depends on it are stopped first. + * @param lifecycleBeans Map with bean name as key and Lifecycle instance as value + * @param beanName the name of the bean to stop + */ + private void doStop(Map lifecycleBeans, String beanName) { + Lifecycle bean = (Lifecycle) lifecycleBeans.get(beanName); + if (bean != null) { + String[] dependentBeans = getBeanFactory().getDependentBeans(beanName); + for (int i = 0; i < dependentBeans.length; i++) { + doStop(lifecycleBeans, dependentBeans[i]); + } + if (bean.isRunning()) { + bean.stop(); + } + lifecycleBeans.remove(beanName); + } + } + + + //--------------------------------------------------------------------- + // Abstract methods that must be implemented by subclasses + //--------------------------------------------------------------------- + + /** + * Subclasses must implement this method to perform the actual configuration load. + * The method is invoked by {@link #refresh()} before any other initialization work. + *

    A subclass will either create a new bean factory and hold a reference to it, + * or return a single BeanFactory instance that it holds. In the latter case, it will + * usually throw an IllegalStateException if refreshing the context more than once. + * @throws BeansException if initialization of the bean factory failed + * @throws IllegalStateException if already initialized and multiple refresh + * attempts are not supported + */ + protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException; + + /** + * Subclasses must implement this method to release their internal bean factory. + * This method gets invoked by {@link #close()} after all other shutdown work. + *

    Should never throw an exception but rather log shutdown failures. + */ + protected abstract void closeBeanFactory(); + + /** + * Subclasses must return their internal bean factory here. They should implement the + * lookup efficiently, so that it can be called repeatedly without a performance penalty. + *

    Note: Subclasses should check whether the context is still active before + * returning the internal bean factory. The internal factory should generally be + * considered unavailable once the context has been closed. + * @return this application context's internal bean factory (never null) + * @throws IllegalStateException if the context does not hold an internal bean factory yet + * (usually if {@link #refresh()} has never been called) or if the context has been + * closed already + * @see #refreshBeanFactory() + * @see #closeBeanFactory() + */ + public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException; + + + /** + * Return information about this context. + */ + public String toString() { + StringBuffer sb = new StringBuffer(getId()); + sb.append(": display name [").append(getDisplayName()); + sb.append("]; startup date [").append(new Date(getStartupDate())); + sb.append("]; "); + ApplicationContext parent = getParent(); + if (parent == null) { + sb.append("root of context hierarchy"); + } + else { + sb.append("parent: ").append(parent.getId()); + } + return sb.toString(); + } + + + /** + * BeanPostProcessor that logs an info message when a bean is created during + * BeanPostProcessor instantiation, i.e. when a bean is not eligible for + * getting processed by all BeanPostProcessors. + */ + private class BeanPostProcessorChecker implements BeanPostProcessor { + + private final ConfigurableListableBeanFactory beanFactory; + + private final int beanPostProcessorTargetCount; + + public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) { + this.beanFactory = beanFactory; + this.beanPostProcessorTargetCount = beanPostProcessorTargetCount; + } + + public Object postProcessBeforeInitialization(Object bean, String beanName) { + return bean; + } + + public Object postProcessAfterInitialization(Object bean, String beanName) { + if (!(bean instanceof BeanPostProcessor) && + this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) { + if (logger.isInfoEnabled()) { + logger.info("Bean '" + beanName + "' is not eligible for getting processed by all " + + "BeanPostProcessors (for example: not eligible for auto-proxying)"); + } + } + return bean; + } + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/AbstractMessageSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/AbstractMessageSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/AbstractMessageSource.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,348 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.springframework.context.HierarchicalMessageSource; +import org.springframework.context.MessageSource; +import org.springframework.context.MessageSourceResolvable; +import org.springframework.context.NoSuchMessageException; +import org.springframework.util.ObjectUtils; + +/** + * Abstract implementation of the {@link HierarchicalMessageSource} interface, + * implementing common handling of message variants, making it easy + * to implement a specific strategy for a concrete MessageSource. + * + *

    Subclasses must implement the abstract {@link #resolveCode} + * method. For efficient resolution of messages without arguments, the + * {@link #resolveCodeWithoutArguments} method should be overridden + * as well, resolving messages without a MessageFormat being involved. + * + *

    Note: By default, message texts are only parsed through + * MessageFormat if arguments have been passed in for the message. In case + * of no arguments, message texts will be returned as-is. As a consequence, + * you should only use MessageFormat escaping for messages with actual + * arguments, and keep all other messages unescaped. If you prefer to + * escape all messages, set the "alwaysUseMessageFormat" flag to "true". + * + *

    Supports not only MessageSourceResolvables as primary messages + * but also resolution of message arguments that are in turn + * MessageSourceResolvables themselves. + * + *

    This class does not implement caching of messages per code, thus + * subclasses can dynamically change messages over time. Subclasses are + * encouraged to cache their messages in a modification-aware fashion, + * allowing for hot deployment of updated messages. + * + * @author Juergen Hoeller + * @author Rod Johnson + * @see #resolveCode(String, java.util.Locale) + * @see #resolveCodeWithoutArguments(String, java.util.Locale) + * @see #setAlwaysUseMessageFormat + * @see java.text.MessageFormat + */ +public abstract class AbstractMessageSource extends MessageSourceSupport implements HierarchicalMessageSource { + + private MessageSource parentMessageSource; + + private boolean useCodeAsDefaultMessage = false; + + + public void setParentMessageSource(MessageSource parent) { + this.parentMessageSource = parent; + } + + public MessageSource getParentMessageSource() { + return this.parentMessageSource; + } + + /** + * Set whether to use the message code as default message instead of + * throwing a NoSuchMessageException. Useful for development and debugging. + * Default is "false". + *

    Note: In case of a MessageSourceResolvable with multiple codes + * (like a FieldError) and a MessageSource that has a parent MessageSource, + * do not activate "useCodeAsDefaultMessage" in the parent: + * Else, you'll get the first code returned as message by the parent, + * without attempts to check further codes. + *

    To be able to work with "useCodeAsDefaultMessage" turned on in the parent, + * AbstractMessageSource and AbstractApplicationContext contain special checks + * to delegate to the internal getMessageInternal method if available. + * In general, it is recommended to just use "useCodeAsDefaultMessage" during + * development and not rely on it in production in the first place, though. + * @see #getMessage(String, Object[], Locale) + * @see #getMessageInternal + * @see org.springframework.validation.FieldError + */ + public void setUseCodeAsDefaultMessage(boolean useCodeAsDefaultMessage) { + this.useCodeAsDefaultMessage = useCodeAsDefaultMessage; + } + + /** + * Return whether to use the message code as default message instead of + * throwing a NoSuchMessageException. Useful for development and debugging. + * Default is "false". + *

    Alternatively, consider overriding the getDefaultMessage + * method to return a custom fallback message for an unresolvable code. + * @see #getDefaultMessage(String) + */ + protected boolean isUseCodeAsDefaultMessage() { + return this.useCodeAsDefaultMessage; + } + + + public final String getMessage(String code, Object[] args, String defaultMessage, Locale locale) { + String msg = getMessageInternal(code, args, locale); + if (msg != null) { + return msg; + } + if (defaultMessage == null) { + String fallback = getDefaultMessage(code); + if (fallback != null) { + return fallback; + } + } + return renderDefaultMessage(defaultMessage, args, locale); + } + + public final String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException { + String msg = getMessageInternal(code, args, locale); + if (msg != null) { + return msg; + } + String fallback = getDefaultMessage(code); + if (fallback != null) { + return fallback; + } + throw new NoSuchMessageException(code, locale); + } + + public final String getMessage(MessageSourceResolvable resolvable, Locale locale) + throws NoSuchMessageException { + + String[] codes = resolvable.getCodes(); + if (codes == null) { + codes = new String[0]; + } + for (int i = 0; i < codes.length; i++) { + String msg = getMessageInternal(codes[i], resolvable.getArguments(), locale); + if (msg != null) { + return msg; + } + } + if (resolvable.getDefaultMessage() != null) { + return renderDefaultMessage(resolvable.getDefaultMessage(), resolvable.getArguments(), locale); + } + if (codes.length > 0) { + String fallback = getDefaultMessage(codes[0]); + if (fallback != null) { + return fallback; + } + } + throw new NoSuchMessageException(codes.length > 0 ? codes[codes.length - 1] : null, locale); + } + + + /** + * Resolve the given code and arguments as message in the given Locale, + * returning null if not found. Does not fall back to + * the code as default message. Invoked by getMessage methods. + * @param code the code to lookup up, such as 'calculator.noRateSet' + * @param args array of arguments that will be filled in for params + * within the message + * @param locale the Locale in which to do the lookup + * @return the resolved message, or null if not found + * @see #getMessage(String, Object[], String, Locale) + * @see #getMessage(String, Object[], Locale) + * @see #getMessage(MessageSourceResolvable, Locale) + * @see #setUseCodeAsDefaultMessage + */ + protected String getMessageInternal(String code, Object[] args, Locale locale) { + if (code == null) { + return null; + } + if (locale == null) { + locale = Locale.getDefault(); + } + Object[] argsToUse = args; + + if (!isAlwaysUseMessageFormat() && ObjectUtils.isEmpty(args)) { + // Optimized resolution: no arguments to apply, + // therefore no MessageFormat needs to be involved. + // Note that the default implementation still uses MessageFormat; + // this can be overridden in specific subclasses. + String message = resolveCodeWithoutArguments(code, locale); + if (message != null) { + return message; + } + } + + else { + // Resolve arguments eagerly, for the case where the message + // is defined in a parent MessageSource but resolvable arguments + // are defined in the child MessageSource. + argsToUse = resolveArguments(args, locale); + + MessageFormat messageFormat = resolveCode(code, locale); + if (messageFormat != null) { + synchronized (messageFormat) { + return messageFormat.format(argsToUse); + } + } + } + + // Not found -> check parent, if any. + return getMessageFromParent(code, argsToUse, locale); + } + + /** + * Try to retrieve the given message from the parent MessageSource, if any. + * @param code the code to lookup up, such as 'calculator.noRateSet' + * @param args array of arguments that will be filled in for params + * within the message + * @param locale the Locale in which to do the lookup + * @return the resolved message, or null if not found + * @see #getParentMessageSource() + */ + protected String getMessageFromParent(String code, Object[] args, Locale locale) { + MessageSource parent = getParentMessageSource(); + if (parent != null) { + if (parent instanceof AbstractMessageSource) { + // Call internal method to avoid getting the default code back + // in case of "useCodeAsDefaultMessage" being activated. + return ((AbstractMessageSource) parent).getMessageInternal(code, args, locale); + } + else { + // Check parent MessageSource, returning null if not found there. + return parent.getMessage(code, args, null, locale); + } + } + // Not found in parent either. + return null; + } + + /** + * Return a fallback default message for the given code, if any. + *

    Default is to return the code itself if "useCodeAsDefaultMessage" + * is activated, or return no fallback else. In case of no fallback, + * the caller will usually receive a NoSuchMessageException from + * getMessage. + * @param code the message code that we couldn't resolve + * and that we didn't receive an explicit default message for + * @return the default message to use, or null if none + * @see #setUseCodeAsDefaultMessage + */ + protected String getDefaultMessage(String code) { + if (isUseCodeAsDefaultMessage()) { + return code; + } + return null; + } + + /** + * Render the given default message String. The default message is + * passed in as specified by the caller and can be rendered into + * a fully formatted default message shown to the user. + *

    The default implementation passes the String to formatMessage, + * resolving any argument placeholders found in them. Subclasses may override + * this method to plug in custom processing of default messages. + * @param defaultMessage the passed-in default message String + * @param args array of arguments that will be filled in for params within + * the message, or null if none. + * @param locale the Locale used for formatting + * @return the rendered default message (with resolved arguments) + * @see #formatMessage(String, Object[], java.util.Locale) + */ + protected String renderDefaultMessage(String defaultMessage, Object[] args, Locale locale) { + return formatMessage(defaultMessage, args, locale); + } + + + /** + * Searches through the given array of objects, find any + * MessageSourceResolvable objects and resolve them. + *

    Allows for messages to have MessageSourceResolvables as arguments. + * @param args array of arguments for a message + * @param locale the locale to resolve through + * @return an array of arguments with any MessageSourceResolvables resolved + */ + protected Object[] resolveArguments(Object[] args, Locale locale) { + if (args == null) { + return new Object[0]; + } + List resolvedArgs = new ArrayList(args.length); + for (int i = 0; i < args.length; i++) { + if (args[i] instanceof MessageSourceResolvable) { + resolvedArgs.add(getMessage((MessageSourceResolvable) args[i], locale)); + } + else { + resolvedArgs.add(args[i]); + } + } + return resolvedArgs.toArray(new Object[resolvedArgs.size()]); + } + + /** + * Subclasses can override this method to resolve a message without + * arguments in an optimized fashion, that is, to resolve a message + * without involving a MessageFormat. + *

    The default implementation does use MessageFormat, + * through delegating to the resolveCode method. + * Subclasses are encouraged to replace this with optimized resolution. + *

    Unfortunately, java.text.MessageFormat is not + * implemented in an efficient fashion. In particular, it does not + * detect that a message pattern doesn't contain argument placeholders + * in the first place. Therefore, it's advisable to circumvent + * MessageFormat completely for messages without arguments. + * @param code the code of the message to resolve + * @param locale the Locale to resolve the code for + * (subclasses are encouraged to support internationalization) + * @return the message String, or null if not found + * @see #resolveCode + * @see java.text.MessageFormat + */ + protected String resolveCodeWithoutArguments(String code, Locale locale) { + MessageFormat messageFormat = resolveCode(code, locale); + if (messageFormat != null) { + synchronized (messageFormat) { + return messageFormat.format(new Object[0]); + } + } + return null; + } + + /** + * Subclasses must implement this method to resolve a message. + *

    Returns a MessageFormat instance rather than a message String, + * to allow for appropriate caching of MessageFormats in subclasses. + *

    Subclasses are encouraged to provide optimized resolution + * for messages without arguments, not involving MessageFormat. + * See resolveCodeWithoutArguments javadoc for details. + * @param code the code of the message to resolve + * @param locale the Locale to resolve the code for + * (subclasses are encouraged to support internationalization) + * @return the MessageFormat for the message, or null if not found + * @see #resolveCodeWithoutArguments(String, java.util.Locale) + */ + protected abstract MessageFormat resolveCode(String code, Locale locale); + +} Index: 3rdParty_sources/spring/org/springframework/context/support/AbstractRefreshableApplicationContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/AbstractRefreshableApplicationContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/AbstractRefreshableApplicationContext.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,214 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.io.IOException; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextException; + +/** + * Base class for {@link org.springframework.context.ApplicationContext} + * implementations which are supposed to support multiple refreshs, + * creating a new internal bean factory instance every time. + * Typically (but not necessarily), such a context will be driven by + * a set of config locations to load bean definitions from. + * + *

    The only method to be implemented by subclasses is {@link #loadBeanDefinitions}, + * which gets invoked on each refresh. A concrete implementation is supposed to load + * bean definitions into the given + * {@link org.springframework.beans.factory.support.DefaultListableBeanFactory}, + * typically delegating to one or more specific bean definition readers. + * + *

    Note that there is a similar base class for WebApplicationContexts. + * {@link org.springframework.web.context.support.AbstractRefreshableWebApplicationContext} + * provides the same subclassing strategy, but additionally pre-implements + * all context functionality for web environments. There is also a + * pre-defined way to receive config locations for a web context. + * + *

    Concrete standalone subclasses of this base class, reading in a + * specific bean definition format, are {@link ClassPathXmlApplicationContext} + * and {@link FileSystemXmlApplicationContext}, which both derive from the + * common {@link AbstractXmlApplicationContext} base class. + * + * @author Juergen Hoeller + * @since 1.1.3 + * @see #loadBeanDefinitions + * @see org.springframework.beans.factory.support.DefaultListableBeanFactory + * @see org.springframework.web.context.support.AbstractRefreshableWebApplicationContext + * @see AbstractXmlApplicationContext + * @see ClassPathXmlApplicationContext + * @see FileSystemXmlApplicationContext + */ +public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext { + + private Boolean allowBeanDefinitionOverriding; + + private Boolean allowCircularReferences; + + /** Bean factory for this context */ + private DefaultListableBeanFactory beanFactory; + + /** Synchronization monitor for the internal BeanFactory */ + private final Object beanFactoryMonitor = new Object(); + + + /** + * Create a new AbstractRefreshableApplicationContext with no parent. + */ + public AbstractRefreshableApplicationContext() { + } + + /** + * Create a new AbstractRefreshableApplicationContext with the given parent context. + * @param parent the parent context + */ + public AbstractRefreshableApplicationContext(ApplicationContext parent) { + super(parent); + } + + + /** + * Set whether it should be allowed to override bean definitions by registering + * a different definition with the same name, automatically replacing the former. + * If not, an exception will be thrown. Default is "true". + * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowBeanDefinitionOverriding + */ + public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) { + this.allowBeanDefinitionOverriding = Boolean.valueOf(allowBeanDefinitionOverriding); + } + + /** + * Set whether to allow circular references between beans - and automatically + * try to resolve them. + *

    Default is "true". Turn this off to throw an exception when encountering + * a circular reference, disallowing them completely. + * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowCircularReferences + */ + public void setAllowCircularReferences(boolean allowCircularReferences) { + this.allowCircularReferences = Boolean.valueOf(allowCircularReferences); + } + + + /** + * This implementation performs an actual refresh of this context's underlying + * bean factory, shutting down the previous bean factory (if any) and + * initializing a fresh bean factory for the next phase of the context's lifecycle. + */ + protected final void refreshBeanFactory() throws BeansException { + if (hasBeanFactory()) { + destroyBeans(); + closeBeanFactory(); + } + try { + DefaultListableBeanFactory beanFactory = createBeanFactory(); + customizeBeanFactory(beanFactory); + loadBeanDefinitions(beanFactory); + synchronized (this.beanFactoryMonitor) { + this.beanFactory = beanFactory; + } + } + catch (IOException ex) { + throw new ApplicationContextException( + "I/O error parsing XML document for application context [" + getDisplayName() + "]", ex); + } + } + + protected final void closeBeanFactory() { + synchronized (this.beanFactoryMonitor) { + this.beanFactory = null; + } + } + + /** + * Determine whether this context currently holds a bean factory, + * i.e. has been refreshed at least once and not been closed yet. + */ + protected final boolean hasBeanFactory() { + synchronized (this.beanFactoryMonitor) { + return (this.beanFactory != null); + } + } + + public final ConfigurableListableBeanFactory getBeanFactory() { + synchronized (this.beanFactoryMonitor) { + if (this.beanFactory == null) { + throw new IllegalStateException("BeanFactory not initialized or already closed - " + + "call 'refresh' before accessing beans via the ApplicationContext"); + } + return this.beanFactory; + } + } + + + /** + * Create an internal bean factory for this context. + * Called for each {@link #refresh()} attempt. + *

    The default implementation creates a + * {@link org.springframework.beans.factory.support.DefaultListableBeanFactory} + * with the {@link #getInternalParentBeanFactory() internal bean factory} of this + * context's parent as parent bean factory. Can be overridden in subclasses, + * for example to customize DefaultListableBeanFactory's settings. + * @return the bean factory for this context + * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowBeanDefinitionOverriding + * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowEagerClassLoading + * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowCircularReferences + * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowRawInjectionDespiteWrapping + */ + protected DefaultListableBeanFactory createBeanFactory() { + return new DefaultListableBeanFactory(getInternalParentBeanFactory()); + } + + /** + * Customize the internal bean factory used by this context. + * Called for each {@link #refresh()} attempt. + *

    The default implementation applies this context's + * {@link #setAllowBeanDefinitionOverriding "allowBeanDefinitionOverriding"} + * and {@link #setAllowCircularReferences "allowCircularReferences"} settings, + * if specified. Can be overridden in subclasses to customize any of + * {@link DefaultListableBeanFactory}'s settings. + * @param beanFactory the newly created bean factory for this context + * @see DefaultListableBeanFactory#setAllowBeanDefinitionOverriding + * @see DefaultListableBeanFactory#setAllowCircularReferences + * @see DefaultListableBeanFactory#setAllowRawInjectionDespiteWrapping + * @see DefaultListableBeanFactory#setAllowEagerClassLoading + */ + protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) { + if (this.allowBeanDefinitionOverriding != null) { + beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding.booleanValue()); + } + if (this.allowCircularReferences != null) { + beanFactory.setAllowCircularReferences(this.allowCircularReferences.booleanValue()); + } + } + + /** + * Load bean definitions into the given bean factory, typically through + * delegating to one or more bean definition readers. + * @param beanFactory the bean factory to load bean definitions into + * @throws IOException if loading of bean definition files failed + * @throws BeansException if parsing of the bean definitions failed + * @see org.springframework.beans.factory.support.PropertiesBeanDefinitionReader + * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader + */ + protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) + throws IOException, BeansException; + +} Index: 3rdParty_sources/spring/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,152 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import org.springframework.beans.factory.BeanNameAware; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.ApplicationContext; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; +import org.springframework.util.SystemPropertyUtils; + +/** + * {@link AbstractRefreshableApplicationContext} subclass that adds common handling + * of specified config locations. Serves as base class for XML-based application + * context implementations such as {@link ClassPathXmlApplicationContext} and + * {@link FileSystemXmlApplicationContext}, as well as + * {@link org.springframework.web.context.support.XmlWebApplicationContext} and + * {@link org.springframework.web.portlet.context.XmlPortletApplicationContext}. + * + * @author Juergen Hoeller + * @since 2.5.2 + * @see #setConfigLocation + * @see #setConfigLocations + * @see #getDefaultConfigLocations + */ +public abstract class AbstractRefreshableConfigApplicationContext extends AbstractRefreshableApplicationContext + implements BeanNameAware, InitializingBean { + + private String[] configLocations; + + private boolean setIdCalled = false; + + + /** + * Create a new AbstractRefreshableConfigApplicationContext with no parent. + */ + public AbstractRefreshableConfigApplicationContext() { + } + + /** + * Create a new AbstractRefreshableConfigApplicationContext with the given parent context. + * @param parent the parent context + */ + public AbstractRefreshableConfigApplicationContext(ApplicationContext parent) { + super(parent); + } + + + /** + * Set the config locations for this application context in init-param style, + * i.e. with distinct locations separated by commas, semicolons or whitespace. + *

    If not set, the implementation may use a default as appropriate. + */ + public void setConfigLocation(String location) { + setConfigLocations(StringUtils.tokenizeToStringArray(location, CONFIG_LOCATION_DELIMITERS)); + } + + /** + * Set the config locations for this application context. + *

    If not set, the implementation may use a default as appropriate. + */ + public void setConfigLocations(String[] locations) { + if (locations != null) { + Assert.noNullElements(locations, "Config locations must not be null"); + this.configLocations = new String[locations.length]; + for (int i = 0; i < locations.length; i++) { + this.configLocations[i] = resolvePath(locations[i]).trim(); + } + } + else { + this.configLocations = null; + } + } + + /** + * Return an array of resource locations, referring to the XML bean definition + * files that this context should be built with. Can also include location + * patterns, which will get resolved via a ResourcePatternResolver. + *

    The default implementation returns null. Subclasses can override + * this to provide a set of resource locations to load bean definitions from. + * @return an array of resource locations, or null if none + * @see #getResources + * @see #getResourcePatternResolver + */ + protected String[] getConfigLocations() { + return (this.configLocations != null ? this.configLocations : getDefaultConfigLocations()); + } + + /** + * Return the default config locations to use, for the case where no + * explicit config locations have been specified. + *

    The default implementation returns null, + * requiring explicit config locations. + * @return an array of default config locations, if any + * @see #setConfigLocations + */ + protected String[] getDefaultConfigLocations() { + return null; + } + + /** + * Resolve the given path, replacing placeholders with corresponding + * system property values if necessary. Applied to config locations. + * @param path the original file path + * @return the resolved file path + * @see org.springframework.util.SystemPropertyUtils#resolvePlaceholders + */ + protected String resolvePath(String path) { + return SystemPropertyUtils.resolvePlaceholders(path); + } + + + public void setId(String id) { + super.setId(id); + this.setIdCalled = true; + } + + /** + * Sets the id of this context to the bean name by default, + * for cases where the context instance is itself defined as a bean. + */ + public void setBeanName(String name) { + if (!this.setIdCalled) { + super.setId(name); + } + } + + /** + * Triggers {@link #refresh()} if not refreshed in the concrete context's + * constructor already. + */ + public void afterPropertiesSet() { + if (!isActive()) { + refresh(); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/AbstractXmlApplicationContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/AbstractXmlApplicationContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/AbstractXmlApplicationContext.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,129 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.io.IOException; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.beans.factory.xml.ResourceEntityResolver; +import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.Resource; + +/** + * Convenient base class for {@link org.springframework.context.ApplicationContext} + * implementations, drawing configuration from XML documents containing bean definitions + * understood by an {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}. + * + *

    Subclasses just have to implement the {@link #getConfigResources} and/or + * the {@link #getConfigLocations} method. Furthermore, they might override + * the {@link #getResourceByPath} hook to interpret relative paths in an + * environment-specific fashion, and/or {@link #getResourcePatternResolver} + * for extended pattern resolution. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see #getConfigResources + * @see #getConfigLocations + * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader + */ +public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext { + + /** + * Create a new AbstractXmlApplicationContext with no parent. + */ + public AbstractXmlApplicationContext() { + } + + /** + * Create a new AbstractXmlApplicationContext with the given parent context. + * @param parent the parent context + */ + public AbstractXmlApplicationContext(ApplicationContext parent) { + super(parent); + } + + + /** + * Loads the bean definitions via an XmlBeanDefinitionReader. + * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader + * @see #initBeanDefinitionReader + * @see #loadBeanDefinitions + */ + protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException { + // Create a new XmlBeanDefinitionReader for the given BeanFactory. + XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); + + // Configure the bean definition reader with this context's + // resource loading environment. + beanDefinitionReader.setResourceLoader(this); + beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); + + // Allow a subclass to provide custom initialization of the reader, + // then proceed with actually loading the bean definitions. + initBeanDefinitionReader(beanDefinitionReader); + loadBeanDefinitions(beanDefinitionReader); + } + + /** + * Initialize the bean definition reader used for loading the bean + * definitions of this context. Default implementation is empty. + *

    Can be overridden in subclasses, e.g. for turning off XML validation + * or using a different XmlBeanDefinitionParser implementation. + * @param beanDefinitionReader the bean definition reader used by this context + * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader#setDocumentReaderClass + */ + protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) { + } + + /** + * Load the bean definitions with the given XmlBeanDefinitionReader. + *

    The lifecycle of the bean factory is handled by the {@link #refreshBeanFactory} + * method; hence this method is just supposed to load and/or register bean definitions. + * @param reader the XmlBeanDefinitionReader to use + * @throws BeansException in case of bean registration errors + * @throws IOException if the required XML document isn't found + * @see #refreshBeanFactory + * @see #getConfigLocations + * @see #getResources + * @see #getResourcePatternResolver + */ + protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { + Resource[] configResources = getConfigResources(); + if (configResources != null) { + reader.loadBeanDefinitions(configResources); + } + String[] configLocations = getConfigLocations(); + if (configLocations != null) { + reader.loadBeanDefinitions(configLocations); + } + } + + /** + * Return an array of Resource objects, referring to the XML bean definition + * files that this context should be built with. + *

    The default implementation returns null. Subclasses can override + * this to provide pre-built Resource objects rather than location Strings. + * @return an array of Resource objects, or null if none + * @see #getConfigLocations() + */ + protected Resource[] getConfigResources() { + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/ApplicationContextAwareProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/ApplicationContextAwareProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/ApplicationContextAwareProcessor.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,79 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ApplicationEventPublisherAware; +import org.springframework.context.MessageSourceAware; +import org.springframework.context.ResourceLoaderAware; + +/** + * {@link org.springframework.beans.factory.config.BeanPostProcessor} + * implementation that passes the ApplicationContext to beans that + * implement the {@link ResourceLoaderAware}, {@link MessageSourceAware}, + * {@link ApplicationEventPublisherAware} and/or + * {@link ApplicationContextAware} interfaces. + * If all of them are implemented, they are satisfied in the given order. + * + *

    Application contexts will automatically register this with their + * underlying bean factory. Applications do not use this directly. + * + * @author Juergen Hoeller + * @since 10.10.2003 + * @see org.springframework.context.ResourceLoaderAware + * @see org.springframework.context.MessageSourceAware + * @see org.springframework.context.ApplicationEventPublisherAware + * @see org.springframework.context.ApplicationContextAware + * @see org.springframework.context.support.AbstractApplicationContext#refresh() + */ +class ApplicationContextAwareProcessor implements BeanPostProcessor { + + private final ApplicationContext applicationContext; + + + /** + * Create a new ApplicationContextAwareProcessor for the given context. + */ + public ApplicationContextAwareProcessor(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + if (bean instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext); + } + if (bean instanceof ApplicationEventPublisherAware) { + ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext); + } + if (bean instanceof MessageSourceAware) { + ((MessageSourceAware) bean).setMessageSource(this.applicationContext); + } + if (bean instanceof ApplicationContextAware) { + ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); + } + return bean; + } + + public Object postProcessAfterInitialization(Object bean, String name) { + return bean; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/ApplicationObjectSupport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/ApplicationObjectSupport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/ApplicationObjectSupport.java 17 Aug 2012 15:14:36 -0000 1.1 @@ -0,0 +1,159 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ApplicationContextException; + +/** + * Convenient superclass for application objects that want to be aware of + * the application context, e.g. for custom lookup of collaborating beans + * or for context-specific resource access. It saves the application + * context reference and provides an initialization callback method. + * Furthermore, it offers numerous convenience methods for message lookup. + * + *

    There is no requirement to subclass this class: It just makes things + * a little easier if you need access to the context, e.g. for access to + * file resources or to the message source. Note that many application + * objects do not need to be aware of the application context at all, + * as they can receive collaborating beans via bean references. + * + *

    Many framework classes are derived from this class, particularly + * within the web support. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see org.springframework.web.context.support.WebApplicationObjectSupport + */ +public abstract class ApplicationObjectSupport implements ApplicationContextAware { + + /** Logger that is available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + /** ApplicationContext this object runs in */ + private ApplicationContext applicationContext; + + /** MessageSourceAccessor for easy message access */ + private MessageSourceAccessor messageSourceAccessor; + + + public final void setApplicationContext(ApplicationContext context) throws BeansException { + if (context == null && !isContextRequired()) { + // Reset internal context state. + this.applicationContext = null; + this.messageSourceAccessor = null; + } + else if (this.applicationContext == null) { + // Initialize with passed-in context. + if (!requiredContextClass().isInstance(context)) { + throw new ApplicationContextException( + "Invalid application context: needs to be of type [" + requiredContextClass().getName() + "]"); + } + this.applicationContext = context; + this.messageSourceAccessor = new MessageSourceAccessor(context); + initApplicationContext(context); + } + else { + // Ignore reinitialization if same context passed in. + if (this.applicationContext != context) { + throw new ApplicationContextException( + "Cannot reinitialize with different application context: current one is [" + + this.applicationContext + "], passed-in one is [" + context + "]"); + } + } + } + + /** + * Determine whether this application object needs to run in an ApplicationContext. + *

    Default is "false". Can be overridden to enforce running in a context + * (i.e. to throw IllegalStateException on accessors if outside a context). + * @see #getApplicationContext + * @see #getMessageSourceAccessor + */ + protected boolean isContextRequired() { + return false; + } + + /** + * Determine the context class that any context passed to + * setApplicationContext must be an instance of. + * Can be overridden in subclasses. + * @see #setApplicationContext + */ + protected Class requiredContextClass() { + return ApplicationContext.class; + } + + /** + * Subclasses can override this for custom initialization behavior. + * Gets called by setApplicationContext after setting the context instance. + *

    Note: Does not get called on reinitialization of the context + * but rather just on first initialization of this object's context reference. + *

    The default implementation calls the overloaded {@link #initApplicationContext()} + * method without ApplicationContext reference. + * @param context the containing ApplicationContext + * @throws ApplicationContextException in case of initialization errors + * @throws BeansException if thrown by ApplicationContext methods + * @see #setApplicationContext + */ + protected void initApplicationContext(ApplicationContext context) throws BeansException { + initApplicationContext(); + } + + /** + * Subclasses can override this for custom initialization behavior. + *

    The default implementation is empty. Called by + * {@link #initApplicationContext(org.springframework.context.ApplicationContext)}. + * @throws ApplicationContextException in case of initialization errors + * @throws BeansException if thrown by ApplicationContext methods + * @see #setApplicationContext + */ + protected void initApplicationContext() throws BeansException { + } + + + /** + * Return the ApplicationContext that this object is associated with. + * @throws IllegalStateException if not running in an ApplicationContext + */ + public final ApplicationContext getApplicationContext() throws IllegalStateException { + if (this.applicationContext == null && isContextRequired()) { + throw new IllegalStateException( + "ApplicationObjectSupport instance [" + this + "] does not run in an ApplicationContext"); + } + return this.applicationContext; + } + + /** + * Return a MessageSourceAccessor for the application context + * used by this object, for easy message access. + * @throws IllegalStateException if not running in an ApplicationContext + */ + protected final MessageSourceAccessor getMessageSourceAccessor() throws IllegalStateException { + if (this.messageSourceAccessor == null && isContextRequired()) { + throw new IllegalStateException( + "ApplicationObjectSupport instance [" + this + "] does not run in an ApplicationContext"); + } + return this.messageSourceAccessor; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/ClassPathXmlApplicationContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/ClassPathXmlApplicationContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/ClassPathXmlApplicationContext.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,205 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.util.Assert; + +/** + * Standalone XML application context, taking the context definition files + * from the class path, interpreting plain paths as class path resource names + * that include the package path (e.g. "mypackage/myresource.txt"). Useful for + * test harnesses as well as for application contexts embedded within JARs. + * + *

    The config location defaults can be overridden via {@link #getConfigLocations}, + * Config locations can either denote concrete files like "/myfiles/context.xml" + * or Ant-style patterns like "/myfiles/*-context.xml" (see the + * {@link org.springframework.util.AntPathMatcher} javadoc for pattern details). + * + *

    Note: In case of multiple config locations, later bean definitions will + * override ones defined in earlier loaded files. This can be leveraged to + * deliberately override certain bean definitions via an extra XML file. + * + *

    This is a simple, one-stop shop convenience ApplicationContext. + * Consider using the {@link GenericApplicationContext} class in combination + * with an {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader} + * for more flexible context setup. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see #getResource + * @see #getResourceByPath + * @see GenericApplicationContext + */ +public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext { + + private Resource[] configResources; + + + /** + * Create a new ClassPathXmlApplicationContext for bean-style configuration. + * @see #setConfigLocation + * @see #setConfigLocations + * @see #afterPropertiesSet() + */ + public ClassPathXmlApplicationContext() { + } + + /** + * Create a new ClassPathXmlApplicationContext for bean-style configuration. + * @param parent the parent context + * @see #setConfigLocation + * @see #setConfigLocations + * @see #afterPropertiesSet() + */ + public ClassPathXmlApplicationContext(ApplicationContext parent) { + super(parent); + } + + /** + * Create a new ClassPathXmlApplicationContext, loading the definitions + * from the given XML file and automatically refreshing the context. + * @param configLocation resource location + * @throws BeansException if context creation failed + */ + public ClassPathXmlApplicationContext(String configLocation) throws BeansException { + this(new String[] {configLocation}, true, null); + } + + /** + * Create a new ClassPathXmlApplicationContext, loading the definitions + * from the given XML files and automatically refreshing the context. + * @param configLocations array of resource locations + * @throws BeansException if context creation failed + */ + public ClassPathXmlApplicationContext(String[] configLocations) throws BeansException { + this(configLocations, true, null); + } + + /** + * Create a new ClassPathXmlApplicationContext with the given parent, + * loading the definitions from the given XML files and automatically + * refreshing the context. + * @param configLocations array of resource locations + * @param parent the parent context + * @throws BeansException if context creation failed + */ + public ClassPathXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException { + this(configLocations, true, parent); + } + + /** + * Create a new ClassPathXmlApplicationContext, loading the definitions + * from the given XML files. + * @param configLocations array of resource locations + * @param refresh whether to automatically refresh the context, + * loading all bean definitions and creating all singletons. + * Alternatively, call refresh manually after further configuring the context. + * @throws BeansException if context creation failed + * @see #refresh() + */ + public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException { + this(configLocations, refresh, null); + } + + /** + * Create a new ClassPathXmlApplicationContext with the given parent, + * loading the definitions from the given XML files. + * @param configLocations array of resource locations + * @param refresh whether to automatically refresh the context, + * loading all bean definitions and creating all singletons. + * Alternatively, call refresh manually after further configuring the context. + * @param parent the parent context + * @throws BeansException if context creation failed + * @see #refresh() + */ + public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) + throws BeansException { + + super(parent); + setConfigLocations(configLocations); + if (refresh) { + refresh(); + } + } + + + /** + * Create a new ClassPathXmlApplicationContext, loading the definitions + * from the given XML file and automatically refreshing the context. + *

    This is a convenience method to load class path resources relative to a + * given Class. For full flexibility, consider using a GenericApplicationContext + * with an XmlBeanDefinitionReader and a ClassPathResource argument. + * @param path relative (or absolute) path within the class path + * @param clazz the class to load resources with (basis for the given paths) + * @throws BeansException if context creation failed + * @see org.springframework.core.io.ClassPathResource#ClassPathResource(String, Class) + * @see org.springframework.context.support.GenericApplicationContext + * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader + */ + public ClassPathXmlApplicationContext(String path, Class clazz) throws BeansException { + this(new String[] {path}, clazz); + } + + /** + * Create a new ClassPathXmlApplicationContext, loading the definitions + * from the given XML files and automatically refreshing the context. + * @param paths array of relative (or absolute) paths within the class path + * @param clazz the class to load resources with (basis for the given paths) + * @throws BeansException if context creation failed + * @see org.springframework.core.io.ClassPathResource#ClassPathResource(String, Class) + * @see org.springframework.context.support.GenericApplicationContext + * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader + */ + public ClassPathXmlApplicationContext(String[] paths, Class clazz) throws BeansException { + this(paths, clazz, null); + } + + /** + * Create a new ClassPathXmlApplicationContext with the given parent, + * loading the definitions from the given XML files and automatically + * refreshing the context. + * @param paths array of relative (or absolute) paths within the class path + * @param clazz the class to load resources with (basis for the given paths) + * @param parent the parent context + * @throws BeansException if context creation failed + * @see org.springframework.core.io.ClassPathResource#ClassPathResource(String, Class) + * @see org.springframework.context.support.GenericApplicationContext + * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader + */ + public ClassPathXmlApplicationContext(String[] paths, Class clazz, ApplicationContext parent) + throws BeansException { + + super(parent); + Assert.notNull(paths, "Path array must not be null"); + Assert.notNull(clazz, "Class argument must not be null"); + this.configResources = new Resource[paths.length]; + for (int i = 0; i < paths.length; i++) { + this.configResources[i] = new ClassPathResource(paths[i], clazz); + } + refresh(); + } + + + protected Resource[] getConfigResources() { + return this.configResources; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/ContextTypeMatchClassLoader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/ContextTypeMatchClassLoader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/ContextTypeMatchClassLoader.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,110 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import org.springframework.core.DecoratingClassLoader; +import org.springframework.core.OverridingClassLoader; +import org.springframework.core.SmartClassLoader; +import org.springframework.util.ReflectionUtils; + +/** + * Special variant of an overriding ClassLoader, used for temporary type + * matching in {@link AbstractApplicationContext}. Redefines classes from + * a cached byte array for every loadClass call in order to + * pick up recently loaded types in the parent ClassLoader. + * + * @author Juergen Hoeller + * @since 2.5 + * @see AbstractApplicationContext + * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#setTempClassLoader + */ +class ContextTypeMatchClassLoader extends DecoratingClassLoader implements SmartClassLoader { + + private static Method findLoadedClassMethod; + + static { + try { + findLoadedClassMethod = ClassLoader.class.getDeclaredMethod("findLoadedClass", new Class[] {String.class}); + } + catch (NoSuchMethodException ex) { + throw new IllegalStateException("Invalid [java.lang.ClassLoader] class: no 'findLoadedClass' method defined!"); + } + } + + + /** Cache for byte array per class name */ + private final Map bytesCache = new HashMap(); + + + public ContextTypeMatchClassLoader(ClassLoader parent) { + super(parent); + } + + public Class loadClass(String name) throws ClassNotFoundException { + return new ContextOverridingClassLoader(getParent()).loadClass(name); + } + + public boolean isClassReloadable(Class clazz) { + return (clazz.getClassLoader() instanceof ContextOverridingClassLoader); + } + + + /** + * ClassLoader to be created for each loaded class. + * Caches class file content but redefines class for each call. + */ + private class ContextOverridingClassLoader extends OverridingClassLoader { + + public ContextOverridingClassLoader(ClassLoader parent) { + super(parent); + } + + protected boolean isEligibleForOverriding(String className) { + if (isExcluded(className) || ContextTypeMatchClassLoader.this.isExcluded(className)) { + return false; + } + ReflectionUtils.makeAccessible(findLoadedClassMethod); + ClassLoader parent = getParent(); + while (parent != null) { + if (ReflectionUtils.invokeMethod(findLoadedClassMethod, parent, new Object[] {className}) != null) { + return false; + } + parent = parent.getParent(); + } + return true; + } + + protected Class loadClassForOverriding(String name) throws ClassNotFoundException { + byte[] bytes = (byte[]) bytesCache.get(name); + if (bytes == null) { + bytes = loadBytesForClass(name); + if (bytes != null) { + bytesCache.put(name, bytes); + } + else { + return null; + } + } + return defineClass(name, bytes, 0, bytes.length); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/DefaultMessageSourceResolvable.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/DefaultMessageSourceResolvable.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/DefaultMessageSourceResolvable.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,162 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.io.Serializable; + +import org.springframework.context.MessageSourceResolvable; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +/** + * Default implementation of the {@link MessageSourceResolvable} interface. + * Offers an easy way to store all the necessary values needed to resolve + * a message via a {@link org.springframework.context.MessageSource}. + * + * @author Juergen Hoeller + * @since 13.02.2004 + * @see org.springframework.context.MessageSource#getMessage(MessageSourceResolvable, java.util.Locale) + */ +public class DefaultMessageSourceResolvable implements MessageSourceResolvable, Serializable { + + private final String[] codes; + + private final Object[] arguments; + + private final String defaultMessage; + + + /** + * Create a new DefaultMessageSourceResolvable. + * @param code the code to be used to resolve this message + */ + public DefaultMessageSourceResolvable(String code) { + this(new String[] {code}, null, null); + } + + /** + * Create a new DefaultMessageSourceResolvable. + * @param codes the codes to be used to resolve this message + */ + public DefaultMessageSourceResolvable(String[] codes) { + this(codes, null, null); + } + + /** + * Create a new DefaultMessageSourceResolvable. + * @param codes the codes to be used to resolve this message + * @param defaultMessage the default message to be used to resolve this message + */ + public DefaultMessageSourceResolvable(String[] codes, String defaultMessage) { + this(codes, null, defaultMessage); + } + + /** + * Create a new DefaultMessageSourceResolvable. + * @param codes the codes to be used to resolve this message + * @param arguments the array of arguments to be used to resolve this message + */ + public DefaultMessageSourceResolvable(String[] codes, Object[] arguments) { + this(codes, arguments, null); + } + + /** + * Create a new DefaultMessageSourceResolvable. + * @param codes the codes to be used to resolve this message + * @param arguments the array of arguments to be used to resolve this message + * @param defaultMessage the default message to be used to resolve this message + */ + public DefaultMessageSourceResolvable(String[] codes, Object[] arguments, String defaultMessage) { + this.codes = codes; + this.arguments = arguments; + this.defaultMessage = defaultMessage; + } + + /** + * Copy constructor: Create a new instance from another resolvable. + * @param resolvable the resolvable to copy from + */ + public DefaultMessageSourceResolvable(MessageSourceResolvable resolvable) { + this(resolvable.getCodes(), resolvable.getArguments(), resolvable.getDefaultMessage()); + } + + + public String[] getCodes() { + return this.codes; + } + + /** + * Return the default code of this resolvable, that is, + * the last one in the codes array. + */ + public String getCode() { + return (this.codes != null && this.codes.length > 0) ? this.codes[this.codes.length - 1] : null; + } + + public Object[] getArguments() { + return this.arguments; + } + + public String getDefaultMessage() { + return this.defaultMessage; + } + + + /** + * Build a default String representation for this MessageSourceResolvable: + * including codes, arguments, and default message. + */ + protected final String resolvableToString() { + StringBuffer buf = new StringBuffer(); + buf.append("codes [").append(StringUtils.arrayToDelimitedString(this.codes, ",")); + buf.append("]; arguments [" + StringUtils.arrayToDelimitedString(this.arguments, ",")); + buf.append("]; default message [").append(this.defaultMessage).append(']'); + return buf.toString(); + } + + /** + * Default implementation exposes the attributes of this MessageSourceResolvable. + * To be overridden in more specific subclasses, potentially including the + * resolvable content through resolvableToString(). + * @see #resolvableToString() + */ + public String toString() { + return getClass().getName() + ": " + resolvableToString(); + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof MessageSourceResolvable)) { + return false; + } + MessageSourceResolvable otherResolvable = (MessageSourceResolvable) other; + return ObjectUtils.nullSafeEquals(getCodes(), otherResolvable.getCodes()) && + ObjectUtils.nullSafeEquals(getArguments(), otherResolvable.getArguments()) && + ObjectUtils.nullSafeEquals(getDefaultMessage(), otherResolvable.getDefaultMessage()); + } + + public int hashCode() { + int hashCode = ObjectUtils.nullSafeHashCode(getCodes()); + hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(getArguments()); + hashCode = 29 * hashCode + ObjectUtils.nullSafeHashCode(getDefaultMessage()); + return hashCode; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/DelegatingMessageSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/DelegatingMessageSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/DelegatingMessageSource.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.util.Locale; + +import org.springframework.context.HierarchicalMessageSource; +import org.springframework.context.MessageSource; +import org.springframework.context.MessageSourceResolvable; +import org.springframework.context.NoSuchMessageException; + +/** + * Empty {@link MessageSource} that delegates all calls to the parent MessageSource. + * If no parent is available, it simply won't resolve any message. + * + *

    Used as placeholder by AbstractApplicationContext, if the context doesn't + * define its own MessageSource. Not intended for direct use in applications. + * + * @author Juergen Hoeller + * @since 1.1.5 + * @see AbstractApplicationContext + */ +public class DelegatingMessageSource extends MessageSourceSupport implements HierarchicalMessageSource { + + private MessageSource parentMessageSource; + + + public void setParentMessageSource(MessageSource parent) { + this.parentMessageSource = parent; + } + + public MessageSource getParentMessageSource() { + return this.parentMessageSource; + } + + + public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) { + if (this.parentMessageSource != null) { + return this.parentMessageSource.getMessage(code, args, defaultMessage, locale); + } + else { + return renderDefaultMessage(defaultMessage, args, locale); + } + } + + public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException { + if (this.parentMessageSource != null) { + return this.parentMessageSource.getMessage(code, args, locale); + } + else { + throw new NoSuchMessageException(code, locale); + } + } + + public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException { + if (this.parentMessageSource != null) { + return this.parentMessageSource.getMessage(resolvable, locale); + } + else { + if (resolvable.getDefaultMessage() != null) { + return renderDefaultMessage(resolvable.getDefaultMessage(), resolvable.getArguments(), locale); + } + String[] codes = resolvable.getCodes(); + String code = (codes != null && codes.length > 0 ? codes[0] : null); + throw new NoSuchMessageException(code, locale); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/FileSystemXmlApplicationContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/FileSystemXmlApplicationContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/FileSystemXmlApplicationContext.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,161 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; + +/** + * Standalone XML application context, taking the context definition files + * from the file system or from URLs, interpreting plain paths as relative + * file system locations (e.g. "mydir/myfile.txt"). Useful for test harnesses + * as well as for standalone environments. + * + *

    NOTE: Plain paths will always be interpreted as relative + * to the current VM working directory, even if they start with a slash. + * (This is consistent with the semantics in a Servlet container.) + * Use an explicit "file:" prefix to enforce an absolute file path. + * + *

    The config location defaults can be overridden via {@link #getConfigLocations}, + * Config locations can either denote concrete files like "/myfiles/context.xml" + * or Ant-style patterns like "/myfiles/*-context.xml" (see the + * {@link org.springframework.util.AntPathMatcher} javadoc for pattern details). + * + *

    Note: In case of multiple config locations, later bean definitions will + * override ones defined in earlier loaded files. This can be leveraged to + * deliberately override certain bean definitions via an extra XML file. + * + *

    This is a simple, one-stop shop convenience ApplicationContext. + * Consider using the {@link GenericApplicationContext} class in combination + * with an {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader} + * for more flexible context setup. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see #getResource + * @see #getResourceByPath + * @see GenericApplicationContext + */ +public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext { + + /** + * Create a new FileSystemXmlApplicationContext for bean-style configuration. + * @see #setConfigLocation + * @see #setConfigLocations + * @see #afterPropertiesSet() + */ + public FileSystemXmlApplicationContext() { + } + + /** + * Create a new FileSystemXmlApplicationContext for bean-style configuration. + * @param parent the parent context + * @see #setConfigLocation + * @see #setConfigLocations + * @see #afterPropertiesSet() + */ + public FileSystemXmlApplicationContext(ApplicationContext parent) { + super(parent); + } + + /** + * Create a new FileSystemXmlApplicationContext, loading the definitions + * from the given XML file and automatically refreshing the context. + * @param configLocation file path + * @throws BeansException if context creation failed + */ + public FileSystemXmlApplicationContext(String configLocation) throws BeansException { + this(new String[] {configLocation}, true, null); + } + + /** + * Create a new FileSystemXmlApplicationContext, loading the definitions + * from the given XML files and automatically refreshing the context. + * @param configLocations array of file paths + * @throws BeansException if context creation failed + */ + public FileSystemXmlApplicationContext(String[] configLocations) throws BeansException { + this(configLocations, true, null); + } + + /** + * Create a new FileSystemXmlApplicationContext with the given parent, + * loading the definitions from the given XML files and automatically + * refreshing the context. + * @param configLocations array of file paths + * @param parent the parent context + * @throws BeansException if context creation failed + */ + public FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException { + this(configLocations, true, parent); + } + + /** + * Create a new FileSystemXmlApplicationContext, loading the definitions + * from the given XML files. + * @param configLocations array of file paths + * @param refresh whether to automatically refresh the context, + * loading all bean definitions and creating all singletons. + * Alternatively, call refresh manually after further configuring the context. + * @throws BeansException if context creation failed + * @see #refresh() + */ + public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException { + this(configLocations, refresh, null); + } + + /** + * Create a new FileSystemXmlApplicationContext with the given parent, + * loading the definitions from the given XML files. + * @param configLocations array of file paths + * @param refresh whether to automatically refresh the context, + * loading all bean definitions and creating all singletons. + * Alternatively, call refresh manually after further configuring the context. + * @param parent the parent context + * @throws BeansException if context creation failed + * @see #refresh() + */ + public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) + throws BeansException { + + super(parent); + setConfigLocations(configLocations); + if (refresh) { + refresh(); + } + } + + + /** + * Resolve resource paths as file system paths. + *

    Note: Even if a given path starts with a slash, it will get + * interpreted as relative to the current VM working directory. + * This is consistent with the semantics in a Servlet container. + * @param path path to the resource + * @return Resource handle + * @see org.springframework.web.context.support.XmlWebApplicationContext#getResourceByPath + */ + protected Resource getResourceByPath(String path) { + if (path != null && path.startsWith("/")) { + path = path.substring(1); + } + return new FileSystemResource(path); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/GenericApplicationContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/GenericApplicationContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/GenericApplicationContext.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,275 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.io.IOException; + +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.util.Assert; + +/** + * Generic ApplicationContext implementation that holds a single internal + * {@link org.springframework.beans.factory.support.DefaultListableBeanFactory} + * instance and does not assume a specific bean definition format. Implements + * the {@link org.springframework.beans.factory.support.BeanDefinitionRegistry} + * interface in order to allow for applying any bean definition readers to it. + * + *

    Typical usage is to register a variety of bean definitions via the + * {@link org.springframework.beans.factory.support.BeanDefinitionRegistry} + * interface and then call {@link #refresh()} to initialize those beans + * with application context semantics (handling + * {@link org.springframework.context.ApplicationContextAware}, auto-detecting + * {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactoryPostProcessors}, + * etc). + * + *

    In contrast to other ApplicationContext implementations that create a new + * internal BeanFactory instance for each refresh, the internal BeanFactory of + * this context is available right from the start, to be able to register bean + * definitions on it. {@link #refresh()} may only be called once. + * + *

    Usage example: + * + *

    + * GenericApplicationContext ctx = new GenericApplicationContext();
    + * XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    + * xmlReader.loadBeanDefinitions(new ClassPathResource("applicationContext.xml"));
    + * PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(ctx);
    + * propReader.loadBeanDefinitions(new ClassPathResource("otherBeans.properties"));
    + * ctx.refresh();
    + *
    + * MyBean myBean = (MyBean) ctx.getBean("myBean");
    + * ...
    + * + * For the typical case of XML bean definitions, simply use + * {@link ClassPathXmlApplicationContext} or {@link FileSystemXmlApplicationContext}, + * which are easier to set up - but less flexible, since you can just use standard + * resource locations for XML bean definitions, rather than mixing arbitrary bean + * definition formats. The equivalent in a web environment is + * {@link org.springframework.web.context.support.XmlWebApplicationContext}. + * + *

    For custom application context implementations that are supposed to read + * special bean definition formats in a refreshable manner, consider deriving + * from the {@link AbstractRefreshableApplicationContext} base class. + * + * @author Juergen Hoeller + * @since 1.1.2 + * @see #registerBeanDefinition + * @see #refresh() + * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader + * @see org.springframework.beans.factory.support.PropertiesBeanDefinitionReader + */ +public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry { + + private final DefaultListableBeanFactory beanFactory; + + private ResourceLoader resourceLoader; + + private boolean refreshed = false; + + + /** + * Create a new GenericApplicationContext. + * @see #registerBeanDefinition + * @see #refresh + */ + public GenericApplicationContext() { + this.beanFactory = new DefaultListableBeanFactory(); + } + + /** + * Create a new GenericApplicationContext with the given DefaultListableBeanFactory. + * @param beanFactory the DefaultListableBeanFactory instance to use for this context + * @see #registerBeanDefinition + * @see #refresh + */ + public GenericApplicationContext(DefaultListableBeanFactory beanFactory) { + Assert.notNull(beanFactory, "BeanFactory must not be null"); + this.beanFactory = beanFactory; + } + + /** + * Create a new GenericApplicationContext with the given parent. + * @param parent the parent application context + * @see #registerBeanDefinition + * @see #refresh + */ + public GenericApplicationContext(ApplicationContext parent) { + this(); + setParent(parent); + } + + /** + * Create a new GenericApplicationContext with the given DefaultListableBeanFactory. + * @param beanFactory the DefaultListableBeanFactory instance to use for this context + * @param parent the parent application context + * @see #registerBeanDefinition + * @see #refresh + */ + public GenericApplicationContext(DefaultListableBeanFactory beanFactory, ApplicationContext parent) { + this(beanFactory); + setParent(parent); + } + + + /** + * Set the parent of this application context, also setting + * the parent of the internal BeanFactory accordingly. + * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#setParentBeanFactory + */ + public void setParent(ApplicationContext parent) { + super.setParent(parent); + this.beanFactory.setParentBeanFactory(getInternalParentBeanFactory()); + } + + /** + * Set a ResourceLoader to use for this context. If set, the context will + * delegate all getResource calls to the given ResourceLoader. + * If not set, default resource loading will apply. + *

    The main reason to specify a custom ResourceLoader is to resolve + * resource paths (withour URL prefix) in a specific fashion. + * The default behavior is to resolve such paths as class path locations. + * To resolve resource paths as file system locations, specify a + * FileSystemResourceLoader here. + *

    You can also pass in a full ResourcePatternResolver, which will + * be autodetected by the context and used for getResources + * calls as well. Else, default resource pattern matching will apply. + * @see #getResource + * @see org.springframework.core.io.DefaultResourceLoader + * @see org.springframework.core.io.FileSystemResourceLoader + * @see org.springframework.core.io.support.ResourcePatternResolver + * @see #getResources + */ + public void setResourceLoader(ResourceLoader resourceLoader) { + this.resourceLoader = resourceLoader; + } + + + /** + * This implementation delegates to this context's ResourceLoader if set, + * falling back to the default superclass behavior else. + * @see #setResourceLoader + */ + public Resource getResource(String location) { + if (this.resourceLoader != null) { + return this.resourceLoader.getResource(location); + } + return super.getResource(location); + } + + /** + * This implementation delegates to this context's ResourceLoader if it + * implements the ResourcePatternResolver interface, falling back to the + * default superclass behavior else. + * @see #setResourceLoader + */ + public Resource[] getResources(String locationPattern) throws IOException { + if (this.resourceLoader instanceof ResourcePatternResolver) { + return ((ResourcePatternResolver) this.resourceLoader).getResources(locationPattern); + } + return super.getResources(locationPattern); + } + + + //--------------------------------------------------------------------- + // Implementations of AbstractApplicationContext's template methods + //--------------------------------------------------------------------- + + /** + * Do nothing: We hold a single internal BeanFactory and rely on callers + * to register beans through our public methods (or the BeanFactory's). + * @see #registerBeanDefinition + */ + protected final void refreshBeanFactory() throws IllegalStateException { + if (this.refreshed) { + throw new IllegalStateException( + "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once"); + } + this.refreshed = true; + } + + /** + * Do nothing: We hold a single internal BeanFactory that will never + * get released. + */ + protected final void closeBeanFactory() { + } + + /** + * Return the single internal BeanFactory held by this context + * (as ConfigurableListableBeanFactory). + */ + public final ConfigurableListableBeanFactory getBeanFactory() { + return this.beanFactory; + } + + /** + * Return the underlying bean factory of this context, + * available for registering bean definitions. + *

    NOTE: You need to call {@link #refresh()} to initialize the + * bean factory and its contained beans with application context semantics + * (autodetecting BeanFactoryPostProcessors, etc). + * @return the internal bean factory (as DefaultListableBeanFactory) + */ + public final DefaultListableBeanFactory getDefaultListableBeanFactory() { + return this.beanFactory; + } + + + //--------------------------------------------------------------------- + // Implementation of BeanDefinitionRegistry + //--------------------------------------------------------------------- + + public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) + throws BeanDefinitionStoreException { + + this.beanFactory.registerBeanDefinition(beanName, beanDefinition); + } + + public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { + this.beanFactory.removeBeanDefinition(beanName); + } + + public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { + return this.beanFactory.getBeanDefinition(beanName); + } + + public boolean isBeanNameInUse(String beanName) { + return this.beanFactory.isBeanNameInUse(beanName); + } + + public void registerAlias(String beanName, String alias) { + this.beanFactory.registerAlias(beanName, alias); + } + + public void removeAlias(String alias) { + this.beanFactory.removeAlias(alias); + } + + public boolean isAlias(String beanName) { + return this.beanFactory.isAlias(beanName); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/MessageSourceAccessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/MessageSourceAccessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/MessageSourceAccessor.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,187 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.util.Locale; + +import org.springframework.context.MessageSource; +import org.springframework.context.MessageSourceResolvable; +import org.springframework.context.NoSuchMessageException; +import org.springframework.context.i18n.LocaleContextHolder; + +/** + * Helper class for easy access to messages from a MessageSource, + * providing various overloaded getMessage methods. + * + *

    Available from ApplicationObjectSupport, but also reusable + * as a standalone helper to delegate to in application objects. + * + * @author Juergen Hoeller + * @since 23.10.2003 + * @see ApplicationObjectSupport#getMessageSourceAccessor + */ +public class MessageSourceAccessor { + + private final MessageSource messageSource; + + private final Locale defaultLocale; + + /** + * Create a new MessageSourceAccessor, using LocaleContextHolder's locale + * as default locale. + * @param messageSource the MessageSource to wrap + * @see org.springframework.context.i18n.LocaleContextHolder#getLocale() + */ + public MessageSourceAccessor(MessageSource messageSource) { + this.messageSource = messageSource; + this.defaultLocale = null; + } + + /** + * Create a new MessageSourceAccessor, using the given default locale. + * @param messageSource the MessageSource to wrap + * @param defaultLocale the default locale to use for message access + */ + public MessageSourceAccessor(MessageSource messageSource, Locale defaultLocale) { + this.messageSource = messageSource; + this.defaultLocale = defaultLocale; + } + + /** + * Return the default locale to use if no explicit locale has been given. + *

    The default implementation returns the default locale passed into the + * corresponding constructor, or LocaleContextHolder's locale as fallback. + * Can be overridden in subclasses. + * @see #MessageSourceAccessor(org.springframework.context.MessageSource, java.util.Locale) + * @see org.springframework.context.i18n.LocaleContextHolder#getLocale() + */ + protected Locale getDefaultLocale() { + return (this.defaultLocale != null ? this.defaultLocale : LocaleContextHolder.getLocale()); + } + + /** + * Retrieve the message for the given code and the default Locale. + * @param code code of the message + * @param defaultMessage String to return if the lookup fails + * @return the message + */ + public String getMessage(String code, String defaultMessage) { + return this.messageSource.getMessage(code, null, defaultMessage, getDefaultLocale()); + } + + /** + * Retrieve the message for the given code and the given Locale. + * @param code code of the message + * @param defaultMessage String to return if the lookup fails + * @param locale Locale in which to do lookup + * @return the message + */ + public String getMessage(String code, String defaultMessage, Locale locale) { + return this.messageSource.getMessage(code, null, defaultMessage, locale); + } + + /** + * Retrieve the message for the given code and the default Locale. + * @param code code of the message + * @param args arguments for the message, or null if none + * @param defaultMessage String to return if the lookup fails + * @return the message + */ + public String getMessage(String code, Object[] args, String defaultMessage) { + return this.messageSource.getMessage(code, args, defaultMessage, getDefaultLocale()); + } + + /** + * Retrieve the message for the given code and the given Locale. + * @param code code of the message + * @param args arguments for the message, or null if none + * @param defaultMessage String to return if the lookup fails + * @param locale Locale in which to do lookup + * @return the message + */ + public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) { + return this.messageSource.getMessage(code, args, defaultMessage, locale); + } + + /** + * Retrieve the message for the given code and the default Locale. + * @param code code of the message + * @return the message + * @throws org.springframework.context.NoSuchMessageException if not found + */ + public String getMessage(String code) throws NoSuchMessageException { + return this.messageSource.getMessage(code, null, getDefaultLocale()); + } + + /** + * Retrieve the message for the given code and the given Locale. + * @param code code of the message + * @param locale Locale in which to do lookup + * @return the message + * @throws org.springframework.context.NoSuchMessageException if not found + */ + public String getMessage(String code, Locale locale) throws NoSuchMessageException { + return this.messageSource.getMessage(code, null, locale); + } + + /** + * Retrieve the message for the given code and the default Locale. + * @param code code of the message + * @param args arguments for the message, or null if none + * @return the message + * @throws org.springframework.context.NoSuchMessageException if not found + */ + public String getMessage(String code, Object[] args) throws NoSuchMessageException { + return this.messageSource.getMessage(code, args, getDefaultLocale()); + } + + /** + * Retrieve the message for the given code and the given Locale. + * @param code code of the message + * @param args arguments for the message, or null if none + * @param locale Locale in which to do lookup + * @return the message + * @throws org.springframework.context.NoSuchMessageException if not found + */ + public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException { + return this.messageSource.getMessage(code, args, locale); + } + + /** + * Retrieve the given MessageSourceResolvable (e.g. an ObjectError instance) + * in the default Locale. + * @param resolvable the MessageSourceResolvable + * @return the message + * @throws org.springframework.context.NoSuchMessageException if not found + */ + public String getMessage(MessageSourceResolvable resolvable) throws NoSuchMessageException { + return this.messageSource.getMessage(resolvable, getDefaultLocale()); + } + + /** + * Retrieve the given MessageSourceResolvable (e.g. an ObjectError instance) + * in the given Locale. + * @param resolvable the MessageSourceResolvable + * @param locale Locale in which to do lookup + * @return the message + * @throws org.springframework.context.NoSuchMessageException if not found + */ + public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException { + return this.messageSource.getMessage(resolvable, locale); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/MessageSourceResourceBundle.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/MessageSourceResourceBundle.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/MessageSourceResourceBundle.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,97 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.util.Enumeration; +import java.util.Locale; +import java.util.ResourceBundle; + +import org.springframework.context.MessageSource; +import org.springframework.context.NoSuchMessageException; +import org.springframework.util.Assert; + +/** + * Helper class that allows for accessing a Spring + * {@link org.springframework.context.MessageSource} as a {@link java.util.ResourceBundle}. + * Used for example to expose a Spring MessageSource to JSTL web views. + * + * @author Juergen Hoeller + * @since 27.02.2003 + * @see org.springframework.context.MessageSource + * @see java.util.ResourceBundle + * @see org.springframework.web.servlet.support.JstlUtils#exposeLocalizationContext + */ +public class MessageSourceResourceBundle extends ResourceBundle { + + private final MessageSource messageSource; + + private final Locale locale; + + + /** + * Create a new MessageSourceResourceBundle for the given MessageSource and Locale. + * @param source the MessageSource to retrieve messages from + * @param locale the Locale to retrieve messages for + */ + public MessageSourceResourceBundle(MessageSource source, Locale locale) { + Assert.notNull(source, "MessageSource must not be null"); + this.messageSource = source; + this.locale = locale; + } + + /** + * Create a new MessageSourceResourceBundle for the given MessageSource and Locale. + * @param source the MessageSource to retrieve messages from + * @param locale the Locale to retrieve messages for + * @param parent the parent ResourceBundle to delegate to if no local message found + */ + public MessageSourceResourceBundle(MessageSource source, Locale locale, ResourceBundle parent) { + this(source, locale); + setParent(parent); + } + + + /** + * This implementation resolves the code in the MessageSource. + * Returns null if the message could not be resolved. + */ + protected Object handleGetObject(String code) { + try { + return this.messageSource.getMessage(code, null, this.locale); + } + catch (NoSuchMessageException ex) { + return null; + } + } + + /** + * This implementation returns null, as a MessageSource does + * not allow for enumerating the defined message codes. + */ + public Enumeration getKeys() { + return null; + } + + /** + * This implementation exposes the specified Locale for introspection + * through the standard ResourceBundle.getLocale() method. + */ + public Locale getLocale() { + return this.locale; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/MessageSourceSupport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/MessageSourceSupport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/MessageSourceSupport.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,153 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Base class for message source implementations, providing support infrastructure + * such as {@link java.text.MessageFormat} handling but not implementing concrete + * methods defined in the {@link org.springframework.context.MessageSource}. + * + *

    {@link AbstractMessageSource} derives from this class, providing concrete + * getMessage implementations that delegate to a central template + * method for message code resolution. + * + * @author Juergen Hoeller + * @since 2.5.5 + */ +public abstract class MessageSourceSupport { + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); + + private boolean alwaysUseMessageFormat = false; + + /** + * Cache to hold already generated MessageFormats per message. + * Used for passed-in default messages. MessageFormats for resolved + * codes are cached on a specific basis in subclasses. + */ + private final Map cachedMessageFormats = new HashMap(); + + + /** + * Set whether to always apply the MessageFormat rules, parsing even + * messages without arguments. + *

    Default is "false": Messages without arguments are by default + * returned as-is, without parsing them through MessageFormat. + * Set this to "true" to enforce MessageFormat for all messages, + * expecting all message texts to be written with MessageFormat escaping. + *

    For example, MessageFormat expects a single quote to be escaped + * as "''". If your message texts are all written with such escaping, + * even when not defining argument placeholders, you need to set this + * flag to "true". Else, only message texts with actual arguments + * are supposed to be written with MessageFormat escaping. + * @see java.text.MessageFormat + */ + public void setAlwaysUseMessageFormat(boolean alwaysUseMessageFormat) { + this.alwaysUseMessageFormat = alwaysUseMessageFormat; + } + + /** + * Return whether to always apply the MessageFormat rules, parsing even + * messages without arguments. + */ + protected boolean isAlwaysUseMessageFormat() { + return this.alwaysUseMessageFormat; + } + + + /** + * Format the given message String, using cached MessageFormats. + * By default invoked for passed-in default messages, to resolve + * any argument placeholders found in them. + * @param msg the message to format + * @param args array of arguments that will be filled in for params within + * the message, or null if none. + * @param locale the Locale used for formatting + * @return the formatted message (with resolved arguments) + */ + protected String formatMessage(String msg, Object[] args, Locale locale) { + if (msg == null || (!this.alwaysUseMessageFormat && (args == null || args.length == 0))) { + return msg; + } + MessageFormat messageFormat = null; + synchronized (this.cachedMessageFormats) { + messageFormat = (MessageFormat) this.cachedMessageFormats.get(msg); + if (messageFormat == null) { + messageFormat = createMessageFormat(msg, locale); + this.cachedMessageFormats.put(msg, messageFormat); + } + } + synchronized (messageFormat) { + return messageFormat.format(resolveArguments(args, locale)); + } + } + + /** + * Create a MessageFormat for the given message and Locale. + * @param msg the message to create a MessageFormat for + * @param locale the Locale to create a MessageFormat for + * @return the MessageFormat instance + */ + protected MessageFormat createMessageFormat(String msg, Locale locale) { + if (logger.isDebugEnabled()) { + logger.debug("Creating MessageFormat for pattern [" + msg + "] and locale '" + locale + "'"); + } + return new MessageFormat((msg != null ? msg : ""), locale); + } + + /** + * Template method for resolving argument objects. + *

    The default implementation simply returns the given argument + * array as-is. Can be overridden in subclasses in order to resolve + * special argument types. + * @param args the original argument array + * @param locale the Locale to resolve against + * @return the resolved argument array + */ + protected Object[] resolveArguments(Object[] args, Locale locale) { + return args; + } + + + /** + * Render the given default message String. The default message is + * passed in as specified by the caller and can be rendered into + * a fully formatted default message shown to the user. + *

    The default implementation passes the String to formatMessage, + * resolving any argument placeholders found in them. Subclasses may override + * this method to plug in custom processing of default messages. + * @param defaultMessage the passed-in default message String + * @param args array of arguments that will be filled in for params within + * the message, or null if none. + * @param locale the Locale used for formatting + * @return the rendered default message (with resolved arguments) + * @see #formatMessage(String, Object[], java.util.Locale) + */ + protected String renderDefaultMessage(String defaultMessage, Object[] args, Locale locale) { + return formatMessage(defaultMessage, args, locale); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/ReloadableResourceBundleMessageSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/ReloadableResourceBundleMessageSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/ReloadableResourceBundleMessageSource.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,663 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; + +import org.springframework.context.ResourceLoaderAware; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.util.Assert; +import org.springframework.util.DefaultPropertiesPersister; +import org.springframework.util.PropertiesPersister; +import org.springframework.util.StringUtils; + +/** + * {@link org.springframework.context.MessageSource} implementation that + * accesses resource bundles using specified basenames. This class uses + * {@link java.util.Properties} instances as its custom data structure for + * messages, loading them via a {@link org.springframework.util.PropertiesPersister} + * strategy: The default strategy is capable of loading properties files + * with a specific character encoding, if desired. + * + *

    In contrast to {@link ResourceBundleMessageSource}, this class supports + * reloading of properties files through the {@link #setCacheSeconds "cacheSeconds"} + * setting, and also through programmatically clearing the properties cache. + * Since application servers typically cache all files loaded from the classpath, + * it is necessary to store resources somewhere else (for example, in the + * "WEB-INF" directory of a web app). Otherwise changes of files in the + * classpath will not be reflected in the application. + * + *

    Note that the base names set as {@link #setBasenames "basenames"} property + * are treated in a slightly different fashion than the "basenames" property of + * {@link ResourceBundleMessageSource}. It follows the basic ResourceBundle rule of not + * specifying file extension or language codes, but can refer to any Spring resource + * location (instead of being restricted to classpath resources). With a "classpath:" + * prefix, resources can still be loaded from the classpath, but "cacheSeconds" values + * other than "-1" (caching forever) will not work in this case. + * + *

    This MessageSource implementation is usually slightly faster than + * {@link ResourceBundleMessageSource}, which builds on {@link java.util.ResourceBundle} + * - in the default mode, i.e. when caching forever. With "cacheSeconds" set to 1, + * message lookup takes about twice as long - with the benefit that changes in + * individual properties files are detected with a maximum delay of 1 second. + * Higher "cacheSeconds" values usually do not make a significant difference. + * + *

    This MessageSource can easily be used outside of an + * {@link org.springframework.context.ApplicationContext}: It will use a + * {@link org.springframework.core.io.DefaultResourceLoader} as default, + * simply getting overridden with the ApplicationContext's resource loader + * if running in a context. It does not have any other specific dependencies. + * + *

    Thanks to Thomas Achleitner for providing the initial implementation of + * this message source! + * + * @author Juergen Hoeller + * @see #setCacheSeconds + * @see #setBasenames + * @see #setDefaultEncoding + * @see #setFileEncodings + * @see #setPropertiesPersister + * @see #setResourceLoader + * @see org.springframework.util.DefaultPropertiesPersister + * @see org.springframework.core.io.DefaultResourceLoader + * @see ResourceBundleMessageSource + * @see java.util.ResourceBundle + */ +public class ReloadableResourceBundleMessageSource extends AbstractMessageSource + implements ResourceLoaderAware { + + private static final String PROPERTIES_SUFFIX = ".properties"; + + private static final String XML_SUFFIX = ".xml"; + + + private String[] basenames = new String[0]; + + private String defaultEncoding; + + private Properties fileEncodings; + + private boolean fallbackToSystemLocale = true; + + private long cacheMillis = -1; + + private PropertiesPersister propertiesPersister = new DefaultPropertiesPersister(); + + private ResourceLoader resourceLoader = new DefaultResourceLoader(); + + /** Cache to hold filename lists per Locale */ + private final Map cachedFilenames = new HashMap(); + + /** Cache to hold already loaded properties per filename */ + private final Map cachedProperties = new HashMap(); + + /** Cache to hold merged loaded properties per basename */ + private final Map cachedMergedProperties = new HashMap(); + + + /** + * Set a single basename, following the basic ResourceBundle convention of + * not specifying file extension or language codes, but in contrast to + * {@link ResourceBundleMessageSource} referring to a Spring resource location: + * e.g. "WEB-INF/messages" for "WEB-INF/messages.properties", + * "WEB-INF/messages_en.properties", etc. + *

    As of Spring 1.2.2, XML properties files are also supported: + * e.g. "WEB-INF/messages" will find and load "WEB-INF/messages.xml", + * "WEB-INF/messages_en.xml", etc as well. Note that this will only + * work on JDK 1.5+. + * @param basename the single basename + * @see #setBasenames + * @see org.springframework.core.io.ResourceEditor + * @see java.util.ResourceBundle + */ + public void setBasename(String basename) { + setBasenames(new String[] {basename}); + } + + /** + * Set an array of basenames, each following the basic ResourceBundle convention + * of not specifying file extension or language codes, but in contrast to + * {@link ResourceBundleMessageSource} referring to a Spring resource location: + * e.g. "WEB-INF/messages" for "WEB-INF/messages.properties", + * "WEB-INF/messages_en.properties", etc. + *

    As of Spring 1.2.2, XML properties files are also supported: + * e.g. "WEB-INF/messages" will find and load "WEB-INF/messages.xml", + * "WEB-INF/messages_en.xml", etc as well. Note that this will only + * work on JDK 1.5+. + *

    The associated resource bundles will be checked sequentially + * when resolving a message code. Note that message definitions in a + * previous resource bundle will override ones in a later bundle, + * due to the sequential lookup. + * @param basenames an array of basenames + * @see #setBasename + * @see java.util.ResourceBundle + */ + public void setBasenames(String[] basenames) { + if (basenames != null) { + this.basenames = new String[basenames.length]; + for (int i = 0; i < basenames.length; i++) { + String basename = basenames[i]; + Assert.hasText(basename, "Basename must not be empty"); + this.basenames[i] = basename.trim(); + } + } + else { + this.basenames = new String[0]; + } + } + + /** + * Set the default charset to use for parsing properties files. + * Used if no file-specific charset is specified for a file. + *

    Default is none, using the java.util.Properties + * default encoding. + *

    Only applies to classic properties files, not to XML files. + * @param defaultEncoding the default charset + * @see #setFileEncodings + * @see org.springframework.util.PropertiesPersister#load + */ + public void setDefaultEncoding(String defaultEncoding) { + this.defaultEncoding = defaultEncoding; + } + + /** + * Set per-file charsets to use for parsing properties files. + *

    Only applies to classic properties files, not to XML files. + * @param fileEncodings Properties with filenames as keys and charset + * names as values. Filenames have to match the basename syntax, + * with optional locale-specific appendices: e.g. "WEB-INF/messages" + * or "WEB-INF/messages_en". + * @see #setBasenames + * @see org.springframework.util.PropertiesPersister#load + */ + public void setFileEncodings(Properties fileEncodings) { + this.fileEncodings = fileEncodings; + } + + /** + * Set whether to fall back to the system Locale if no files for a specific + * Locale have been found. Default is "true"; if this is turned off, the only + * fallback will be the default file (e.g. "messages.properties" for + * basename "messages"). + *

    Falling back to the system Locale is the default behavior of + * java.util.ResourceBundle. However, this is often not + * desirable in an application server environment, where the system Locale + * is not relevant to the application at all: Set this flag to "false" + * in such a scenario. + */ + public void setFallbackToSystemLocale(boolean fallbackToSystemLocale) { + this.fallbackToSystemLocale = fallbackToSystemLocale; + } + + /** + * Set the number of seconds to cache loaded properties files. + *

      + *
    • Default is "-1", indicating to cache forever (just like + * java.util.ResourceBundle). + *
    • A positive number will cache loaded properties files for the given + * number of seconds. This is essentially the interval between refresh checks. + * Note that a refresh attempt will first check the last-modified timestamp + * of the file before actually reloading it; so if files don't change, this + * interval can be set rather low, as refresh attempts will not actually reload. + *
    • A value of "0" will check the last-modified timestamp of the file on + * every message access. Do not use this in a production environment! + *
    + */ + public void setCacheSeconds(int cacheSeconds) { + this.cacheMillis = (cacheSeconds * 1000); + } + + /** + * Set the PropertiesPersister to use for parsing properties files. + *

    The default is a DefaultPropertiesPersister. + * @see org.springframework.util.DefaultPropertiesPersister + */ + public void setPropertiesPersister(PropertiesPersister propertiesPersister) { + this.propertiesPersister = + (propertiesPersister != null ? propertiesPersister : new DefaultPropertiesPersister()); + } + + /** + * Set the ResourceLoader to use for loading bundle properties files. + *

    The default is a DefaultResourceLoader. Will get overridden by the + * ApplicationContext if running in a context, as it implements the + * ResourceLoaderAware interface. Can be manually overridden when + * running outside of an ApplicationContext. + * @see org.springframework.core.io.DefaultResourceLoader + * @see org.springframework.context.ResourceLoaderAware + */ + public void setResourceLoader(ResourceLoader resourceLoader) { + this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader()); + } + + + /** + * Resolves the given message code as key in the retrieved bundle files, + * returning the value found in the bundle as-is (without MessageFormat parsing). + */ + protected String resolveCodeWithoutArguments(String code, Locale locale) { + if (this.cacheMillis < 0) { + PropertiesHolder propHolder = getMergedProperties(locale); + String result = propHolder.getProperty(code); + if (result != null) { + return result; + } + } + else { + for (int i = 0; i < this.basenames.length; i++) { + List filenames = calculateAllFilenames(this.basenames[i], locale); + for (int j = 0; j < filenames.size(); j++) { + String filename = (String) filenames.get(j); + PropertiesHolder propHolder = getProperties(filename); + String result = propHolder.getProperty(code); + if (result != null) { + return result; + } + } + } + } + return null; + } + + /** + * Resolves the given message code as key in the retrieved bundle files, + * using a cached MessageFormat instance per message code. + */ + protected MessageFormat resolveCode(String code, Locale locale) { + if (this.cacheMillis < 0) { + PropertiesHolder propHolder = getMergedProperties(locale); + MessageFormat result = propHolder.getMessageFormat(code, locale); + if (result != null) { + return result; + } + } + else { + for (int i = 0; i < this.basenames.length; i++) { + List filenames = calculateAllFilenames(this.basenames[i], locale); + for (int j = 0; j < filenames.size(); j++) { + String filename = (String) filenames.get(j); + PropertiesHolder propHolder = getProperties(filename); + MessageFormat result = propHolder.getMessageFormat(code, locale); + if (result != null) { + return result; + } + } + } + } + return null; + } + + + /** + * Get a PropertiesHolder that contains the actually visible properties + * for a Locale, after merging all specified resource bundles. + * Either fetches the holder from the cache or freshly loads it. + *

    Only used when caching resource bundle contents forever, i.e. + * with cacheSeconds < 0. Therefore, merged properties are always + * cached forever. + */ + protected PropertiesHolder getMergedProperties(Locale locale) { + synchronized (this.cachedMergedProperties) { + PropertiesHolder mergedHolder = (PropertiesHolder) this.cachedMergedProperties.get(locale); + if (mergedHolder != null) { + return mergedHolder; + } + Properties mergedProps = new Properties(); + mergedHolder = new PropertiesHolder(mergedProps, -1); + for (int i = this.basenames.length - 1; i >= 0; i--) { + List filenames = calculateAllFilenames(this.basenames[i], locale); + for (int j = filenames.size() - 1; j >= 0; j--) { + String filename = (String) filenames.get(j); + PropertiesHolder propHolder = getProperties(filename); + if (propHolder.getProperties() != null) { + mergedProps.putAll(propHolder.getProperties()); + } + } + } + this.cachedMergedProperties.put(locale, mergedHolder); + return mergedHolder; + } + } + + /** + * Calculate all filenames for the given bundle basename and Locale. + * Will calculate filenames for the given Locale, the system Locale + * (if applicable), and the default file. + * @param basename the basename of the bundle + * @param locale the locale + * @return the List of filenames to check + * @see #setFallbackToSystemLocale + * @see #calculateFilenamesForLocale + */ + protected List calculateAllFilenames(String basename, Locale locale) { + synchronized (this.cachedFilenames) { + Map localeMap = (Map) this.cachedFilenames.get(basename); + if (localeMap != null) { + List filenames = (List) localeMap.get(locale); + if (filenames != null) { + return filenames; + } + } + List filenames = new ArrayList(7); + filenames.addAll(calculateFilenamesForLocale(basename, locale)); + if (this.fallbackToSystemLocale && !locale.equals(Locale.getDefault())) { + List fallbackFilenames = calculateFilenamesForLocale(basename, Locale.getDefault()); + for (Iterator it = fallbackFilenames.iterator(); it.hasNext();) { + String fallbackFilename = (String) it.next(); + if (!filenames.contains(fallbackFilename)) { + // Entry for fallback locale that isn't already in filenames list. + filenames.add(fallbackFilename); + } + } + } + filenames.add(basename); + if (localeMap != null) { + localeMap.put(locale, filenames); + } + else { + localeMap = new HashMap(); + localeMap.put(locale, filenames); + this.cachedFilenames.put(basename, localeMap); + } + return filenames; + } + } + + /** + * Calculate the filenames for the given bundle basename and Locale, + * appending language code, country code, and variant code. + * E.g.: basename "messages", Locale "de_AT_oo" -> "messages_de_AT_OO", + * "messages_de_AT", "messages_de". + * @param basename the basename of the bundle + * @param locale the locale + * @return the List of filenames to check + */ + protected List calculateFilenamesForLocale(String basename, Locale locale) { + List result = new ArrayList(3); + String language = locale.getLanguage(); + String country = locale.getCountry(); + String variant = locale.getVariant(); + StringBuffer temp = new StringBuffer(basename); + + if (language.length() > 0) { + temp.append('_').append(language); + result.add(0, temp.toString()); + } + + if (country.length() > 0) { + temp.append('_').append(country); + result.add(0, temp.toString()); + } + + if (variant.length() > 0) { + temp.append('_').append(variant); + result.add(0, temp.toString()); + } + + return result; + } + + + /** + * Get a PropertiesHolder for the given filename, either from the + * cache or freshly loaded. + * @param filename the bundle filename (basename + Locale) + * @return the current PropertiesHolder for the bundle + */ + protected PropertiesHolder getProperties(String filename) { + synchronized (this.cachedProperties) { + PropertiesHolder propHolder = (PropertiesHolder) this.cachedProperties.get(filename); + if (propHolder != null && + (propHolder.getRefreshTimestamp() < 0 || + propHolder.getRefreshTimestamp() > System.currentTimeMillis() - this.cacheMillis)) { + // up to date + return propHolder; + } + return refreshProperties(filename, propHolder); + } + } + + /** + * Refresh the PropertiesHolder for the given bundle filename. + * The holder can be null if not cached before, or a timed-out cache entry + * (potentially getting re-validated against the current last-modified timestamp). + * @param filename the bundle filename (basename + Locale) + * @param propHolder the current PropertiesHolder for the bundle + */ + protected PropertiesHolder refreshProperties(String filename, PropertiesHolder propHolder) { + long refreshTimestamp = (this.cacheMillis < 0) ? -1 : System.currentTimeMillis(); + + Resource resource = this.resourceLoader.getResource(filename + PROPERTIES_SUFFIX); + if (!resource.exists()) { + resource = this.resourceLoader.getResource(filename + XML_SUFFIX); + } + + if (resource.exists()) { + long fileTimestamp = -1; + if (this.cacheMillis >= 0) { + // Last-modified timestamp of file will just be read if caching with timeout. + try { + fileTimestamp = resource.lastModified(); + if (propHolder != null && propHolder.getFileTimestamp() == fileTimestamp) { + if (logger.isDebugEnabled()) { + logger.debug("Re-caching properties for filename [" + filename + "] - file hasn't been modified"); + } + propHolder.setRefreshTimestamp(refreshTimestamp); + return propHolder; + } + } + catch (IOException ex) { + // Probably a class path resource: cache it forever. + if (logger.isDebugEnabled()) { + logger.debug( + resource + " could not be resolved in the file system - assuming that is hasn't changed", ex); + } + fileTimestamp = -1; + } + } + try { + Properties props = loadProperties(resource, filename); + propHolder = new PropertiesHolder(props, fileTimestamp); + } + catch (IOException ex) { + if (logger.isWarnEnabled()) { + logger.warn("Could not parse properties file [" + resource.getFilename() + "]", ex); + } + // Empty holder representing "not valid". + propHolder = new PropertiesHolder(); + } + } + + else { + // Resource does not exist. + if (logger.isDebugEnabled()) { + logger.debug("No properties file found for [" + filename + "] - neither plain properties nor XML"); + } + // Empty holder representing "not found". + propHolder = new PropertiesHolder(); + } + + propHolder.setRefreshTimestamp(refreshTimestamp); + this.cachedProperties.put(filename, propHolder); + return propHolder; + } + + /** + * Load the properties from the given resource. + * @param resource the resource to load from + * @param filename the original bundle filename (basename + Locale) + * @return the populated Properties instance + * @throws IOException if properties loading failed + */ + protected Properties loadProperties(Resource resource, String filename) throws IOException { + InputStream is = resource.getInputStream(); + Properties props = new Properties(); + try { + if (resource.getFilename().endsWith(XML_SUFFIX)) { + if (logger.isDebugEnabled()) { + logger.debug("Loading properties [" + resource.getFilename() + "]"); + } + this.propertiesPersister.loadFromXml(props, is); + } + else { + String encoding = null; + if (this.fileEncodings != null) { + encoding = this.fileEncodings.getProperty(filename); + } + if (encoding == null) { + encoding = this.defaultEncoding; + } + if (encoding != null) { + if (logger.isDebugEnabled()) { + logger.debug("Loading properties [" + resource.getFilename() + "] with encoding '" + encoding + "'"); + } + this.propertiesPersister.load(props, new InputStreamReader(is, encoding)); + } + else { + if (logger.isDebugEnabled()) { + logger.debug("Loading properties [" + resource.getFilename() + "]"); + } + this.propertiesPersister.load(props, is); + } + } + return props; + } + finally { + is.close(); + } + } + + + /** + * Clear the resource bundle cache. + * Subsequent resolve calls will lead to reloading of the properties files. + */ + public void clearCache() { + logger.debug("Clearing entire resource bundle cache"); + synchronized (this.cachedProperties) { + this.cachedProperties.clear(); + } + synchronized (this.cachedMergedProperties) { + this.cachedMergedProperties.clear(); + } + } + + /** + * Clear the resource bundle caches of this MessageSource and all its ancestors. + * @see #clearCache + */ + public void clearCacheIncludingAncestors() { + clearCache(); + if (getParentMessageSource() instanceof ReloadableResourceBundleMessageSource) { + ((ReloadableResourceBundleMessageSource) getParentMessageSource()).clearCacheIncludingAncestors(); + } + } + + + public String toString() { + return getClass().getName() + ": basenames=[" + StringUtils.arrayToCommaDelimitedString(this.basenames) + "]"; + } + + + /** + * PropertiesHolder for caching. + * Stores the last-modified timestamp of the source file for efficient + * change detection, and the timestamp of the last refresh attempt + * (updated every time the cache entry gets re-validated). + */ + protected class PropertiesHolder { + + private Properties properties; + + private long fileTimestamp = -1; + + private long refreshTimestamp = -1; + + /** Cache to hold already generated MessageFormats per message code */ + private final Map cachedMessageFormats = new HashMap(); + + public PropertiesHolder(Properties properties, long fileTimestamp) { + this.properties = properties; + this.fileTimestamp = fileTimestamp; + } + + public PropertiesHolder() { + } + + public Properties getProperties() { + return properties; + } + + public long getFileTimestamp() { + return fileTimestamp; + } + + public void setRefreshTimestamp(long refreshTimestamp) { + this.refreshTimestamp = refreshTimestamp; + } + + public long getRefreshTimestamp() { + return refreshTimestamp; + } + + public String getProperty(String code) { + if (this.properties == null) { + return null; + } + return this.properties.getProperty(code); + } + + public MessageFormat getMessageFormat(String code, Locale locale) { + if (this.properties == null) { + return null; + } + synchronized (this.cachedMessageFormats) { + Map localeMap = (Map) this.cachedMessageFormats.get(code); + if (localeMap != null) { + MessageFormat result = (MessageFormat) localeMap.get(locale); + if (result != null) { + return result; + } + } + String msg = this.properties.getProperty(code); + if (msg != null) { + if (localeMap == null) { + localeMap = new HashMap(); + this.cachedMessageFormats.put(code, localeMap); + } + MessageFormat result = createMessageFormat(msg, locale); + localeMap.put(locale, result); + return result; + } + return null; + } + } + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/ResourceBundleMessageSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/ResourceBundleMessageSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/ResourceBundleMessageSource.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,306 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +/** + * {@link org.springframework.context.MessageSource} implementation that + * accesses resource bundles using specified basenames. This class relies + * on the underlying JDK's {@link java.util.ResourceBundle} implementation, + * in combination with the JDK's standard message parsing provided by + * {@link java.text.MessageFormat}. + * + *

    This MessageSource caches both the accessed ResourceBundle instances and + * the generated MessageFormats for each message. It also implements rendering of + * no-arg messages without MessageFormat, as supported by the AbstractMessageSource + * base class. The caching provided by this MessageSource is significantly faster + * than the built-in caching of the java.util.ResourceBundle class. + * + *

    Unfortunately, java.util.ResourceBundle caches loaded bundles + * forever: Reloading a bundle during VM execution is not possible. + * As this MessageSource relies on ResourceBundle, it faces the same limitation. + * Consider {@link ReloadableResourceBundleMessageSource} for an alternative + * that is capable of refreshing the underlying bundle files. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see #setBasenames + * @see ReloadableResourceBundleMessageSource + * @see java.util.ResourceBundle + * @see java.text.MessageFormat + */ +public class ResourceBundleMessageSource extends AbstractMessageSource implements BeanClassLoaderAware { + + private String[] basenames = new String[0]; + + private ClassLoader bundleClassLoader; + + private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); + + /** + * Cache to hold loaded ResourceBundles. + * This Map is keyed with the bundle basename, which holds a Map that is + * keyed with the Locale and in turn holds the ResourceBundle instances. + * This allows for very efficient hash lookups, significantly faster + * than the ResourceBundle class's own cache. + */ + private final Map cachedResourceBundles = new HashMap(); + + /** + * Cache to hold already generated MessageFormats. + * This Map is keyed with the ResourceBundle, which holds a Map that is + * keyed with the message code, which in turn holds a Map that is keyed + * with the Locale and holds the MessageFormat values. This allows for + * very efficient hash lookups without concatenated keys. + * @see #getMessageFormat + */ + private final Map cachedBundleMessageFormats = new HashMap(); + + + /** + * Set a single basename, following {@link java.util.ResourceBundle} conventions: + * essentially, a fully-qualified classpath location. If it doesn't contain a + * package qualifier (such as org.mypackage), it will be resolved + * from the classpath root. + *

    Messages will normally be held in the "/lib" or "/classes" directory of + * a web application's WAR structure. They can also be held in jar files on + * the class path. + *

    Note that ResourceBundle names are effectively classpath locations: As a + * consequence, the JDK's standard ResourceBundle treats dots as package separators. + * This means that "test.theme" is effectively equivalent to "test/theme", + * just like it is for programmatic java.util.ResourceBundle usage. + * @see #setBasenames + * @see java.util.ResourceBundle#getBundle(String) + */ + public void setBasename(String basename) { + setBasenames(new String[] {basename}); + } + + /** + * Set an array of basenames, each following {@link java.util.ResourceBundle} + * conventions: essentially, a fully-qualified classpath location. If it + * doesn't contain a package qualifier (such as org.mypackage), + * it will be resolved from the classpath root. + *

    The associated resource bundles will be checked sequentially + * when resolving a message code. Note that message definitions in a + * previous resource bundle will override ones in a later bundle, + * due to the sequential lookup. + *

    Note that ResourceBundle names are effectively classpath locations: As a + * consequence, the JDK's standard ResourceBundle treats dots as package separators. + * This means that "test.theme" is effectively equivalent to "test/theme", + * just like it is for programmatic java.util.ResourceBundle usage. + * @see #setBasename + * @see java.util.ResourceBundle#getBundle(String) + */ + public void setBasenames(String[] basenames) { + if (basenames != null) { + this.basenames = new String[basenames.length]; + for (int i = 0; i < basenames.length; i++) { + String basename = basenames[i]; + Assert.hasText(basename, "Basename must not be empty"); + this.basenames[i] = basename.trim(); + } + } + else { + this.basenames = new String[0]; + } + } + + /** + * Set the ClassLoader to load resource bundles with. + *

    Default is the containing BeanFactory's + * {@link org.springframework.beans.factory.BeanClassLoaderAware bean ClassLoader}, + * or the default ClassLoader determined by + * {@link org.springframework.util.ClassUtils#getDefaultClassLoader()} + * if not running within a BeanFactory. + */ + public void setBundleClassLoader(ClassLoader classLoader) { + this.bundleClassLoader = classLoader; + } + + /** + * Return the ClassLoader to load resource bundles with. + *

    Default is the containing BeanFactory's bean ClassLoader. + * @see #setBundleClassLoader + */ + protected ClassLoader getBundleClassLoader() { + return (this.bundleClassLoader != null ? this.bundleClassLoader : this.beanClassLoader); + } + + public void setBeanClassLoader(ClassLoader classLoader) { + this.beanClassLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); + } + + + /** + * Resolves the given message code as key in the registered resource bundles, + * returning the value found in the bundle as-is (without MessageFormat parsing). + */ + protected String resolveCodeWithoutArguments(String code, Locale locale) { + String result = null; + for (int i = 0; result == null && i < this.basenames.length; i++) { + ResourceBundle bundle = getResourceBundle(this.basenames[i], locale); + if (bundle != null) { + result = getStringOrNull(bundle, code); + } + } + return result; + } + + /** + * Resolves the given message code as key in the registered resource bundles, + * using a cached MessageFormat instance per message code. + */ + protected MessageFormat resolveCode(String code, Locale locale) { + MessageFormat messageFormat = null; + for (int i = 0; messageFormat == null && i < this.basenames.length; i++) { + ResourceBundle bundle = getResourceBundle(this.basenames[i], locale); + if (bundle != null) { + messageFormat = getMessageFormat(bundle, code, locale); + } + } + return messageFormat; + } + + + /** + * Return a ResourceBundle for the given basename and code, + * fetching already generated MessageFormats from the cache. + * @param basename the basename of the ResourceBundle + * @param locale the Locale to find the ResourceBundle for + * @return the resulting ResourceBundle, or null if none + * found for the given basename and Locale + */ + protected ResourceBundle getResourceBundle(String basename, Locale locale) { + synchronized (this.cachedResourceBundles) { + Map localeMap = (Map) this.cachedResourceBundles.get(basename); + if (localeMap != null) { + ResourceBundle bundle = (ResourceBundle) localeMap.get(locale); + if (bundle != null) { + return bundle; + } + } + try { + ResourceBundle bundle = doGetBundle(basename, locale); + if (localeMap == null) { + localeMap = new HashMap(); + this.cachedResourceBundles.put(basename, localeMap); + } + localeMap.put(locale, bundle); + return bundle; + } + catch (MissingResourceException ex) { + if (logger.isWarnEnabled()) { + logger.warn("ResourceBundle [" + basename + "] not found for MessageSource: " + ex.getMessage()); + } + // Assume bundle not found + // -> do NOT throw the exception to allow for checking parent message source. + return null; + } + } + } + + /** + * Obtain the resource bundle for the given basename and Locale. + * @param basename the basename to look for + * @param locale the Locale to look for + * @return the corresponding ResourceBundle + * @throws MissingResourceException if no matching bundle could be found + * @see java.util.ResourceBundle#getBundle(String, java.util.Locale, ClassLoader) + * @see #getBundleClassLoader() + */ + protected ResourceBundle doGetBundle(String basename, Locale locale) throws MissingResourceException { + return ResourceBundle.getBundle(basename, locale, getBundleClassLoader()); + } + + /** + * Return a MessageFormat for the given bundle and code, + * fetching already generated MessageFormats from the cache. + * @param bundle the ResourceBundle to work on + * @param code the message code to retrieve + * @param locale the Locale to use to build the MessageFormat + * @return the resulting MessageFormat, or null if no message + * defined for the given code + * @throws MissingResourceException if thrown by the ResourceBundle + */ + protected MessageFormat getMessageFormat(ResourceBundle bundle, String code, Locale locale) + throws MissingResourceException { + + synchronized (this.cachedBundleMessageFormats) { + Map codeMap = (Map) this.cachedBundleMessageFormats.get(bundle); + Map localeMap = null; + if (codeMap != null) { + localeMap = (Map) codeMap.get(code); + if (localeMap != null) { + MessageFormat result = (MessageFormat) localeMap.get(locale); + if (result != null) { + return result; + } + } + } + + String msg = getStringOrNull(bundle, code); + if (msg != null) { + if (codeMap == null) { + codeMap = new HashMap(); + this.cachedBundleMessageFormats.put(bundle, codeMap); + } + if (localeMap == null) { + localeMap = new HashMap(); + codeMap.put(code, localeMap); + } + MessageFormat result = createMessageFormat(msg, locale); + localeMap.put(locale, result); + return result; + } + + return null; + } + } + + private String getStringOrNull(ResourceBundle bundle, String key) { + try { + return bundle.getString(key); + } + catch (MissingResourceException ex) { + // Assume key not found + // -> do NOT throw the exception to allow for checking parent message source. + return null; + } + } + + + /** + * Show the configuration of this MessageSource. + */ + public String toString() { + return getClass().getName() + ": basenames=[" + + StringUtils.arrayToCommaDelimitedString(this.basenames) + "]"; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/ResourceMapFactoryBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/ResourceMapFactoryBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/ResourceMapFactoryBean.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,98 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.io.IOException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.springframework.beans.factory.config.PropertiesFactoryBean; +import org.springframework.context.ResourceLoaderAware; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; + +/** + * FactoryBean that creates a Map with String keys and Resource values from + * properties, interpreting passed-in String values as resource locations. + * + *

    Extends PropertiesFactoryBean to inherit the capability of defining + * local properties and loading from properties files. + * + *

    Implements the ResourceLoaderAware interface to automatically use + * the context ResourceLoader if running in an ApplicationContext. + * Uses DefaultResourceLoader else. + * + * @author Juergen Hoeller + * @author Keith Donald + * @since 1.0.2 + * @see org.springframework.core.io.DefaultResourceLoader + */ +public class ResourceMapFactoryBean extends PropertiesFactoryBean implements ResourceLoaderAware { + + private String resourceBasePath = ""; + + private ResourceLoader resourceLoader = new DefaultResourceLoader(); + + + /** + * Set a base path to prepend to each resource location value + * in the properties file. + *

    E.g.: resourceBasePath="/images", value="/test.gif" + * -> location="/images/test.gif" + */ + public void setResourceBasePath(String resourceBasePath) { + this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : ""); + } + + public void setResourceLoader(ResourceLoader resourceLoader) { + this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader()); + } + + + public Class getObjectType() { + return Map.class; + } + + /** + * Create the Map instance, populated with keys and Resource values. + */ + protected Object createInstance() throws IOException { + Map resourceMap = new HashMap(); + Properties props = mergeProperties(); + for (Enumeration en = props.propertyNames(); en.hasMoreElements();) { + String key = (String) en.nextElement(); + String location = props.getProperty(key); + resourceMap.put(key, getResource(location)); + } + return resourceMap; + } + + /** + * Fetch the Resource handle for the given location, + * prepeding the resource base path. + * @param location the resource location + * @return the Resource handle + * @see org.springframework.core.io.ResourceLoader#getResource(String) + */ + protected Resource getResource(String location) { + return this.resourceLoader.getResource(this.resourceBasePath + location); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/StaticApplicationContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/StaticApplicationContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/StaticApplicationContext.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,140 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.util.Locale; + +import org.springframework.beans.BeansException; +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.support.GenericBeanDefinition; +import org.springframework.context.ApplicationContext; + +/** + * {@link org.springframework.context.ApplicationContext} implementation + * which supports programmatic registration of beans and messages, + * rather than reading bean definitions from external configuration sources. + * Mainly useful for testing. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @see #registerSingleton + * @see #registerPrototype + * @see #registerBeanDefinition + * @see #refresh + */ +public class StaticApplicationContext extends GenericApplicationContext { + + private final StaticMessageSource staticMessageSource; + + + /** + * Create a new StaticApplicationContext. + * @see #registerSingleton + * @see #registerPrototype + * @see #registerBeanDefinition + * @see #refresh + */ + public StaticApplicationContext() throws BeansException { + this(null); + } + + /** + * Create a new StaticApplicationContext with the given parent. + * @see #registerSingleton + * @see #registerPrototype + * @see #registerBeanDefinition + * @see #refresh + */ + public StaticApplicationContext(ApplicationContext parent) throws BeansException { + super(parent); + + // Initialize and register a StaticMessageSource. + this.staticMessageSource = new StaticMessageSource(); + getBeanFactory().registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.staticMessageSource); + } + + + /** + * Return the internal StaticMessageSource used by this context. + * Can be used to register messages on it. + * @see #addMessage + */ + public final StaticMessageSource getStaticMessageSource() { + return this.staticMessageSource; + } + + + /** + * Register a singleton bean with the underlying bean factory. + *

    For more advanced needs, register with the underlying BeanFactory directly. + * @see #getDefaultListableBeanFactory + */ + public void registerSingleton(String name, Class clazz) throws BeansException { + GenericBeanDefinition bd = new GenericBeanDefinition(); + bd.setBeanClass(clazz); + getDefaultListableBeanFactory().registerBeanDefinition(name, bd); + } + + /** + * Register a singleton bean with the underlying bean factory. + *

    For more advanced needs, register with the underlying BeanFactory directly. + * @see #getDefaultListableBeanFactory + */ + public void registerSingleton(String name, Class clazz, MutablePropertyValues pvs) throws BeansException { + GenericBeanDefinition bd = new GenericBeanDefinition(); + bd.setBeanClass(clazz); + bd.setPropertyValues(pvs); + getDefaultListableBeanFactory().registerBeanDefinition(name, bd); + } + + /** + * Register a prototype bean with the underlying bean factory. + *

    For more advanced needs, register with the underlying BeanFactory directly. + * @see #getDefaultListableBeanFactory + */ + public void registerPrototype(String name, Class clazz) throws BeansException { + GenericBeanDefinition bd = new GenericBeanDefinition(); + bd.setScope(GenericBeanDefinition.SCOPE_PROTOTYPE); + bd.setBeanClass(clazz); + getDefaultListableBeanFactory().registerBeanDefinition(name, bd); + } + + /** + * Register a prototype bean with the underlying bean factory. + *

    For more advanced needs, register with the underlying BeanFactory directly. + * @see #getDefaultListableBeanFactory + */ + public void registerPrototype(String name, Class clazz, MutablePropertyValues pvs) throws BeansException { + GenericBeanDefinition bd = new GenericBeanDefinition(); + bd.setScope(GenericBeanDefinition.SCOPE_PROTOTYPE); + bd.setBeanClass(clazz); + bd.setPropertyValues(pvs); + getDefaultListableBeanFactory().registerBeanDefinition(name, bd); + } + + /** + * Associate the given message with the given code. + * @param code lookup code + * @param locale locale message should be found within + * @param defaultMessage message associated with this lookup code + * @see #getStaticMessageSource + */ + public void addMessage(String code, Locale locale, String defaultMessage) { + getStaticMessageSource().addMessage(code, locale, defaultMessage); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/StaticMessageSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/StaticMessageSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/StaticMessageSource.java 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,82 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; + +import org.springframework.util.Assert; + +/** + * Simple implementation of {@link org.springframework.context.MessageSource} + * which allows messages to be registered programmatically. + * This MessageSource supports basic internationalization. + * + *

    Intended for testing rather than for use in production systems. + * + * @author Rod Johnson + * @author Juergen Hoeller + */ +public class StaticMessageSource extends AbstractMessageSource { + + /** Map from 'code + locale' keys to message Strings */ + private final Map messages = new HashMap(); + + + protected MessageFormat resolveCode(String code, Locale locale) { + return (MessageFormat) this.messages.get(code + "_" + locale.toString()); + } + + /** + * Associate the given message with the given code. + * @param code the lookup code + * @param locale the locale that the message should be found within + * @param msg the message associated with this lookup code + */ + public void addMessage(String code, Locale locale, String msg) { + Assert.notNull(code, "Code must not be null"); + Assert.notNull(locale, "Locale must not be null"); + Assert.notNull(msg, "Message must not be null"); + this.messages.put(code + "_" + locale.toString(), createMessageFormat(msg, locale)); + if (logger.isDebugEnabled()) { + logger.debug("Added message [" + msg + "] for code [" + code + "] and Locale [" + locale + "]"); + } + } + + /** + * Associate the given message values with the given keys as codes. + * @param messages the messages to register, with messages codes + * as keys and message texts as values + * @param locale the locale that the messages should be found within + */ + public void addMessages(Map messages, Locale locale) { + Assert.notNull(messages, "Messages Map must not be null"); + for (Iterator it = messages.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + addMessage(entry.getKey().toString(), locale, entry.getValue().toString()); + } + } + + + public String toString() { + return getClass().getName() + ": " + this.messages; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/support/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/support/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/support/package.html 17 Aug 2012 15:14:37 -0000 1.1 @@ -0,0 +1,9 @@ + + + +Classes supporting the org.springframework.context package, +such as abstract base classes for ApplicationContext +implementations and a MessageSource implementation. + + + Index: 3rdParty_sources/spring/org/springframework/context/weaving/AspectJWeavingEnabler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/weaving/AspectJWeavingEnabler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/weaving/AspectJWeavingEnabler.java 17 Aug 2012 15:14:39 -0000 1.1 @@ -0,0 +1,96 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.weaving; + +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.IllegalClassFormatException; +import java.security.ProtectionDomain; + +import org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.core.Ordered; +import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver; +import org.springframework.instrument.classloading.LoadTimeWeaver; + +/** + * Post-processor that registers AspectJ's + * {@link org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter} + * with the Spring application context's default + * {@link org.springframework.instrument.classloading.LoadTimeWeaver}. + * + * @author Juergen Hoeller + * @author Ramnivas Laddad + * @since 2.5 + */ +public class AspectJWeavingEnabler + implements BeanFactoryPostProcessor, BeanClassLoaderAware, LoadTimeWeaverAware, Ordered { + + private ClassLoader beanClassLoader; + + private LoadTimeWeaver loadTimeWeaver; + + + public void setBeanClassLoader(ClassLoader classLoader) { + this.beanClassLoader = classLoader; + } + + public void setLoadTimeWeaver(LoadTimeWeaver loadTimeWeaver) { + this.loadTimeWeaver = loadTimeWeaver; + } + + public int getOrder() { + return HIGHEST_PRECEDENCE; + } + + + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + LoadTimeWeaver weaverToUse = this.loadTimeWeaver; + if (weaverToUse == null && InstrumentationLoadTimeWeaver.isInstrumentationAvailable()) { + weaverToUse = new InstrumentationLoadTimeWeaver(this.beanClassLoader); + } + weaverToUse.addTransformer(new AspectJClassBypassingClassFileTransformer( + new ClassPreProcessorAgentAdapter())); + } + + + /* + * Decorator to suppress processing AspectJ classes, hence avoiding potential LinkageErrors. + * OC4J and Tomcat (in Glassfish) definitely need such bypassing of AspectJ classes. + */ + private static class AspectJClassBypassingClassFileTransformer implements ClassFileTransformer { + + private final ClassFileTransformer delegate; + + public AspectJClassBypassingClassFileTransformer(ClassFileTransformer delegate) { + this.delegate = delegate; + } + + public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, + ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { + + if (className.startsWith("org.aspectj") || className.startsWith("org/aspectj")) { + return classfileBuffer; + } + return this.delegate.transform(loader, className, classBeingRedefined, protectionDomain, classfileBuffer); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/context/weaving/DefaultContextLoadTimeWeaver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/weaving/DefaultContextLoadTimeWeaver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/weaving/DefaultContextLoadTimeWeaver.java 17 Aug 2012 15:14:39 -0000 1.1 @@ -0,0 +1,136 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.weaving; + +import java.lang.instrument.ClassFileTransformer; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.instrument.InstrumentationSavingAgent; +import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver; +import org.springframework.instrument.classloading.LoadTimeWeaver; +import org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver; +import org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver; +import org.springframework.instrument.classloading.oc4j.OC4JLoadTimeWeaver; +import org.springframework.instrument.classloading.weblogic.WebLogicLoadTimeWeaver; + +/** + * Default {@link LoadTimeWeaver} bean for use in an application context, + * decorating an automatically detected internal LoadTimeWeaver. + * + *

    Typically registered for the default bean name + * "loadTimeWeaver"; the most convenient way to achieve this is + * Spring's <context:load-time-weaver> XML tag. + * + *

    This class implements a runtime environment check for obtaining the + * appropriate weaver implementation: As of Spring 2.5, it detects Sun's + * GlassFish, Oracle's OC4J, BEA's WebLogic 10, + * {@link InstrumentationSavingAgent Spring's VM agent} and any + * {@link ClassLoader} supported by Spring's {@link ReflectiveLoadTimeWeaver} + * (for example the + * {@link org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader}). + * + * @author Juergen Hoeller + * @author Ramnivas Laddad + * @since 2.5 + * @see org.springframework.context.ConfigurableApplicationContext#LOAD_TIME_WEAVER_BEAN_NAME + */ +public class DefaultContextLoadTimeWeaver implements LoadTimeWeaver, BeanClassLoaderAware, DisposableBean { + + protected final Log logger = LogFactory.getLog(getClass()); + + private LoadTimeWeaver loadTimeWeaver; + + + public void setBeanClassLoader(ClassLoader classLoader) { + LoadTimeWeaver serverSpecificLoadTimeWeaver = createServerSpecificLoadTimeWeaver(classLoader); + if (serverSpecificLoadTimeWeaver != null) { + if (logger.isInfoEnabled()) { + logger.info("Determined server-specific load-time weaver: " + + serverSpecificLoadTimeWeaver.getClass().getName()); + } + this.loadTimeWeaver = serverSpecificLoadTimeWeaver; + } + else if (InstrumentationLoadTimeWeaver.isInstrumentationAvailable()) { + logger.info("Found Spring's JVM agent for instrumentation"); + this.loadTimeWeaver = new InstrumentationLoadTimeWeaver(classLoader); + } + else { + try { + this.loadTimeWeaver = new ReflectiveLoadTimeWeaver(classLoader); + logger.info("Using a reflective load-time weaver for class loader: " + + this.loadTimeWeaver.getInstrumentableClassLoader().getClass().getName()); + } + catch (IllegalStateException ex) { + throw new IllegalStateException(ex.getMessage() + " Specify a custom LoadTimeWeaver " + + "or start your Java virtual machine with Spring's agent: -javaagent:spring-agent.jar"); + } + } + } + + /* + * This method never fails, allowing to try other possible ways to use an + * server-agnostic weaver. This non-failure logic is required since + * determining a load-time weaver based on the ClassLoader name alone may + * legitimately fail due to other mismatches. Specific case in point: the + * use of WebLogicLoadTimeWeaver works for WLS 10 but fails due to the lack + * of a specific method (addInstanceClassPreProcessor) for any earlier + * versions even though the ClassLoader name is the same. + */ + protected LoadTimeWeaver createServerSpecificLoadTimeWeaver(ClassLoader classLoader) { + try { + if (classLoader.getClass().getName().startsWith("weblogic")) { + return new WebLogicLoadTimeWeaver(classLoader); + } + else if (classLoader.getClass().getName().startsWith("oracle")) { + return new OC4JLoadTimeWeaver(classLoader); + } + else if (classLoader.getClass().getName().startsWith("com.sun.enterprise")) { + return new GlassFishLoadTimeWeaver(classLoader); + } + } + catch (IllegalStateException ex) { + logger.info("Could not obtain server-specific LoadTimeWeaver: " + ex.getMessage()); + } + return null; + } + + public void destroy() { + if (this.loadTimeWeaver instanceof InstrumentationLoadTimeWeaver) { + logger.info("Removing all registered transformers for class loader: " + + this.loadTimeWeaver.getInstrumentableClassLoader().getClass().getName()); + ((InstrumentationLoadTimeWeaver) this.loadTimeWeaver).removeTransformers(); + } + } + + + public void addTransformer(ClassFileTransformer transformer) { + this.loadTimeWeaver.addTransformer(transformer); + } + + public ClassLoader getInstrumentableClassLoader() { + return this.loadTimeWeaver.getInstrumentableClassLoader(); + } + + public ClassLoader getThrowawayClassLoader() { + return this.loadTimeWeaver.getThrowawayClassLoader(); + } + +} Index: 3rdParty_sources/spring/org/springframework/context/weaving/LoadTimeWeaverAware.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/weaving/LoadTimeWeaverAware.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/weaving/LoadTimeWeaverAware.java 17 Aug 2012 15:14:39 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.weaving; + +import org.springframework.instrument.classloading.LoadTimeWeaver; + +/** + * Interface to be implemented by any object that wishes to be notified + * of the application context's default {@link LoadTimeWeaver}. + * + * @author Juergen Hoeller + * @since 2.5 + * @see org.springframework.context.ConfigurableApplicationContext#LOAD_TIME_WEAVER_BEAN_NAME + */ +public interface LoadTimeWeaverAware { + + /** + * Set the {@link LoadTimeWeaver} of this object's containing + * {@link org.springframework.context.ApplicationContext ApplicationContext}. + *

    Invoked after the population of normal bean properties but before an + * initialization callback like + * {@link org.springframework.beans.factory.InitializingBean InitializingBean's} + * {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet() afterPropertiesSet()} + * or a custom init-method. Invoked after + * {@link org.springframework.context.ApplicationContextAware ApplicationContextAware's} + * {@link org.springframework.context.ApplicationContextAware#setApplicationContext setApplicationContext(..)}. + *

    NOTE: This method will only be called if there actually is a + * LoadTimeWeaver available in the application context. If + * there is none, the method will simply not get invoked, assuming that the + * implementing object is able to activate its weaving dependency accordingly. + * @param loadTimeWeaver the LoadTimeWeaver instance (never null) + * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet + * @see org.springframework.context.ApplicationContextAware#setApplicationContext + */ + void setLoadTimeWeaver(LoadTimeWeaver loadTimeWeaver); + +} Index: 3rdParty_sources/spring/org/springframework/context/weaving/LoadTimeWeaverAwareProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/weaving/LoadTimeWeaverAwareProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/weaving/LoadTimeWeaverAwareProcessor.java 17 Aug 2012 15:14:39 -0000 1.1 @@ -0,0 +1,97 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.weaving; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.instrument.classloading.LoadTimeWeaver; +import org.springframework.util.Assert; + +/** + * {@link org.springframework.beans.factory.config.BeanPostProcessor} + * implementation that passes the context's default {@link LoadTimeWeaver} + * to beans that implement the {@link LoadTimeWeaverAware} interface. + * + *

    {@link org.springframework.context.ApplicationContext Application contexts} + * will automatically register this with their underlying + * {@link BeanFactory bean factory}, provided that a default + * LoadTimeWeaver is actually available. + * + *

    Applications should not use this class directly. + * + * @author Juergen Hoeller + * @since 2.5 + * @see LoadTimeWeaverAware + * @see org.springframework.context.ConfigurableApplicationContext#LOAD_TIME_WEAVER_BEAN_NAME + */ +public class LoadTimeWeaverAwareProcessor implements BeanPostProcessor, BeanFactoryAware { + + private LoadTimeWeaver loadTimeWeaver; + + private BeanFactory beanFactory; + + + /** + * Create a new LoadTimeWeaverAwareProcessor that will + * auto-retrieve the {@link LoadTimeWeaver} from the containing + * {@link BeanFactory}, expecting a bean named + * {@link ConfigurableApplicationContext#LOAD_TIME_WEAVER_BEAN_NAME "loadTimeWeaver"}. + */ + public LoadTimeWeaverAwareProcessor() { + } + + /** + * Create a new LoadTimeWeaverAwareProcessor for the given + * {@link LoadTimeWeaver}. + *

    If the given loadTimeWeaver is null, then a + * LoadTimeWeaver will be auto-retrieved from the containing + * {@link BeanFactory}, expecting a bean named + * {@link ConfigurableApplicationContext#LOAD_TIME_WEAVER_BEAN_NAME "loadTimeWeaver"}. + * @param loadTimeWeaver the specific LoadTimeWeaver that is to be used; can be null + */ + public LoadTimeWeaverAwareProcessor(LoadTimeWeaver loadTimeWeaver) { + this.loadTimeWeaver = loadTimeWeaver; + } + + + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + + + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + if (bean instanceof LoadTimeWeaverAware) { + LoadTimeWeaver ltw = this.loadTimeWeaver; + if (ltw == null) { + Assert.state(this.beanFactory != null, + "BeanFactory required if no LoadTimeWeaver explicitly specified"); + ltw = (LoadTimeWeaver) this.beanFactory.getBean( + ConfigurableApplicationContext.LOAD_TIME_WEAVER_BEAN_NAME, LoadTimeWeaver.class); + } + ((LoadTimeWeaverAware) bean).setLoadTimeWeaver(ltw); + } + return bean; + } + + public Object postProcessAfterInitialization(Object bean, String name) { + return bean; + } + +} Index: 3rdParty_sources/spring/org/springframework/context/weaving/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/context/weaving/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/context/weaving/package.html 17 Aug 2012 15:14:39 -0000 1.1 @@ -0,0 +1,8 @@ + + + +Load-time weaving support for a Spring application context, building on Spring's +{@link org.springframework.instrument.classloading.LoadTimeWeaver} abstraction. + + + Index: 3rdParty_sources/spring/org/springframework/core/AliasRegistry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/AliasRegistry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/AliasRegistry.java 17 Aug 2012 15:14:27 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +/** + * Common interface for managing aliases. Serves as super-interface for + * {@link org.springframework.beans.factory.support.BeanDefinitionRegistry}. + * + * @author Juergen Hoeller + * @since 2.5.2 + */ +public interface AliasRegistry { + + /** + * Given a name, register an alias for it. + * @param name the canonical name + * @param alias the alias to be registered + * @throws IllegalStateException if the alias is already in use + * and may not be overridden + */ + void registerAlias(String name, String alias); + + /** + * Remove the specified alias from this registry. + * @param alias the alias to remove + * @throws IllegalStateException if no such alias was found + */ + void removeAlias(String alias); + + /** + * Determine whether this given name is defines as an alias + * (as opposed to the name of an actually registered component). + * @param beanName the bean name to check + * @return whether the given name is an alias + */ + boolean isAlias(String beanName); + + /** + * Return the aliases for the given name, if defined. + * @param name the name to check for aliases + * @return the aliases, or an empty array if none + */ + String[] getAliases(String name); + +} Index: 3rdParty_sources/spring/org/springframework/core/AttributeAccessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/AttributeAccessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/AttributeAccessor.java 17 Aug 2012 15:14:26 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +/** + * Interface defining a generic contract for attaching and accessing metadata + * to/from arbitrary objects. + * + * @author Rob Harrop + * @since 2.0 + */ +public interface AttributeAccessor { + + /** + * Set the attribute defined by name to the supplied value. + * If value is null, the attribute is {@link #removeAttribute removed}. + *

    In general, users should take care to prevent overlaps with other + * metadata attributes by using fully-qualified names, perhaps using + * class or package names as prefix. + * @param name the unique attribute key + * @param value the attribute value to be attached + */ + void setAttribute(String name, Object value); + + /** + * Get the value of the attribute identified by name. + * Return null if the attribute doesn't exist. + * @param name the unique attribute key + * @return the current value of the attribute, if any + */ + Object getAttribute(String name); + + /** + * Remove the attribute identified by name and return its value. + * Return null if no attribute under name is found. + * @param name the unique attribute key + * @return the last value of the attribute, if any + */ + Object removeAttribute(String name); + + /** + * Return true if the attribute identified by name exists. + * Otherwise return false. + * @param name the unique attribute key + */ + boolean hasAttribute(String name); + + /** + * Return the names of all attributes. + */ + String[] attributeNames(); + +} Index: 3rdParty_sources/spring/org/springframework/core/AttributeAccessorSupport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/AttributeAccessorSupport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/AttributeAccessorSupport.java 17 Aug 2012 15:14:27 -0000 1.1 @@ -0,0 +1,102 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +import java.io.Serializable; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import org.springframework.util.Assert; + +/** + * Support class for {@link AttributeAccessor AttributeAccessors}, providing + * a base implementation of all methods. To be extended by subclasses. + * + *

    {@link Serializable} if subclasses and all attribute values are {@link Serializable}. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public abstract class AttributeAccessorSupport implements AttributeAccessor, Serializable { + + /** Map with String keys and Object values */ + private final Map attributes = new LinkedHashMap(); + + + public void setAttribute(String name, Object value) { + Assert.notNull(name, "Name must not be null"); + if (value != null) { + this.attributes.put(name, value); + } + else { + removeAttribute(name); + } + } + + public Object getAttribute(String name) { + Assert.notNull(name, "Name must not be null"); + return this.attributes.get(name); + } + + public Object removeAttribute(String name) { + Assert.notNull(name, "Name must not be null"); + return this.attributes.remove(name); + } + + public boolean hasAttribute(String name) { + Assert.notNull(name, "Name must not be null"); + return this.attributes.containsKey(name); + } + + public String[] attributeNames() { + Set attributeNames = this.attributes.keySet(); + return (String[]) attributeNames.toArray(new String[attributeNames.size()]); + } + + + /** + * Copy the attributes from the supplied AttributeAccessor to this accessor. + * @param source the AttributeAccessor to copy from + */ + protected void copyAttributesFrom(AttributeAccessor source) { + Assert.notNull(source, "Source must not be null"); + String[] attributeNames = source.attributeNames(); + for (int i = 0; i < attributeNames.length; i++) { + String attributeName = attributeNames[i]; + setAttribute(attributeName, source.getAttribute(attributeName)); + } + } + + + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof AttributeAccessorSupport)) { + return false; + } + AttributeAccessorSupport that = (AttributeAccessorSupport) other; + return this.attributes.equals(that.attributes); + } + + public int hashCode() { + return this.attributes.hashCode(); + } + +} Index: 3rdParty_sources/spring/org/springframework/core/BridgeMethodResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/BridgeMethodResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/BridgeMethodResolver.java 17 Aug 2012 15:14:27 -0000 1.1 @@ -0,0 +1,206 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; + +/** + * Helper for resolving synthetic {@link Method#isBridge bridge Methods} to the + * {@link Method} being bridged. + * + *

    Given a synthetic {@link Method#isBridge bridge Method} returns the {@link Method} + * being bridged. A bridge method may be created by the compiler when extending a + * parameterized type whose methods have parameterized arguments. During runtime + * invocation the bridge {@link Method} may be invoked and/or used via reflection. + * When attempting to locate annotations on {@link Method Methods}, it is wise to check + * for bridge {@link Method Methods} as appropriate and find the bridged {@link Method}. + * + *

    See + * The Java Language Specification for more details on the use of bridge methods. + * + *

    Only usable on JDK 1.5 and higher. Use an appropriate {@link JdkVersion} + * check before calling this class if a fallback for JDK 1.4 is desirable. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + * @see JdkVersion + */ +public abstract class BridgeMethodResolver { + + /** + * Find the original method for the supplied {@link Method bridge Method}. + *

    It is safe to call this method passing in a non-bridge {@link Method} instance. + * In such a case, the supplied {@link Method} instance is returned directly to the caller. + * Callers are not required to check for bridging before calling this method. + * @throws IllegalStateException if no bridged {@link Method} can be found + */ + public static Method findBridgedMethod(Method bridgeMethod) { + if (bridgeMethod == null || !bridgeMethod.isBridge()) { + return bridgeMethod; + } + + // Gather all methods with matching name and parameter size. + List candidateMethods = new ArrayList(); + Method[] methods = ReflectionUtils.getAllDeclaredMethods(bridgeMethod.getDeclaringClass()); + for (int i = 0; i < methods.length; i++) { + Method candidateMethod = methods[i]; + if (isBridgedCandidateFor(candidateMethod, bridgeMethod)) { + candidateMethods.add(candidateMethod); + } + } + + Method result; + // Now perform simple quick checks. + if (candidateMethods.size() == 1) { + result = (Method) candidateMethods.get(0); + } + else { + result = searchCandidates(candidateMethods, bridgeMethod); + } + + if (result == null) { + throw new IllegalStateException( + "Unable to locate bridged method for bridge method '" + bridgeMethod + "'"); + } + + return result; + } + + /** + * Searches for the bridged method in the given candidates. + * @param candidateMethods the List of candidate Methods + * @param bridgeMethod the bridge method + * @return the bridged method, or null if none found + */ + private static Method searchCandidates(List candidateMethods, Method bridgeMethod) { + Map typeParameterMap = GenericTypeResolver.getTypeVariableMap(bridgeMethod.getDeclaringClass()); + for (int i = 0; i < candidateMethods.size(); i++) { + Method candidateMethod = (Method) candidateMethods.get(i); + if (isBridgeMethodFor(bridgeMethod, candidateMethod, typeParameterMap)) { + return candidateMethod; + } + } + return null; + } + + /** + * Returns true if the supplied 'candidateMethod' can be + * consider a validate candidate for the {@link Method} that is {@link Method#isBridge() bridged} + * by the supplied {@link Method bridge Method}. This method performs inexpensive + * checks and can be used quickly filter for a set of possible matches. + */ + private static boolean isBridgedCandidateFor(Method candidateMethod, Method bridgeMethod) { + return (!candidateMethod.isBridge() && !candidateMethod.equals(bridgeMethod) && + candidateMethod.getName().equals(bridgeMethod.getName()) && + candidateMethod.getParameterTypes().length == bridgeMethod.getParameterTypes().length); + } + + /** + * Determines whether or not the bridge {@link Method} is the bridge for the + * supplied candidate {@link Method}. + */ + static boolean isBridgeMethodFor(Method bridgeMethod, Method candidateMethod, Map typeVariableMap) { + if (isResolvedTypeMatch(candidateMethod, bridgeMethod, typeVariableMap)) { + return true; + } + Method method = findGenericDeclaration(bridgeMethod); + return (method != null && isResolvedTypeMatch(method, candidateMethod, typeVariableMap)); + } + + /** + * Searches for the generic {@link Method} declaration whose erased signature + * matches that of the supplied bridge method. + * @throws IllegalStateException if the generic declaration cannot be found + */ + private static Method findGenericDeclaration(Method bridgeMethod) { + // Search parent types for method that has same signature as bridge. + Class superclass = bridgeMethod.getDeclaringClass().getSuperclass(); + while (!Object.class.equals(superclass)) { + Method method = searchForMatch(superclass, bridgeMethod); + if (method != null && !method.isBridge()) { + return method; + } + superclass = superclass.getSuperclass(); + } + + // Search interfaces. + Class[] interfaces = ClassUtils.getAllInterfacesForClass(bridgeMethod.getDeclaringClass()); + for (int i = 0; i < interfaces.length; i++) { + Class anInterface = interfaces[i]; + Method method = searchForMatch(anInterface, bridgeMethod); + if (method != null && !method.isBridge()) { + return method; + } + } + + return null; + } + + /** + * Returns true if the {@link Type} signature of both the supplied + * {@link Method#getGenericParameterTypes() generic Method} and concrete {@link Method} + * are equal after resolving all {@link TypeVariable TypeVariables} using the supplied + * TypeVariable Map, otherwise returns false. + */ + private static boolean isResolvedTypeMatch(Method genericMethod, Method candidateMethod, Map typeVariableMap) { + Type[] genericParameters = genericMethod.getGenericParameterTypes(); + Class[] candidateParameters = candidateMethod.getParameterTypes(); + if (genericParameters.length != candidateParameters.length) { + return false; + } + for (int i = 0; i < genericParameters.length; i++) { + Type genericParameter = genericParameters[i]; + Class candidateParameter = candidateParameters[i]; + if (candidateParameter.isArray()) { + // An array type: compare the component type. + Type rawType = GenericTypeResolver.getRawType(genericParameter, typeVariableMap); + if (rawType instanceof GenericArrayType) { + if (!candidateParameter.getComponentType().equals( + GenericTypeResolver.resolveType(((GenericArrayType) rawType).getGenericComponentType(), typeVariableMap))) { + return false; + } + break; + } + } + // A non-array type: compare the type itself. + if (!candidateParameter.equals(GenericTypeResolver.resolveType(genericParameter, typeVariableMap))) { + return false; + } + } + return true; + } + + /** + * If the supplied {@link Class} has a declared {@link Method} whose signature matches + * that of the supplied {@link Method}, then this matching {@link Method} is returned, + * otherwise null is returned. + */ + private static Method searchForMatch(Class type, Method bridgeMethod) { + return ReflectionUtils.findMethod(type, bridgeMethod.getName(), bridgeMethod.getParameterTypes()); + } + +} Index: 3rdParty_sources/spring/org/springframework/core/CollectionFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/CollectionFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/CollectionFactory.java 17 Aug 2012 15:14:27 -0000 1.1 @@ -0,0 +1,370 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.NavigableMap; +import java.util.NavigableSet; +import java.util.Set; +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArraySet; + +import org.apache.commons.collections.map.CaseInsensitiveMap; +import org.apache.commons.collections.map.ListOrderedMap; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.util.ClassUtils; + +/** + * Factory for collections, being aware of Commons Collection 3.x's extended + * collections as well as of JDK 1.5+ concurrent collections and backport-concurrent + * collections. Mainly for internal use within the framework. + * + *

    The goal of this class is to avoid runtime dependencies on JDK 1.5+ and + * Commons Collections 3.x, simply using the best collection implementation + * that is available at runtime. As of Spring 2.5, JDK 1.4 is required, + * so former adapter methods for JDK 1.3/1.4 always return the JDK 1.4 + * collections now. The adapter methods are still kept for supporting + * Spring-based applications/frameworks which were built to support JDK 1.3. + * + * @author Juergen Hoeller + * @since 1.1.1 + */ +public abstract class CollectionFactory { + + private static final Log logger = LogFactory.getLog(CollectionFactory.class); + + /** Whether the Commons Collections 3.x library is present on the classpath */ + private static final boolean commonsCollections3Available = + ClassUtils.isPresent("org.apache.commons.collections.map.CaseInsensitiveMap", + CollectionFactory.class.getClassLoader()); + + /** Whether the backport-concurrent library is present on the classpath */ + private static final boolean backportConcurrentAvailable = + ClassUtils.isPresent("edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap", + CollectionFactory.class.getClassLoader()); + + + private static final Set approximableCollectionTypes = new HashSet(10); + + private static final Set approximableMapTypes = new HashSet(6); + + static { + approximableCollectionTypes.add(Collection.class); + approximableCollectionTypes.add(List.class); + approximableCollectionTypes.add(Set.class); + approximableCollectionTypes.add(SortedSet.class); + approximableMapTypes.add(Map.class); + approximableMapTypes.add(SortedMap.class); + if (JdkVersion.isAtLeastJava16()) { + approximableCollectionTypes.add(NavigableSet.class); + approximableMapTypes.add(NavigableMap.class); + } + approximableCollectionTypes.add(ArrayList.class); + approximableCollectionTypes.add(LinkedList.class); + approximableCollectionTypes.add(HashSet.class); + approximableCollectionTypes.add(LinkedHashSet.class); + approximableCollectionTypes.add(TreeSet.class); + approximableMapTypes.add(HashMap.class); + approximableMapTypes.add(LinkedHashMap.class); + approximableMapTypes.add(TreeMap.class); + } + + /** + * Create a linked Set if possible: This implementation always + * creates a {@link java.util.LinkedHashSet}, since Spring 2.5 + * requires JDK 1.4 anyway. + * @param initialCapacity the initial capacity of the Set + * @return the new Set instance + * @deprecated as of Spring 2.5, for usage on JDK 1.4 or higher + */ + public static Set createLinkedSetIfPossible(int initialCapacity) { + return new LinkedHashSet(initialCapacity); + } + + /** + * Create a copy-on-write Set (allowing for synchronization-less iteration), + * requiring JDK >= 1.5 or the backport-concurrent library on the classpath. + * Prefers a JDK 1.5+ CopyOnWriteArraySet to its backport-concurrent equivalent. + * Throws an IllegalStateException if no copy-on-write Set is available. + * @return the new Set instance + * @throws IllegalStateException if no copy-on-write Set is available + * @see java.util.concurrent.ConcurrentHashMap + * @see edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap + */ + public static Set createCopyOnWriteSet() { + if (JdkVersion.isAtLeastJava15()) { + logger.trace("Creating [java.util.concurrent.CopyOnWriteArraySet]"); + return JdkConcurrentCollectionFactory.createCopyOnWriteArraySet(); + } + else if (backportConcurrentAvailable) { + logger.trace("Creating [edu.emory.mathcs.backport.java.util.concurrent.CopyOnWriteArraySet]"); + return BackportConcurrentCollectionFactory.createCopyOnWriteArraySet(); + } + else { + throw new IllegalStateException("Cannot create CopyOnWriteArraySet - " + + "neither JDK 1.5 nor backport-concurrent available on the classpath"); + } + } + + /** + * Create a linked Map if possible: This implementation always + * creates a {@link java.util.LinkedHashMap}, since Spring 2.5 + * requires JDK 1.4 anyway. + * @param initialCapacity the initial capacity of the Map + * @return the new Map instance + * @deprecated as of Spring 2.5, for usage on JDK 1.4 or higher + */ + public static Map createLinkedMapIfPossible(int initialCapacity) { + return new LinkedHashMap(initialCapacity); + } + + /** + * Create a linked case-insensitive Map if possible: if Commons Collections + * 3.x is available, a CaseInsensitiveMap with ListOrderedMap decorator will + * be created. Else, a JDK {@link java.util.LinkedHashMap} will be used. + * @param initialCapacity the initial capacity of the Map + * @return the new Map instance + * @see org.apache.commons.collections.map.CaseInsensitiveMap + * @see org.apache.commons.collections.map.ListOrderedMap + */ + public static Map createLinkedCaseInsensitiveMapIfPossible(int initialCapacity) { + if (commonsCollections3Available) { + logger.trace("Creating [org.apache.commons.collections.map.ListOrderedMap/CaseInsensitiveMap]"); + return CommonsCollectionFactory.createListOrderedCaseInsensitiveMap(initialCapacity); + } + else { + logger.debug("Falling back to [java.util.LinkedHashMap] for linked case-insensitive map"); + return new LinkedHashMap(initialCapacity); + } + } + + /** + * Create an identity Map if possible: This implementation always + * creates a {@link java.util.IdentityHashMap}, since Spring 2.5 + * requires JDK 1.4 anyway. + * @param initialCapacity the initial capacity of the Map + * @return the new Map instance + * @deprecated as of Spring 2.5, for usage on JDK 1.4 or higher + */ + public static Map createIdentityMapIfPossible(int initialCapacity) { + return new IdentityHashMap(initialCapacity); + } + + /** + * Create a concurrent Map if possible: that is, if running on JDK >= 1.5 + * or if the backport-concurrent library is available. Prefers a JDK 1.5+ + * ConcurrentHashMap to its backport-concurrent equivalent. Falls back + * to a plain synchronized HashMap if no concurrent Map is available. + * @param initialCapacity the initial capacity of the Map + * @return the new Map instance + * @see java.util.concurrent.ConcurrentHashMap + * @see edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap + */ + public static Map createConcurrentMapIfPossible(int initialCapacity) { + if (JdkVersion.isAtLeastJava15()) { + logger.trace("Creating [java.util.concurrent.ConcurrentHashMap]"); + return JdkConcurrentCollectionFactory.createConcurrentHashMap(initialCapacity); + } + else if (backportConcurrentAvailable) { + logger.trace("Creating [edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap]"); + return BackportConcurrentCollectionFactory.createConcurrentHashMap(initialCapacity); + } + else { + logger.debug("Falling back to plain synchronized [java.util.HashMap] for concurrent map"); + return Collections.synchronizedMap(new HashMap(initialCapacity)); + } + } + + /** + * Create a concurrent Map with a dedicated {@link ConcurrentMap} interface, + * requiring JDK >= 1.5 or the backport-concurrent library on the classpath. + * Prefers a JDK 1.5+ ConcurrentHashMap to its backport-concurrent equivalent. + * Throws an IllegalStateException if no concurrent Map is available. + * @param initialCapacity the initial capacity of the Map + * @return the new ConcurrentMap instance + * @throws IllegalStateException if no concurrent Map is available + * @see java.util.concurrent.ConcurrentHashMap + * @see edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap + */ + public static ConcurrentMap createConcurrentMap(int initialCapacity) { + if (JdkVersion.isAtLeastJava15()) { + logger.trace("Creating [java.util.concurrent.ConcurrentHashMap]"); + return new JdkConcurrentHashMap(initialCapacity); + } + else if (backportConcurrentAvailable) { + logger.trace("Creating [edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap]"); + return new BackportConcurrentHashMap(initialCapacity); + } + else { + throw new IllegalStateException("Cannot create ConcurrentHashMap - " + + "neither JDK 1.5 nor backport-concurrent available on the classpath"); + } + } + + + /** + * Determine whether the given collection type is an approximable type, + * i.e. a type that {@link #createApproximateCollection} can approximate. + * @param collectionType the collection type to check + * @return true if the type is approximable, + * false if it is not + */ + public static boolean isApproximableCollectionType(Class collectionType) { + return (collectionType != null && approximableCollectionTypes.contains(collectionType)); + } + + /** + * Create the most approximate collection for the given collection. + *

    Creates an ArrayList, TreeSet or linked Set for a List, SortedSet + * or Set, respectively. + * @param collection the original collection object + * @param initialCapacity the initial capacity + * @return the new collection instance + * @see java.util.ArrayList + * @see java.util.TreeSet + * @see java.util.LinkedHashSet + */ + public static Collection createApproximateCollection(Object collection, int initialCapacity) { + if (collection instanceof LinkedList) { + return new LinkedList(); + } + else if (collection instanceof List) { + return new ArrayList(initialCapacity); + } + else if (collection instanceof SortedSet) { + return new TreeSet(((SortedSet) collection).comparator()); + } + else { + return new LinkedHashSet(initialCapacity); + } + } + + /** + * Determine whether the given map type is an approximable type, + * i.e. a type that {@link #createApproximateMap} can approximate. + * @param mapType the map type to check + * @return true if the type is approximable, + * false if it is not + */ + public static boolean isApproximableMapType(Class mapType) { + return (mapType != null && approximableMapTypes.contains(mapType)); + } + + /** + * Create the most approximate map for the given map. + *

    Creates a TreeMap or linked Map for a SortedMap or Map, respectively. + * @param map the original map object + * @param initialCapacity the initial capacity + * @return the new collection instance + * @see java.util.TreeMap + * @see java.util.LinkedHashMap + */ + public static Map createApproximateMap(Object map, int initialCapacity) { + if (map instanceof SortedMap) { + return new TreeMap(((SortedMap) map).comparator()); + } + else { + return new LinkedHashMap(initialCapacity); + } + } + + + /** + * Actual creation of Commons Collections. + * In separate inner class to avoid runtime dependency on Commons Collections 3.x. + */ + private static abstract class CommonsCollectionFactory { + + private static Map createListOrderedCaseInsensitiveMap(int initialCapacity) { + // Commons Collections does not support initial capacity of 0. + return ListOrderedMap.decorate(new CaseInsensitiveMap(initialCapacity == 0 ? 1 : initialCapacity)); + } + } + + + /** + * Actual creation of JDK 1.5+ concurrent Collections. + * In separate inner class to avoid runtime dependency on JDK 1.5. + */ + private static abstract class JdkConcurrentCollectionFactory { + + private static Set createCopyOnWriteArraySet() { + return new CopyOnWriteArraySet(); + } + + private static Map createConcurrentHashMap(int initialCapacity) { + return new ConcurrentHashMap(initialCapacity); + } + } + + + /** + * Actual creation of backport-concurrent Collections. + * In separate inner class to avoid runtime dependency on the backport-concurrent library. + */ + private static abstract class BackportConcurrentCollectionFactory { + + private static Set createCopyOnWriteArraySet() { + return new edu.emory.mathcs.backport.java.util.concurrent.CopyOnWriteArraySet(); + } + + private static Map createConcurrentHashMap(int initialCapacity) { + return new edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap(initialCapacity); + } + } + + + /** + * ConcurrentMap adapter for the JDK ConcurrentHashMap class. + */ + private static class JdkConcurrentHashMap extends ConcurrentHashMap implements ConcurrentMap { + + public JdkConcurrentHashMap(int initialCapacity) { + super(initialCapacity); + } + } + + + /** + * ConcurrentMap adapter for the backport-concurrent ConcurrentHashMap class. + */ + private static class BackportConcurrentHashMap + extends edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap + implements ConcurrentMap { + + public BackportConcurrentHashMap(int initialCapacity) { + super(initialCapacity); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/core/ConcurrentMap.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/ConcurrentMap.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/ConcurrentMap.java 17 Aug 2012 15:14:26 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +import java.util.Map; + +/** + * Common interface for a concurrent Map, as exposed by + * {@link CollectionFactory#createConcurrentMap}. Mirrors + * {@link java.util.concurrent.ConcurrentMap}, allowing to be backed by a + * JDK ConcurrentHashMap as well as a backport-concurrent ConcurrentHashMap. + * + *

    Check out the {@link java.util.concurrent.ConcurrentMap ConcurrentMap javadoc} + * for details on the interface's methods. + * + * @author Juergen Hoeller + * @since 2.5 + */ +public interface ConcurrentMap extends Map { + + Object putIfAbsent(Object key, Object value); + + boolean remove(Object key, Object value); + + boolean replace(Object key, Object oldValue, Object newValue); + + Object replace(Object key, Object value); + +} Index: 3rdParty_sources/spring/org/springframework/core/ConfigurableObjectInputStream.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/ConfigurableObjectInputStream.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/ConfigurableObjectInputStream.java 17 Aug 2012 15:14:26 -0000 1.1 @@ -0,0 +1,126 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectStreamClass; +import java.lang.reflect.Proxy; + +import org.springframework.util.ClassUtils; + +/** + * Special ObjectInputStream subclass that resolves class names + * against a specific ClassLoader. Serves as base class for + * {@link org.springframework.remoting.rmi.CodebaseAwareObjectInputStream}. + * + * @author Juergen Hoeller + * @since 2.5.5 + */ +public class ConfigurableObjectInputStream extends ObjectInputStream { + + private final ClassLoader classLoader; + + + /** + * Create a new ConfigurableObjectInputStream for the given InputStream and ClassLoader. + * @param in the InputStream to read from + * @param classLoader the ClassLoader to use for loading local classes + * @see java.io.ObjectInputStream#ObjectInputStream(java.io.InputStream) + */ + public ConfigurableObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException { + super(in); + this.classLoader = classLoader; + } + + + protected Class resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException { + try { + if (this.classLoader != null) { + // Use the specified ClassLoader to resolve local classes. + return ClassUtils.forName(classDesc.getName(), this.classLoader); + } + else { + // Use the default ClassLoader... + return super.resolveClass(classDesc); + } + } + catch (ClassNotFoundException ex) { + return resolveFallbackIfPossible(classDesc.getName(), ex); + } + } + + protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { + if (this.classLoader != null) { + // Use the specified ClassLoader to resolve local proxy classes. + Class[] resolvedInterfaces = new Class[interfaces.length]; + for (int i = 0; i < interfaces.length; i++) { + try { + resolvedInterfaces[i] = ClassUtils.forName(interfaces[i], this.classLoader); + } + catch (ClassNotFoundException ex) { + resolvedInterfaces[i] = resolveFallbackIfPossible(interfaces[i], ex); + } + } + try { + return Proxy.getProxyClass(this.classLoader, resolvedInterfaces); + } + catch (IllegalArgumentException ex) { + throw new ClassNotFoundException(null, ex); + } + } + else { + // Use ObjectInputStream's default ClassLoader... + try { + return super.resolveProxyClass(interfaces); + } + catch (ClassNotFoundException ex) { + Class[] resolvedInterfaces = new Class[interfaces.length]; + for (int i = 0; i < interfaces.length; i++) { + resolvedInterfaces[i] = resolveFallbackIfPossible(interfaces[i], ex); + } + return Proxy.getProxyClass(getFallbackClassLoader(), resolvedInterfaces); + } + } + } + + + /** + * Resolve the given class name against a fallback class loader. + *

    The default implementation simply rethrows the original exception, + * since there is no fallback available. + * @param className the class name to resolve + * @param ex the original exception thrown when attempting to load the class + * @return the newly resolved class (never null) + */ + protected Class resolveFallbackIfPossible(String className, ClassNotFoundException ex) + throws IOException, ClassNotFoundException{ + + throw ex; + } + + /** + * Return the fallback ClassLoader to use when no ClassLoader was specified + * and ObjectInputStream's own default ClassLoader failed. + *

    The default implementation simply returns null. + */ + protected ClassLoader getFallbackClassLoader() throws IOException { + return null; + } + +} Index: 3rdParty_sources/spring/org/springframework/core/ConstantException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/ConstantException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/ConstantException.java 17 Aug 2012 15:14:26 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Copyright 2002-2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +/** + * Exception thrown when the {@link Constants} class is asked for + * an invalid constant name. + * + * @author Rod Johnson + * @since 28.04.2003 + * @see org.springframework.core.Constants + */ +public class ConstantException extends IllegalArgumentException { + + /** + * Thrown when an invalid constant name is requested. + * @param className name of the class containing the constant definitions + * @param field invalid constant name + * @param message description of the problem + */ + public ConstantException(String className, String field, String message) { + super("Field '" + field + "' " + message + " in class [" + className + "]"); + } + + /** + * Thrown when an invalid constant value is looked up. + * @param className name of the class containing the constant definitions + * @param namePrefix prefix of the searched constant names + * @param value the looked up constant value + */ + public ConstantException(String className, String namePrefix, Object value) { + super("No '" + namePrefix + "' field with value '" + value + "' found in class [" + className + "]"); + } + +} Index: 3rdParty_sources/spring/org/springframework/core/Constants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/Constants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/Constants.java 17 Aug 2012 15:14:26 -0000 1.1 @@ -0,0 +1,346 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import org.springframework.util.Assert; +import org.springframework.util.ReflectionUtils; + +/** + * This class can be used to parse other classes containing constant definitions + * in public static final members. The asXXXX methods of this class + * allow these constant values to be accessed via their string names. + * + *

    Consider class Foo containing public final static int CONSTANT1 = 66; + * An instance of this class wrapping Foo.class will return the constant value + * of 66 from its asNumber method given the argument "CONSTANT1". + * + *

    This class is ideal for use in PropertyEditors, enabling them to + * recognize the same names as the constants themselves, and freeing them + * from maintaining their own mapping. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 16.03.2003 + */ +public class Constants { + + /** The name of the introspected class */ + private final String className; + + /** Map from String field name to object value */ + private final Map fieldCache = new HashMap(); + + + /** + * Create a new Constants converter class wrapping the given class. + *

    All public static final variables will be exposed, whatever their type. + * @param clazz the class to analyze + * @throws IllegalArgumentException if the supplied clazz is null + */ + public Constants(Class clazz) { + Assert.notNull(clazz); + this.className = clazz.getName(); + Field[] fields = clazz.getFields(); + for (int i = 0; i < fields.length; i++) { + Field field = fields[i]; + if (ReflectionUtils.isPublicStaticFinal(field)) { + String name = field.getName(); + try { + Object value = field.get(null); + this.fieldCache.put(name, value); + } + catch (IllegalAccessException ex) { + // just leave this field and continue + } + } + } + } + + + /** + * Return the name of the analyzed class. + */ + public final String getClassName() { + return this.className; + } + + /** + * Return the number of constants exposed. + */ + public final int getSize() { + return this.fieldCache.size(); + } + + /** + * Exposes the field cache to subclasses: + * a Map from String field name to object value. + */ + protected final Map getFieldCache() { + return this.fieldCache; + } + + + /** + * Return a constant value cast to a Number. + * @param code the name of the field (never null) + * @return the Number value + * @see #asObject + * @throws ConstantException if the field name wasn't found + * or if the type wasn't compatible with Number + */ + public Number asNumber(String code) throws ConstantException { + Object obj = asObject(code); + if (!(obj instanceof Number)) { + throw new ConstantException(this.className, code, "not a Number"); + } + return (Number) obj; + } + + /** + * Return a constant value as a String. + * @param code the name of the field (never null) + * @return the String value + * Works even if it's not a string (invokes toString()). + * @see #asObject + * @throws ConstantException if the field name wasn't found + */ + public String asString(String code) throws ConstantException { + return asObject(code).toString(); + } + + /** + * Parse the given String (upper or lower case accepted) and return + * the appropriate value if it's the name of a constant field in the + * class that we're analysing. + * @param code the name of the field (never null) + * @return the Object value + * @throws ConstantException if there's no such field + */ + public Object asObject(String code) throws ConstantException { + Assert.notNull(code, "Code must not be null"); + String codeToUse = code.toUpperCase(Locale.ENGLISH); + Object val = this.fieldCache.get(codeToUse); + if (val == null) { + throw new ConstantException(this.className, codeToUse, "not found"); + } + return val; + } + + + /** + * Return all names of the given group of constants. + *

    Note that this method assumes that constants are named + * in accordance with the standard Java convention for constant + * values (i.e. all uppercase). The supplied namePrefix + * will be uppercased (in a locale-insensitive fashion) prior to + * the main logic of this method kicking in. + * @param namePrefix prefix of the constant names to search (may be null) + * @return the set of constant names + */ + public Set getNames(String namePrefix) { + String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : ""); + Set names = new HashSet(); + for (Iterator it = this.fieldCache.keySet().iterator(); it.hasNext();) { + String code = (String) it.next(); + if (code.startsWith(prefixToUse)) { + names.add(code); + } + } + return names; + } + + /** + * Return all names of the group of constants for the + * given bean property name. + * @param propertyName the name of the bean property + * @return the set of values + * @see #propertyToConstantNamePrefix + */ + public Set getNamesForProperty(String propertyName) { + return getNames(propertyToConstantNamePrefix(propertyName)); + } + + /** + * Return all names of the given group of constants. + *

    Note that this method assumes that constants are named + * in accordance with the standard Java convention for constant + * values (i.e. all uppercase). The supplied nameSuffix + * will be uppercased (in a locale-insensitive fashion) prior to + * the main logic of this method kicking in. + * @param nameSuffix suffix of the constant names to search (may be null) + * @return the set of constant names + */ + public Set getNamesForSuffix(String nameSuffix) { + String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : ""); + Set names = new HashSet(); + for (Iterator it = this.fieldCache.keySet().iterator(); it.hasNext();) { + String code = (String) it.next(); + if (code.endsWith(suffixToUse)) { + names.add(code); + } + } + return names; + } + + + /** + * Return all values of the given group of constants. + *

    Note that this method assumes that constants are named + * in accordance with the standard Java convention for constant + * values (i.e. all uppercase). The supplied namePrefix + * will be uppercased (in a locale-insensitive fashion) prior to + * the main logic of this method kicking in. + * @param namePrefix prefix of the constant names to search (may be null) + * @return the set of values + */ + public Set getValues(String namePrefix) { + String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : ""); + Set values = new HashSet(); + for (Iterator it = this.fieldCache.keySet().iterator(); it.hasNext();) { + String code = (String) it.next(); + if (code.startsWith(prefixToUse)) { + values.add(this.fieldCache.get(code)); + } + } + return values; + } + + /** + * Return all values of the group of constants for the + * given bean property name. + * @param propertyName the name of the bean property + * @return the set of values + * @see #propertyToConstantNamePrefix + */ + public Set getValuesForProperty(String propertyName) { + return getValues(propertyToConstantNamePrefix(propertyName)); + } + + /** + * Return all values of the given group of constants. + *

    Note that this method assumes that constants are named + * in accordance with the standard Java convention for constant + * values (i.e. all uppercase). The supplied nameSuffix + * will be uppercased (in a locale-insensitive fashion) prior to + * the main logic of this method kicking in. + * @param nameSuffix suffix of the constant names to search (may be null) + * @return the set of values + */ + public Set getValuesForSuffix(String nameSuffix) { + String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : ""); + Set values = new HashSet(); + for (Iterator it = this.fieldCache.keySet().iterator(); it.hasNext();) { + String code = (String) it.next(); + if (code.endsWith(suffixToUse)) { + values.add(this.fieldCache.get(code)); + } + } + return values; + } + + + /** + * Look up the given value within the given group of constants. + *

    Will return the first match. + * @param value constant value to look up + * @param namePrefix prefix of the constant names to search (may be null) + * @return the name of the constant field + * @throws ConstantException if the value wasn't found + */ + public String toCode(Object value, String namePrefix) throws ConstantException { + String prefixToUse = (namePrefix != null ? namePrefix.trim().toUpperCase(Locale.ENGLISH) : null); + for (Iterator it = this.fieldCache.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + String key = (String) entry.getKey(); + if (key.startsWith(prefixToUse) && entry.getValue().equals(value)) { + return key; + } + } + throw new ConstantException(this.className, prefixToUse, value); + } + + /** + * Look up the given value within the group of constants for + * the given bean property name. Will return the first match. + * @param value constant value to look up + * @param propertyName the name of the bean property + * @return the name of the constant field + * @throws ConstantException if the value wasn't found + * @see #propertyToConstantNamePrefix + */ + public String toCodeForProperty(Object value, String propertyName) throws ConstantException { + return toCode(value, propertyToConstantNamePrefix(propertyName)); + } + + /** + * Look up the given value within the given group of constants. + *

    Will return the first match. + * @param value constant value to look up + * @param nameSuffix suffix of the constant names to search (may be null) + * @return the name of the constant field + * @throws ConstantException if the value wasn't found + */ + public String toCodeForSuffix(Object value, String nameSuffix) throws ConstantException { + String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : null); + for (Iterator it = this.fieldCache.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = (Map.Entry) it.next(); + String key = (String) entry.getKey(); + if (key.endsWith(suffixToUse) && entry.getValue().equals(value)) { + return key; + } + } + throw new ConstantException(this.className, suffixToUse, value); + } + + + /** + * Convert the given bean property name to a constant name prefix. + *

    Uses a common naming idiom: turning all lower case characters to + * upper case, and prepending upper case characters with an underscore. + *

    Example: "imageSize" -> "IMAGE_SIZE"
    + * Example: "imagesize" -> "IMAGESIZE".
    + * Example: "ImageSize" -> "_IMAGE_SIZE".
    + * Example: "IMAGESIZE" -> "_I_M_A_G_E_S_I_Z_E" + * @param propertyName the name of the bean property + * @return the corresponding constant name prefix + * @see #getValuesForProperty + * @see #toCodeForProperty + */ + public String propertyToConstantNamePrefix(String propertyName) { + StringBuffer parsedPrefix = new StringBuffer(); + for(int i = 0; i < propertyName.length(); i++) { + char c = propertyName.charAt(i); + if (Character.isUpperCase(c)) { + parsedPrefix.append("_"); + parsedPrefix.append(c); + } + else { + parsedPrefix.append(Character.toUpperCase(c)); + } + } + return parsedPrefix.toString(); + } + +} Index: 3rdParty_sources/spring/org/springframework/core/ControlFlow.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/ControlFlow.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/ControlFlow.java 17 Aug 2012 15:14:27 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +/** + * Interface to be implemented by objects that can return information about + * the current call stack. Useful in AOP (as in AspectJ cflow concept) + * but not AOP-specific. + * + * @author Rod Johnson + * @since 02.02.2004 + */ +public interface ControlFlow { + + /** + * Detect whether we're under the given class, + * according to the current stack trace. + * @param clazz the clazz to look for + */ + boolean under(Class clazz); + + /** + * Detect whether we're under the given class and method, + * according to the current stack trace. + * @param clazz the clazz to look for + * @param methodName the name of the method to look for + */ + boolean under(Class clazz, String methodName); + + /** + * Detect whether the current stack trace contains the given token. + * @param token the token to look for + */ + boolean underToken(String token); + +} Index: 3rdParty_sources/spring/org/springframework/core/ControlFlowFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/ControlFlowFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/ControlFlowFactory.java 17 Aug 2012 15:14:27 -0000 1.1 @@ -0,0 +1,118 @@ +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import org.springframework.util.Assert; + +/** + * Static factory to conceal the automatic choice of the ControlFlow + * implementation class. + * + *

    This implementation always uses the efficient Java 1.4 StackTraceElement + * mechanism for analyzing control flows. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @since 02.02.2004 + */ +public abstract class ControlFlowFactory { + + /** + * Return an appropriate {@link ControlFlow} instance. + */ + public static ControlFlow createControlFlow() { + return new Jdk14ControlFlow(); + } + + + /** + * Utilities for cflow-style pointcuts. Note that such pointcuts are + * 5-10 times more expensive to evaluate than other pointcuts, as they require + * analysis of the stack trace (through constructing a new throwable). + * However, they are useful in some cases. + *

    This implementation uses the StackTraceElement class introduced in Java 1.4. + * @see java.lang.StackTraceElement + */ + static class Jdk14ControlFlow implements ControlFlow { + + private StackTraceElement[] stack; + + public Jdk14ControlFlow() { + this.stack = new Throwable().getStackTrace(); + } + + /** + * Searches for class name match in a StackTraceElement. + */ + public boolean under(Class clazz) { + Assert.notNull(clazz, "Class must not be null"); + String className = clazz.getName(); + for (int i = 0; i < stack.length; i++) { + if (this.stack[i].getClassName().equals(className)) { + return true; + } + } + return false; + } + + /** + * Searches for class name match plus method name match + * in a StackTraceElement. + */ + public boolean under(Class clazz, String methodName) { + Assert.notNull(clazz, "Class must not be null"); + Assert.notNull(methodName, "Method name must not be null"); + String className = clazz.getName(); + for (int i = 0; i < this.stack.length; i++) { + if (this.stack[i].getClassName().equals(className) && + this.stack[i].getMethodName().equals(methodName)) { + return true; + } + } + return false; + } + + /** + * Leave it up to the caller to decide what matches. + * Caller must understand stack trace format, so there's less abstraction. + */ + public boolean underToken(String token) { + if (token == null) { + return false; + } + StringWriter sw = new StringWriter(); + new Throwable().printStackTrace(new PrintWriter(sw)); + String stackTrace = sw.toString(); + return stackTrace.indexOf(token) != -1; + } + + public String toString() { + StringBuffer sb = new StringBuffer("Jdk14ControlFlow: "); + for (int i = 0; i < this.stack.length; i++) { + if (i > 0) { + sb.append("\n\t@"); + } + sb.append(this.stack[i]); + } + return sb.toString(); + } + } + +} Index: 3rdParty_sources/spring/org/springframework/core/Conventions.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/Conventions.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/Conventions.java 17 Aug 2012 15:14:26 -0000 1.1 @@ -0,0 +1,307 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +import java.io.Externalizable; +import java.io.Serializable; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; + +/** + * Provides methods to support various naming and other conventions used + * throughout the framework. Mainly for internal use within the framework. + * + * @author Rob Harrop + * @author Juergen Hoeller + * @since 2.0 + */ +public abstract class Conventions { + + /** + * Suffix added to names when using arrays. + */ + private static final String PLURAL_SUFFIX = "List"; + + + /** + * Set of interfaces that are supposed to be ignored + * when searching for the 'primary' interface of a proxy. + */ + private static final Set ignoredInterfaces = new HashSet(); + + static { + ignoredInterfaces.add(Serializable.class); + ignoredInterfaces.add(Externalizable.class); + ignoredInterfaces.add(Cloneable.class); + ignoredInterfaces.add(Comparable.class); + } + + + /** + * Determine the conventional variable name for the supplied + * Object based on its concrete type. The convention + * used is to return the uncapitalized short name of the Class, + * according to JavaBeans property naming rules: So, + * com.myapp.Product becomes product; + * com.myapp.MyProduct becomes myProduct; + * com.myapp.UKProduct becomes UKProduct. + *

    For arrays, we use the pluralized version of the array component type. + * For Collections we attempt to 'peek ahead' in the + * Collection to determine the component type and + * return the pluralized version of that component type. + * @param value the value to generate a variable name for + * @return the generated variable name + */ + public static String getVariableName(Object value) { + Assert.notNull(value, "Value must not be null"); + Class valueClass = null; + boolean pluralize = false; + + if (value.getClass().isArray()) { + valueClass = value.getClass().getComponentType(); + pluralize = true; + } + else if (value instanceof Collection) { + Collection collection = (Collection) value; + if (collection.isEmpty()) { + throw new IllegalArgumentException("Cannot generate variable name for an empty Collection"); + } + Object valueToCheck = peekAhead(collection); + valueClass = getClassForValue(valueToCheck); + pluralize = true; + } + else { + valueClass = getClassForValue(value); + } + + String name = ClassUtils.getShortNameAsProperty(valueClass); + return (pluralize ? pluralize(name) : name); + } + + /** + * Determine the conventional variable name for the supplied parameter, + * taking the generic collection type (if any) into account. + * @param parameter the method or constructor parameter to generate a variable name for + * @return the generated variable name + */ + public static String getVariableNameForParameter(MethodParameter parameter) { + Assert.notNull(parameter, "MethodParameter must not be null"); + Class valueClass = null; + boolean pluralize = false; + + if (parameter.getParameterType().isArray()) { + valueClass = parameter.getParameterType().getComponentType(); + pluralize = true; + } + else if (Collection.class.isAssignableFrom(parameter.getParameterType())) { + if (JdkVersion.isAtLeastJava15()) { + valueClass = GenericCollectionTypeResolver.getCollectionParameterType(parameter); + } + if (valueClass == null) { + throw new IllegalArgumentException("Cannot generate variable name for non-typed Collection parameter type"); + } + pluralize = true; + } + else { + valueClass = parameter.getParameterType(); + } + + String name = ClassUtils.getShortNameAsProperty(valueClass); + return (pluralize ? pluralize(name) : name); + } + + /** + * Determine the conventional variable name for the return type of the supplied method, + * taking the generic collection type (if any) into account. + * @param method the method to generate a variable name for + * @return the generated variable name + */ + public static String getVariableNameForReturnType(Method method) { + return getVariableNameForReturnType(method, method.getReturnType(), null); + } + + /** + * Determine the conventional variable name for the return type of the supplied method, + * taking the generic collection type (if any) into account, falling back to the + * given return value if the method declaration is not specific enough (i.e. in case of + * the return type being declared as Object or as untyped collection). + * @param method the method to generate a variable name for + * @param value the return value (may be null if not available) + * @return the generated variable name + */ + public static String getVariableNameForReturnType(Method method, Object value) { + return getVariableNameForReturnType(method, method.getReturnType(), value); + } + + /** + * Determine the conventional variable name for the return type of the supplied method, + * taking the generic collection type (if any) into account, falling back to the + * given return value if the method declaration is not specific enough (i.e. in case of + * the return type being declared as Object or as untyped collection). + * @param method the method to generate a variable name for + * @param resolvedType the resolved return type of the method + * @param value the return value (may be null if not available) + * @return the generated variable name + */ + public static String getVariableNameForReturnType(Method method, Class resolvedType, Object value) { + Assert.notNull(method, "Method must not be null"); + + if (Object.class.equals(resolvedType)) { + if (value == null) { + throw new IllegalArgumentException("Cannot generate variable name for an Object return type with null value"); + } + return getVariableName(value); + } + + Class valueClass = null; + boolean pluralize = false; + + if (resolvedType.isArray()) { + valueClass = resolvedType.getComponentType(); + pluralize = true; + } + else if (Collection.class.isAssignableFrom(resolvedType)) { + if (JdkVersion.isAtLeastJava15()) { + valueClass = GenericCollectionTypeResolver.getCollectionReturnType(method); + } + if (valueClass == null) { + if (!(value instanceof Collection)) { + throw new IllegalArgumentException( + "Cannot generate variable name for non-typed Collection return type and a non-Collection value"); + } + Collection collection = (Collection) value; + if (collection.isEmpty()) { + throw new IllegalArgumentException( + "Cannot generate variable name for non-typed Collection return type and an empty Collection value"); + } + Object valueToCheck = peekAhead(collection); + valueClass = getClassForValue(valueToCheck); + } + pluralize = true; + } + else { + valueClass = resolvedType; + } + + String name = ClassUtils.getShortNameAsProperty(valueClass); + return (pluralize ? pluralize(name) : name); + } + + /** + * Convert Strings in attribute name format (lowercase, hyphens separating words) + * into property name format (camel-cased). For example, transaction-manager is + * converted into transactionManager. + */ + public static String attributeNameToPropertyName(String attributeName) { + Assert.notNull(attributeName, "'attributeName' must not be null"); + if (attributeName.indexOf("-") == -1) { + return attributeName; + } + char[] chars = attributeName.toCharArray(); + char[] result = new char[chars.length -1]; // not completely accurate but good guess + int currPos = 0; + boolean upperCaseNext = false; + for (int i = 0; i < chars.length; i++) { + char c = chars[i]; + if (c == '-') { + upperCaseNext = true; + } + else if (upperCaseNext) { + result[currPos++] = Character.toUpperCase(c); + upperCaseNext = false; + } + else { + result[currPos++] = c; + } + } + return new String(result, 0, currPos); + } + + /** + * Return an attribute name qualified by the supplied enclosing {@link Class}. For example, + * the attribute name 'foo' qualified by {@link Class} 'com.myapp.SomeClass' + * would be 'com.myapp.SomeClass.foo' + */ + public static String getQualifiedAttributeName(Class enclosingClass, String attributeName) { + Assert.notNull(enclosingClass, "'enclosingClass' must not be null"); + Assert.notNull(attributeName, "'attributeName' must not be null"); + return enclosingClass.getName() + "." + attributeName; + } + + + /** + * Determines the class to use for naming a variable that contains + * the given value. + *

    Will return the class of the given value, except when + * encountering a JDK proxy, in which case it will determine + * the 'primary' interface implemented by that proxy. + * @param value the value to check + * @return the class to use for naming a variable + */ + private static Class getClassForValue(Object value) { + Class valueClass = value.getClass(); + if (Proxy.isProxyClass(valueClass)) { + Class[] ifcs = valueClass.getInterfaces(); + for (int i = 0; i < ifcs.length; i++) { + Class ifc = ifcs[i]; + if (!ignoredInterfaces.contains(ifc)) { + return ifc; + } + } + } + else if (valueClass.getName().lastIndexOf('$') != -1 && valueClass.getDeclaringClass() == null) { + // '$' in the class name but no inner class - + // assuming it's a special subclass (e.g. by OpenJPA) + valueClass = valueClass.getSuperclass(); + } + return valueClass; + } + + /** + * Pluralize the given name. + */ + private static String pluralize(String name) { + return name + PLURAL_SUFFIX; + } + + /** + * Retrieves the Class of an element in the Collection. + * The exact element for which the Class is retreived will depend + * on the concrete Collection implementation. + */ + private static Object peekAhead(Collection collection) { + Iterator it = collection.iterator(); + if (!it.hasNext()) { + throw new IllegalStateException( + "Unable to peek ahead in non-empty collection - no element found"); + } + Object value = it.next(); + if (value == null) { + throw new IllegalStateException( + "Unable to peek ahead in non-empty collection - only null element found"); + } + return value; + } + +} Index: 3rdParty_sources/spring/org/springframework/core/DecoratingClassLoader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/DecoratingClassLoader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/DecoratingClassLoader.java 17 Aug 2012 15:14:27 -0000 1.1 @@ -0,0 +1,108 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.springframework.util.Assert; + +/** + * Base class for decorating ClassLoaders such as {@link OverridingClassLoader} + * and {@link org.springframework.instrument.classloading.ShadowingClassLoader}, + * providing common handling of excluded packages and classes. + * + * @author Juergen Hoeller + * @author Rod Johnson + * @since 2.5.2 + */ +public abstract class DecoratingClassLoader extends ClassLoader { + + private final Set excludedPackages = new HashSet(); + + private final Set excludedClasses = new HashSet(); + + private final Object exclusionMonitor = new Object(); + + + /** + * Create a new DecoratingClassLoader with no parent ClassLoader. + */ + public DecoratingClassLoader() { + } + + /** + * Create a new DecoratingClassLoader using the given parent ClassLoader + * for delegation. + */ + public DecoratingClassLoader(ClassLoader parent) { + super(parent); + } + + + /** + * Add a package name to exclude from decoration (e.g. overriding). + *

    Any class whose fully-qualified name starts with the name registered + * here will be handled by the parent ClassLoader in the usual fashion. + * @param packageName the package name to exclude + */ + public void excludePackage(String packageName) { + Assert.notNull(packageName, "Package name must not be null"); + synchronized (this.exclusionMonitor) { + this.excludedPackages.add(packageName); + } + } + + /** + * Add a class name to exclude from decoration (e.g. overriding). + *

    Any class name registered here will be handled by the parent + * ClassLoader in the usual fashion. + * @param className the class name to exclude + */ + public void excludeClass(String className) { + Assert.notNull(className, "Class name must not be null"); + synchronized (this.exclusionMonitor) { + this.excludedClasses.add(className); + } + } + + /** + * Determine whether the specified class is excluded from decoration + * by this class loader. + *

    The default implementation checks against excluded packages and classes. + * @param className the class name to check + * @return whether the specified class is eligible + * @see #excludePackage + * @see #excludeClass + */ + protected boolean isExcluded(String className) { + synchronized (this.exclusionMonitor) { + if (this.excludedClasses.contains(className)) { + return true; + } + for (Iterator it = this.excludedPackages.iterator(); it.hasNext();) { + String packageName = (String) it.next(); + if (className.startsWith(packageName)) { + return true; + } + } + } + return false; + } + +} Index: 3rdParty_sources/spring/org/springframework/core/ErrorCoded.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/ErrorCoded.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/ErrorCoded.java 17 Aug 2012 15:14:26 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Copyright 2002-2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +/** + * Interface that can be implemented by exceptions etc that are error coded. + * The error code is a String, rather than a number, so it can be given + * user-readable values, such as "object.failureDescription". + * + *

    An error code can be resolved by a MessageSource, for example. + * + * @author Rod Johnson + * @see org.springframework.context.MessageSource + */ +public interface ErrorCoded { + + /** + * Return the error code associated with this failure. + * The GUI can render this any way it pleases, allowing for localization etc. + * @return a String error code associated with this failure, + * or null if not error-coded + */ + String getErrorCode(); + +} Index: 3rdParty_sources/spring/org/springframework/core/GenericCollectionTypeResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/GenericCollectionTypeResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/GenericCollectionTypeResolver.java 17 Aug 2012 15:14:27 -0000 1.1 @@ -0,0 +1,426 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; +import java.util.Collection; +import java.util.Map; + +/** + * Helper class for determining element types of collections and maps. + * + *

    Mainly intended for usage within the framework, determining the + * target type of values to be added to a collection or map + * (to be able to attempt type conversion if appropriate). + * + *

    Only usable on Java 5. Use an appropriate {@link JdkVersion} check + * before calling this class, if a fallback for JDK 1.4 is desirable. + * + * @author Juergen Hoeller + * @since 2.0 + * @see org.springframework.beans.BeanWrapper + */ +public abstract class GenericCollectionTypeResolver { + + /** + * Determine the generic element type of the given Collection class + * (if it declares one through a generic superclass or generic interface). + * @param collectionClass the collection class to introspect + * @return the generic type, or null if none + */ + public static Class getCollectionType(Class collectionClass) { + return extractTypeFromClass(collectionClass, Collection.class, 0); + } + + /** + * Determine the generic key type of the given Map class + * (if it declares one through a generic superclass or generic interface). + * @param mapClass the map class to introspect + * @return the generic type, or null if none + */ + public static Class getMapKeyType(Class mapClass) { + return extractTypeFromClass(mapClass, Map.class, 0); + } + + /** + * Determine the generic value type of the given Map class + * (if it declares one through a generic superclass or generic interface). + * @param mapClass the map class to introspect + * @return the generic type, or null if none + */ + public static Class getMapValueType(Class mapClass) { + return extractTypeFromClass(mapClass, Map.class, 1); + } + + /** + * Determine the generic element type of the given Collection field. + * @param collectionField the collection field to introspect + * @return the generic type, or null if none + */ + public static Class getCollectionFieldType(Field collectionField) { + return getGenericFieldType(collectionField, Collection.class, 0, 1); + } + + /** + * Determine the generic element type of the given Collection field. + * @param collectionField the collection field to introspect + * @param nestingLevel the nesting level of the target type + * (typically 1; e.g. in case of a List of Lists, 1 would indicate the + * nested List, whereas 2 would indicate the element of the nested List) + * @return the generic type, or null if none + */ + public static Class getCollectionFieldType(Field collectionField, int nestingLevel) { + return getGenericFieldType(collectionField, Collection.class, 0, nestingLevel); + } + + /** + * Determine the generic key type of the given Map field. + * @param mapField the map field to introspect + * @return the generic type, or null if none + */ + public static Class getMapKeyFieldType(Field mapField) { + return getGenericFieldType(mapField, Map.class, 0, 1); + } + + /** + * Determine the generic key type of the given Map field. + * @param mapField the map field to introspect + * @param nestingLevel the nesting level of the target type + * (typically 1; e.g. in case of a List of Lists, 1 would indicate the + * nested List, whereas 2 would indicate the element of the nested List) + * @return the generic type, or null if none + */ + public static Class getMapKeyFieldType(Field mapField, int nestingLevel) { + return getGenericFieldType(mapField, Map.class, 0, nestingLevel); + } + + /** + * Determine the generic value type of the given Map field. + * @param mapField the map field to introspect + * @return the generic type, or null if none + */ + public static Class getMapValueFieldType(Field mapField) { + return getGenericFieldType(mapField, Map.class, 1, 1); + } + + /** + * Determine the generic value type of the given Map field. + * @param mapField the map field to introspect + * @param nestingLevel the nesting level of the target type + * (typically 1; e.g. in case of a List of Lists, 1 would indicate the + * nested List, whereas 2 would indicate the element of the nested List) + * @return the generic type, or null if none + */ + public static Class getMapValueFieldType(Field mapField, int nestingLevel) { + return getGenericFieldType(mapField, Map.class, 1, nestingLevel); + } + + /** + * Determine the generic element type of the given Collection parameter. + * @param methodParam the method parameter specification + * @return the generic type, or null if none + */ + public static Class getCollectionParameterType(MethodParameter methodParam) { + return getGenericParameterType(methodParam, Collection.class, 0); + } + + /** + * Determine the generic key type of the given Map parameter. + * @param methodParam the method parameter specification + * @return the generic type, or null if none + */ + public static Class getMapKeyParameterType(MethodParameter methodParam) { + return getGenericParameterType(methodParam, Map.class, 0); + } + + /** + * Determine the generic value type of the given Map parameter. + * @param methodParam the method parameter specification + * @return the generic type, or null if none + */ + public static Class getMapValueParameterType(MethodParameter methodParam) { + return getGenericParameterType(methodParam, Map.class, 1); + } + + /** + * Determine the generic element type of the given Collection return type. + * @param method the method to check the return type for + * @return the generic type, or null if none + */ + public static Class getCollectionReturnType(Method method) { + return getGenericReturnType(method, Collection.class, 0, 1); + } + + /** + * Determine the generic element type of the given Collection return type. + *

    If the specified nesting level is higher than 1, the element type of + * a nested Collection/Map will be analyzed. + * @param method the method to check the return type for + * @param nestingLevel the nesting level of the target type + * (typically 1; e.g. in case of a List of Lists, 1 would indicate the + * nested List, whereas 2 would indicate the element of the nested List) + * @return the generic type, or null if none + */ + public static Class getCollectionReturnType(Method method, int nestingLevel) { + return getGenericReturnType(method, Collection.class, 0, nestingLevel); + } + + /** + * Determine the generic key type of the given Map return type. + * @param method the method to check the return type for + * @return the generic type, or null if none + */ + public static Class getMapKeyReturnType(Method method) { + return getGenericReturnType(method, Map.class, 0, 1); + } + + /** + * Determine the generic key type of the given Map return type. + * @param method the method to check the return type for + * @param nestingLevel the nesting level of the target type + * (typically 1; e.g. in case of a List of Lists, 1 would indicate the + * nested List, whereas 2 would indicate the element of the nested List) + * @return the generic type, or null if none + */ + public static Class getMapKeyReturnType(Method method, int nestingLevel) { + return getGenericReturnType(method, Map.class, 0, nestingLevel); + } + + /** + * Determine the generic value type of the given Map return type. + * @param method the method to check the return type for + * @return the generic type, or null if none + */ + public static Class getMapValueReturnType(Method method) { + return getGenericReturnType(method, Map.class, 1, 1); + } + + /** + * Determine the generic value type of the given Map return type. + * @param method the method to check the return type for + * @param nestingLevel the nesting level of the target type + * (typically 1; e.g. in case of a List of Lists, 1 would indicate the + * nested List, whereas 2 would indicate the element of the nested List) + * @return the generic type, or null if none + */ + public static Class getMapValueReturnType(Method method, int nestingLevel) { + return getGenericReturnType(method, Map.class, 1, nestingLevel); + } + + + /** + * Extract the generic parameter type from the given method or constructor. + * @param methodParam the method parameter specification + * @param source the source class/interface defining the generic parameter types + * @param typeIndex the index of the type (e.g. 0 for Collections, + * 0 for Map keys, 1 for Map values) + * @return the generic type, or null if none + */ + private static Class getGenericParameterType(MethodParameter methodParam, Class source, int typeIndex) { + return extractType(methodParam, GenericTypeResolver.getTargetType(methodParam), + source, typeIndex, methodParam.getNestingLevel(), 1); + } + + /** + * Extract the generic type from the given field. + * @param field the field to check the type for + * @param source the source class/interface defining the generic parameter types + * @param typeIndex the index of the type (e.g. 0 for Collections, + * 0 for Map keys, 1 for Map values) + * @param nestingLevel the nesting level of the target type + * @return the generic type, or null if none + */ + private static Class getGenericFieldType(Field field, Class source, int typeIndex, int nestingLevel) { + return extractType(null, field.getGenericType(), source, typeIndex, nestingLevel, 1); + } + + /** + * Extract the generic return type from the given method. + * @param method the method to check the return type for + * @param source the source class/interface defining the generic parameter types + * @param typeIndex the index of the type (e.g. 0 for Collections, + * 0 for Map keys, 1 for Map values) + * @param nestingLevel the nesting level of the target type + * @return the generic type, or null if none + */ + private static Class getGenericReturnType(Method method, Class source, int typeIndex, int nestingLevel) { + return extractType(null, method.getGenericReturnType(), source, typeIndex, nestingLevel, 1); + } + + /** + * Extract the generic type from the given Type object. + * @param methodParam the method parameter specification + * @param type the Type to check + * @param source the source collection/map Class that we check + * @param typeIndex the index of the actual type argument + * @param nestingLevel the nesting level of the target type + * @param currentLevel the current nested level + * @return the generic type as Class, or null if none + */ + private static Class extractType( + MethodParameter methodParam, Type type, Class source, int typeIndex, int nestingLevel, int currentLevel) { + + Type resolvedType = type; + if (type instanceof TypeVariable && methodParam != null && methodParam.typeVariableMap != null) { + Type mappedType = (Type) methodParam.typeVariableMap.get(type); + if (mappedType != null) { + resolvedType = mappedType; + } + } + if (resolvedType instanceof ParameterizedType) { + return extractTypeFromParameterizedType( + methodParam, (ParameterizedType) resolvedType, source, typeIndex, nestingLevel, currentLevel); + } + else if (resolvedType instanceof Class) { + return extractTypeFromClass(methodParam, (Class) resolvedType, source, typeIndex, nestingLevel, currentLevel); + } + else { + return null; + } + } + + /** + * Extract the generic type from the given ParameterizedType object. + * @param methodParam the method parameter specification + * @param ptype the ParameterizedType to check + * @param source the expected raw source type (can be null) + * @param typeIndex the index of the actual type argument + * @param nestingLevel the nesting level of the target type + * @param currentLevel the current nested level + * @return the generic type as Class, or null if none + */ + private static Class extractTypeFromParameterizedType(MethodParameter methodParam, + ParameterizedType ptype, Class source, int typeIndex, int nestingLevel, int currentLevel) { + + if (!(ptype.getRawType() instanceof Class)) { + return null; + } + Class rawType = (Class) ptype.getRawType(); + Type[] paramTypes = ptype.getActualTypeArguments(); + if (nestingLevel - currentLevel > 0) { + int nextLevel = currentLevel + 1; + Integer currentTypeIndex = (methodParam != null ? methodParam.getTypeIndexForLevel(nextLevel) : null); + // Default is last parameter type: Collection element or Map value. + int indexToUse = (currentTypeIndex != null ? currentTypeIndex.intValue() : paramTypes.length - 1); + Type paramType = paramTypes[indexToUse]; + return extractType(methodParam, paramType, source, typeIndex, nestingLevel, nextLevel); + } + if (source != null && !source.isAssignableFrom(rawType)) { + return null; + } + Class fromSuperclassOrInterface = + extractTypeFromClass(methodParam, rawType, source, typeIndex, nestingLevel, currentLevel); + if (fromSuperclassOrInterface != null) { + return fromSuperclassOrInterface; + } + if (paramTypes == null || typeIndex >= paramTypes.length) { + return null; + } + Type paramType = paramTypes[typeIndex]; + if (paramType instanceof TypeVariable && methodParam != null && methodParam.typeVariableMap != null) { + Type mappedType = (Type) methodParam.typeVariableMap.get(paramType); + if (mappedType != null) { + paramType = mappedType; + } + } + if (paramType instanceof WildcardType) { + Type[] lowerBounds = ((WildcardType) paramType).getLowerBounds(); + if (lowerBounds != null && lowerBounds.length > 0) { + paramType = lowerBounds[0]; + } + } + if (paramType instanceof ParameterizedType) { + paramType = ((ParameterizedType) paramType).getRawType(); + } + if (paramType instanceof GenericArrayType) { + // A generic array type... Let's turn it into a straight array type if possible. + Type compType = ((GenericArrayType) paramType).getGenericComponentType(); + if (compType instanceof Class) { + return Array.newInstance((Class) compType, 0).getClass(); + } + } + else if (paramType instanceof Class) { + // We finally got a straight Class... + return (Class) paramType; + } + return null; + } + + /** + * Extract the generic type from the given Class object. + * @param clazz the Class to check + * @param source the expected raw source type (can be null) + * @param typeIndex the index of the actual type argument + * @return the generic type as Class, or null if none + */ + private static Class extractTypeFromClass(Class clazz, Class source, int typeIndex) { + return extractTypeFromClass(null, clazz, source, typeIndex, 1, 1); + } + + /** + * Extract the generic type from the given Class object. + * @param methodParam the method parameter specification + * @param clazz the Class to check + * @param source the expected raw source type (can be null) + * @param typeIndex the index of the actual type argument + * @param nestingLevel the nesting level of the target type + * @param currentLevel the current nested level + * @return the generic type as Class, or null if none + */ + private static Class extractTypeFromClass( + MethodParameter methodParam, Class clazz, Class source, int typeIndex, int nestingLevel, int currentLevel) { + + if (clazz.getName().startsWith("java.util.")) { + return null; + } + if (clazz.getSuperclass() != null && isIntrospectionCandidate(clazz.getSuperclass())) { + return extractType(methodParam, clazz.getGenericSuperclass(), source, typeIndex, nestingLevel, currentLevel); + } + Type[] ifcs = clazz.getGenericInterfaces(); + if (ifcs != null) { + for (int i = 0; i < ifcs.length; i++) { + Type ifc = ifcs[i]; + Type rawType = ifc; + if (ifc instanceof ParameterizedType) { + rawType = ((ParameterizedType) ifc).getRawType(); + } + if (rawType instanceof Class && isIntrospectionCandidate((Class) rawType)) { + return extractType(methodParam, ifc, source, typeIndex, nestingLevel, currentLevel); + } + } + } + return null; + } + + /** + * Determine whether the given class is a potential candidate + * that defines generic collection or map types. + * @param clazz the class to check + * @return whether the given class is assignable to Collection or Map + */ + private static boolean isIntrospectionCandidate(Class clazz) { + return (Collection.class.isAssignableFrom(clazz) || Map.class.isAssignableFrom(clazz)); + } + +} Index: 3rdParty_sources/spring/org/springframework/core/GenericTypeResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/spring/org/springframework/core/GenericTypeResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/spring/org/springframework/core/GenericTypeResolver.java 17 Aug 2012 15:14:26 -0000 1.1 @@ -0,0 +1,262 @@ +/* + * Copyright 2002-2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core; + +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.WeakHashMap; + +import org.springframework.util.Assert; + +/** + * Helper class for resolving generic types against type variables. + * + *

    Mainly intended for usage within the framework, resolving method + * parameter types even when they are declared generically. + * + *

    Only usable on Java 5. Use an appropriate JdkVersion check before + * calling this class, if a fallback for JDK 1.4 is desirable. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @since 2.5.2 + * @see GenericCollectionTypeResolver + * @see JdkVersion + */ +public abstract class GenericTypeResolver { + + /** Cache from Class to TypeVariable Map */ + private static final Map typeVariableCache = Collections.synchronizedMap(new WeakHashMap()); + + + /** + * Determine the target type for the given parameter specification. + * @param methodParam the method parameter specification + * @return the corresponding generic parameter type + */ + public static Type getTargetType(MethodParameter methodParam) { + Assert.notNull(methodParam, "MethodParameter must not be null"); + if (methodParam.getConstructor() != null) { + return methodParam.getConstructor().getGenericParameterTypes()[methodParam.getParameterIndex()]; + } + else { + if (methodParam.getParameterIndex() >= 0) { + return methodParam.getMethod().getGenericParameterTypes()[methodParam.getParameterIndex()]; + } + else { + return methodParam.getMethod().getGenericReturnType(); + } + } + } + + /** + * Determine the target type for the given generic parameter type. + * @param methodParam the method parameter specification + * @param clazz the class to resolve type variables against + * @return the corresponding generic parameter or return type + */ + public static Class resolveParameterType(MethodParameter methodParam, Class clazz) { + Type genericType = getTargetType(methodParam); + Assert.notNull(clazz, "Class must not be null"); + Map typeVariableMap = getTypeVariableMap(clazz); + Type rawType = getRawType(genericType, typeVariableMap); + Class result = (rawType instanceof Class ? (Class) rawType : methodParam.getParameterType()); + methodParam.setParameterType(result); + methodParam.typeVariableMap = typeVariableMap; + return result; + } + + /** + * Determine the target type for the generic return type of the given method. + * @param method the method to introspect + * @param clazz the class to resolve type variables against + * @return the corresponding generic parameter or return type + */ + public static Class resolveReturnType(Method method, Class clazz) { + Assert.notNull(method, "Method must not be null"); + Type genericType = method.getGenericReturnType(); + Assert.notNull(clazz, "Class must not be null"); + Map typeVariableMap = getTypeVariableMap(clazz); + Type rawType = getRawType(genericType, typeVariableMap); + return (rawType instanceof Class ? (Class) rawType : method.getReturnType()); + } + + + /** + * Resolve the specified generic type against the given TypeVariable map. + * @param genericType the generic type to resolve + * @param typeVariableMap the TypeVariable Map to resolved against + * @return the type if it resolves to a Class, or Object.class otherwise + */ + static Class resolveType(Type genericType, Map typeVariableMap) { + Type rawType = getRawType(genericType, typeVariableMap); + return (rawType instanceof Class ? (Class) rawType : Object.class); + } + + /** + * Determine the raw type for the given generic parameter type. + * @param genericType the generic type to resolve + * @param typeVariableMap the TypeVariable Map to resolved against + * @return the resolved raw type + */ + static Type getRawType(Type genericType, Map typeVariableMap) { + Type resolvedType = genericType; + if (genericType instanceof TypeVariable) { + TypeVariable tv = (TypeVariable) genericType; + resolvedType = (Type) typeVariableMap.get(tv); + if (resolvedType == null) { + resolvedType = extractBoundForTypeVariable(tv); + } + } + if (resolvedType instanceof ParameterizedType) { + return ((ParameterizedType) resolvedType).getRawType(); + } + else { + return resolvedType; + } + } + + /** + * Build a mapping of {@link TypeVariable#getName TypeVariable names} to concrete + * {@link Class} for the specified {@link Class}. Searches all super types, + * enclosing types and interfaces. + */ + static Map getTypeVariableMap(Class clazz) { + Map typeVariableMap = (Map) typeVariableCache.get(clazz); + + if (typeVariableMap == null) { + typeVariableMap = new HashMap(); + + // interfaces + extractTypeVariablesFromGenericInterfaces(clazz.getGenericInterfaces(), typeVariableMap); + + // super class + Type genericType = clazz.getGenericSuperclass(); + Class type = clazz.getSuperclass(); + while (type != null && !Object.class.equals(type)) { + if (genericType instanceof ParameterizedType) { + ParameterizedType pt = (ParameterizedType) genericType; + populateTypeMapFromParameterizedType(pt, typeVariableMap); + } + extractTypeVariablesFromGenericInterfaces(type.getGenericInterfaces(), typeVariableMap); + genericType = type.getGenericSuperclass(); + type = type.getSuperclass(); + } + + // enclosing class + type = clazz; + while (type.isMemberClass()) { + genericType = type.getGenericSuperclass(); + if (genericType instanceof ParameterizedType) { + ParameterizedType pt = (ParameterizedType) genericType; + populateTypeMapFromParameterizedType(pt, typeVariableMap); + } + type = type.getEnclosingClass(); + } + + typeVariableCache.put(clazz, typeVariableMap); + } + + return typeVariableMap; + } + + /** + * Extracts the bound Type for a given {@link TypeVariable}. + */ + static Type extractBoundForTypeVariable(TypeVariable typeVariable) { + Type[] bounds = typeVariable.getBounds(); + if (bounds.length == 0) { + return Object.class; + } + Type bound = bounds[0]; + if (bound instanceof TypeVariable) { + bound = extractBoundForTypeVariable((TypeVariable) bound); + } + return bound; + } + + private static void extractTypeVariablesFromGenericInterfaces(Type[] genericInterfaces, Map typeVariableMap) { + for (int i = 0; i < genericInterfaces.length; i++) { + Type genericInterface = genericInterfaces[i]; + if (genericInterface instanceof ParameterizedType) { + ParameterizedType pt = (ParameterizedType) genericInterface; + populateTypeMapFromParameterizedType(pt, typeVariableMap); + if (pt.getRawType() instanceof Class) { + extractTypeVariablesFromGenericInterfaces( + ((Class) pt.getRawType()).getGenericInterfaces(), typeVariableMap); + } + } + else if (genericInterface instanceof Class) { + extractTypeVariablesFromGenericInterfaces( + ((Class) genericInterface).getGenericInterfaces(), typeVariableMap); + } + } + } + + /** + * Read the {@link TypeVariable TypeVariables} from the supplied {@link ParameterizedType} + * and add mappings corresponding to the {@link TypeVariable#getName TypeVariable name} -> + * concrete type to the supplied {@link Map}. + *

    Consider this case: + *